HEX
Server: nginx/1.28.3
System: Linux VM-0-7-opencloudos 6.6.117-45.oc9.x86_64 #1 SMP Thu Dec 4 10:26:39 CST 2025 x86_64
User: www (1000)
PHP: 8.2.28
Disabled: passthru,exec,system,putenv,chroot,chgrp,chown,shell_exec,popen,proc_open,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv
Upload Files
File: /www/wwwroot/www.213n.cn/wp-content/plugins/wpturbo/vendor/BaiduBce.phar
<?php
Phar::mapPhar('BaiduBce.phar');
require 'phar://BaiduBce.phar/index.php';
__HALT_COMPILER(); ?>
�i
BaiduBce.phar	index.php���c��Y� vendor/myclabs/deep-copy/LICENSE5��c5ʭ˄�"vendor/myclabs/deep-copy/README.mdS%��cS%���v�,vendor/myclabs/deep-copy/.github/FUNDING.yml���c�7S	��2vendor/myclabs/deep-copy/.github/workflows/ci.yaml�
��c�
5� J�&vendor/myclabs/deep-copy/composer.json���c��盵�3vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php���c�"e��Avendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyMatcher.php���c�?S�b�Ovendor/myclabs/deep-copy/src/DeepCopy/Matcher/Doctrine/DoctrineProxyMatcher.phph��chL�b�9vendor/myclabs/deep-copy/src/DeepCopy/Matcher/Matcher.php���c�q�e�Evendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php���c�Y��x�Evendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php$��c$3!�*�2vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.phpZ��cZ���r�>vendor/myclabs/deep-copy/src/DeepCopy/Filter/ReplaceFilter.php���c�a�˲�;vendor/myclabs/deep-copy/src/DeepCopy/Filter/KeepFilter.php��c����Wvendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php���c���7ߤRvendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineCollectionFilter.php��c�:D�Mvendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineProxyFilter.php���c���7vendor/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php\��c\6S���>vendor/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php���c�]��]�Avendor/myclabs/deep-copy/src/DeepCopy/TypeMatcher/TypeMatcher.php���c�s�w֤Bvendor/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php��cL��t�Evendor/myclabs/deep-copy/src/DeepCopy/Exception/PropertyException.phpx��cx�4��Evendor/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php~��c~:�̤Bvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php��c7���Rvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/SplDoublyLinkedListFilter.php��cJ�霤Lvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/SplDoublyLinkedList.php���c���̤Jvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/ArrayObjectFilter.php���c�0�)�Lvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Date/DateIntervalFilter.php��cGF�ФFvendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php���c���Z٤?vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php���c��-h�vendor/autoload.php��c��[��vendor/bin/phpunitl��cl_��&vendor/theseer/tokenizer/composer.lock���c����� vendor/theseer/tokenizer/LICENSE���c��R(�%vendor/theseer/tokenizer/CHANGELOG.mdS��cS�K)`�"vendor/theseer/tokenizer/README.md���c�Y�n�&vendor/theseer/tokenizer/composer.json2��c2�x�R�%vendor/theseer/tokenizer/.php_cs.dist�-��c�-_|k�&vendor/theseer/tokenizer/src/Token.php���c�K�>j�6vendor/theseer/tokenizer/src/NamespaceUriException.phpq��cq)0�U�9vendor/theseer/tokenizer/src/TokenCollectionException.phpt��ct��u�0vendor/theseer/tokenizer/src/TokenCollection.php���c�ӱ��*vendor/theseer/tokenizer/src/Tokenizer.phpm
��cm
^oڰ�.vendor/theseer/tokenizer/src/XMLSerializer.php���c���.��-vendor/theseer/tokenizer/src/NamespaceUri.phpS��cS����*vendor/theseer/tokenizer/src/Exception.phpf��cf����'vendor/composer/autoload_namespaces.php4��c4�I��vendor/composer/LICENSE.��c. ��vendor/composer/ClassLoader.php/@��c/@!mj�!vendor/composer/autoload_psr4.php��c<>��%vendor/composer/autoload_classmap.phpa���ca�o�Vz�"vendor/composer/platform_check.php���c���%��#vendor/composer/autoload_static.phpm��cmy��q�!vendor/composer/autoload_real.phpn��cn�E�2�vendor/composer/installed.jsonu��cu|ٓt�"vendor/composer/autoload_files.php���c�ک���%vendor/composer/InstalledVersions.php�:��c�:畎K�vendor/composer/installed.php:��c:�����$vendor/doctrine/instantiator/LICENSE$��c$
͂�.vendor/doctrine/instantiator/docs/en/index.rst���c�HX��0vendor/doctrine/instantiator/docs/en/sidebar.rst&��c&�v�&vendor/doctrine/instantiator/README.md+��c+�4@�,vendor/doctrine/instantiator/CONTRIBUTING.md��c�ﻦ�3vendor/doctrine/instantiator/.doctrine-project.json��cxxd�*vendor/doctrine/instantiator/composer.json��c��&vendor/doctrine/instantiator/psalm.xml���c���w�Gvendor/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.php���c�yaݤPvendor/doctrine/instantiator/src/Doctrine/Instantiator/InstantiatorInterface.php���c���.U�Wvendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/ExceptionInterface.php���c��f��]vendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/UnexpectedValueException.phpW��cW�z.��]vendor/doctrine/instantiator/src/Doctrine/Instantiator/Exception/InvalidArgumentException.php���c�$�8�$vendor/phpunit/php-timer/phpunit.xml���c�c�'� vendor/phpunit/php-timer/LICENSE��c]Ut��%vendor/phpunit/php-timer/ChangeLog.md���c�\��7�"vendor/phpunit/php-timer/build.xml���c�o(wc�,vendor/phpunit/php-timer/tests/TimerTest.php���c�P)�"vendor/phpunit/php-timer/README.md>��c>

v-�#vendor/phpunit/php-timer/.gitignore.��c.�Ol�,vendor/phpunit/php-timer/.github/FUNDING.yml��c1�S)�*vendor/phpunit/php-timer/.github/stale.yml���c���9�'vendor/phpunit/php-timer/.gitattributes��crsX�$vendor/phpunit/php-timer/.travis.yml|��c|�|,��&vendor/phpunit/php-timer/composer.json���c��n�%vendor/phpunit/php-timer/.php_cs.dist9��c9�[�T�1vendor/phpunit/php-timer/src/RuntimeException.php{��c{�%��&vendor/phpunit/php-timer/src/Timer.php�	��c�	:��(�*vendor/phpunit/php-timer/src/Exception.phpC��cC/u��'vendor/phpunit/php-token-stream/LICENSE��c�Z[{�,vendor/phpunit/php-token-stream/ChangeLog.md>��c>�s�)vendor/phpunit/php-token-stream/README.md���c�\���*vendor/phpunit/php-token-stream/.gitignore[��c[�b��.vendor/phpunit/php-token-stream/.gitattributes5��c5�u\b�-vendor/phpunit/php-token-stream/composer.json���c�xl�R�5vendor/phpunit/php-token-stream/src/CoalesceEqual.phpC��cC��6�,vendor/phpunit/php-token-stream/src/Goto.php9��c9��C�-vendor/phpunit/php-token-stream/src/Final.php:��c:S�|�/vendor/phpunit/php-token-stream/src/SrEqual.php=��c=�ՓW�1vendor/phpunit/php-token-stream/src/Ampersand.php>��c>�gPU�-vendor/phpunit/php-token-stream/src/Comma.php:��c:��	ؤ3vendor/phpunit/php-token-stream/src/DoubleArrow.phpA��cA���+vendor/phpunit/php-token-stream/src/For.php8��c8XZ�ޤ1vendor/phpunit/php-token-stream/src/Insteadof.php>��c>��)�0vendor/phpunit/php-token-stream/src/CloseTag.php>��c>�fh�,vendor/phpunit/php-token-stream/src/Plus.php9��c9�^�.vendor/phpunit/php-token-stream/src/Static.php;��c;D��P�0vendor/phpunit/php-token-stream/src/AndEqual.php>��c>��[�0vendor/phpunit/php-token-stream/src/Endwhile.php=��c=a��1vendor/phpunit/php-token-stream/src/NumString.php?��c?��ɇ�.vendor/phpunit/php-token-stream/src/Global.php;��c;R����2vendor/phpunit/php-token-stream/src/Enddeclare.php?��c?�,i٤6vendor/phpunit/php-token-stream/src/TokenWithScope.php��c�B�-vendor/phpunit/php-token-stream/src/Endif.php:��c:'Y�ˤ;vendor/phpunit/php-token-stream/src/PaamayimNekudotayim.phpI��cI��~��-vendor/phpunit/php-token-stream/src/Class.phpf��cf���y�*vendor/phpunit/php-token-stream/src/Lt.php7��c7Ny�0vendor/phpunit/php-token-stream/src/Callable.php=��c=�)���*vendor/phpunit/php-token-stream/src/As.php7��c790\��3vendor/phpunit/php-token-stream/src/DoubleColon.phpA��cA�qBe�0vendor/phpunit/php-token-stream/src/DivEqual.php>��c>����0vendor/phpunit/php-token-stream/src/Variable.php=��c=^~�ʤ-vendor/phpunit/php-token-stream/src/Const.php:��c:MѢ�0vendor/phpunit/php-token-stream/src/Continue.php=��c=�颤1vendor/phpunit/php-token-stream/src/LogicalOr.php?��c?��.vendor/phpunit/php-token-stream/src/Return.php;��c;'�p�-vendor/phpunit/php-token-stream/src/Yield.php:��c:�bJi�9vendor/phpunit/php-token-stream/src/ClassNameConstant.phpH��cHh.}��2vendor/phpunit/php-token-stream/src/Instanceof.php?��c?�7ͤ>vendor/phpunit/php-token-stream/src/ConstantEncapsedString.phpM��cMJ�q��/vendor/phpunit/php-token-stream/src/Include.phpE��cE�LY��-vendor/phpunit/php-token-stream/src/Token.php���c�
{㾤1vendor/phpunit/php-token-stream/src/Spaceship.php>��c>�?Gt�2vendor/phpunit/php-token-stream/src/DocComment.php@��c@���D�,vendor/phpunit/php-token-stream/src/Case.php9��c9�r�=�-vendor/phpunit/php-token-stream/src/Unset.php:��c:�€Ӥ/vendor/phpunit/php-token-stream/src/DNumber.php<��c<+�\��-vendor/phpunit/php-token-stream/src/Catch.php:��c:GL��,vendor/phpunit/php-token-stream/src/Eval.php9��c9�Wh�*vendor/phpunit/php-token-stream/src/At.php7��c7ND��4vendor/phpunit/php-token-stream/src/DoubleQuotes.phpB��cB��~��.vendor/phpunit/php-token-stream/src/Endfor.php;��c;uC�w�+vendor/phpunit/php-token-stream/src/Dot.php8��c8gC�{�/vendor/phpunit/php-token-stream/src/SlEqual.php=��c=��K��2vendor/phpunit/php-token-stream/src/Implements.php?��c?v�Ǥ6vendor/phpunit/php-token-stream/src/IsNotIdentical.phpE��cE��ӊ�1vendor/phpunit/php-token-stream/src/YieldFrom.php?��c?%��4vendor/phpunit/php-token-stream/src/StartHeredoc.phpB��cB���]�0vendor/phpunit/php-token-stream/src/Abstract.php=��c=��9�2vendor/phpunit/php-token-stream/src/DoubleCast.php@��c@֟T?�-vendor/phpunit/php-token-stream/src/Empty.php:��c:���N�2vendor/phpunit/php-token-stream/src/ObjectCast.php@��c@���*�3vendor/phpunit/php-token-stream/src/RequireOnce.phpJ��cJ��&�+vendor/phpunit/php-token-stream/src/Dir.php8��c8�}i��1vendor/phpunit/php-token-stream/src/ArrayCast.php?��c?Bf��:vendor/phpunit/php-token-stream/src/NameFullyQualified.phpI��cI�2vendor/phpunit/php-token-stream/src/CloseCurly.php@��c@'��}�1vendor/phpunit/php-token-stream/src/Endswitch.php>��c>�kUI�-vendor/phpunit/php-token-stream/src/FuncC.php;��c;3����,vendor/phpunit/php-token-stream/src/File.php9��c9|g;ݤ/vendor/phpunit/php-token-stream/src/OpenTag.php=��c=j�3�1vendor/phpunit/php-token-stream/src/Protected.php>��c>PEM/�1vendor/phpunit/php-token-stream/src/OpenCurly.php?��c?����1vendor/phpunit/php-token-stream/src/BooleanOr.php?��c?�����-vendor/phpunit/php-token-stream/src/Array.php:��c:C�1�8vendor/phpunit/php-token-stream/src/IsSmallerOrEqual.phpH��cH-�I�2vendor/phpunit/php-token-stream/src/LogicalAnd.php@��c@���1vendor/phpunit/php-token-stream/src/Interface.php���c�H���+vendor/phpunit/php-token-stream/src/Var.php8��c81�z3�0vendor/phpunit/php-token-stream/src/PowEqual.php>��c>����1vendor/phpunit/php-token-stream/src/CurlyOpen.php?��c?,��%�-vendor/phpunit/php-token-stream/src/Equal.php:��c:����0vendor/phpunit/php-token-stream/src/Function.php��cW��2vendor/phpunit/php-token-stream/src/IsNotEqual.phpA��cA%�{Ϥ2vendor/phpunit/php-token-stream/src/MinusEqual.php@��c@	Ƅä-vendor/phpunit/php-token-stream/src/Throw.php:��c:X�m�+vendor/phpunit/php-token-stream/src/NsC.php9��c90OO(�/vendor/phpunit/php-token-stream/src/Declare.php<��c<N����.vendor/phpunit/php-token-stream/src/Dollar.php;��c;(Ф*vendor/phpunit/php-token-stream/src/Do.php7��c77
:�*vendor/phpunit/php-token-stream/src/Gt.php7��c7�k���.vendor/phpunit/php-token-stream/src/TraitC.php<��c<龻S�.vendor/phpunit/php-token-stream/src/Public.php;��c;2���/vendor/phpunit/php-token-stream/src/Require.phpE��cE�h�Ƥ2vendor/phpunit/php-token-stream/src/BooleanAnd.php@��c@:�ڒ�4vendor/phpunit/php-token-stream/src/CloseBracket.phpB��cB��/)�+vendor/phpunit/php-token-stream/src/Div.php8��c8��oɤ*vendor/phpunit/php-token-stream/src/Sr.php7��c7-T�,vendor/phpunit/php-token-stream/src/Echo.php9��c9&�Gޤ-vendor/phpunit/php-token-stream/src/Clone.php:��c:/�<"�2vendor/phpunit/php-token-stream/src/LogicalXor.php@��c@�eJ��/vendor/phpunit/php-token-stream/src/Extends.php<��c<c3��+vendor/phpunit/php-token-stream/src/Dec.php8��c8Ǿ���-vendor/phpunit/php-token-stream/src/Colon.php:��c:�1gL�+vendor/phpunit/php-token-stream/src/Use.php8��c8�Z/G�,vendor/phpunit/php-token-stream/src/List.php9��c9գ��4vendor/phpunit/php-token-stream/src/HaltCompiler.phpB��cB!J{�.vendor/phpunit/php-token-stream/src/Stream.php}H��c}H`W3T�=vendor/phpunit/php-token-stream/src/DollarOpenCurlyBraces.phpM��cMۄ!פ-vendor/phpunit/php-token-stream/src/Print.php:��c:kłڤ*vendor/phpunit/php-token-stream/src/If.php7��c7�'�Cvendor/phpunit/php-token-stream/src/TokenWithScopeAndVisibility.php���c�i���3vendor/phpunit/php-token-stream/src/NsSeparator.phpA��cA��l�-vendor/phpunit/php-token-stream/src/Minus.php:��c:��XL�/vendor/phpunit/php-token-stream/src/IsEqual.php=��c=�,}�7vendor/phpunit/php-token-stream/src/OpenTagWithEcho.phpG��cG���y�2vendor/phpunit/php-token-stream/src/OpenSquare.php@��c@LƤ[�6vendor/phpunit/php-token-stream/src/ObjectOperator.phpD��cD�w���3vendor/phpunit/php-token-stream/src/OpenBracket.phpA��cAZ�A(�3vendor/phpunit/php-token-stream/src/UseFunction.phpA��cA9)�1vendor/phpunit/php-token-stream/src/Character.php>��c>�dQ��/vendor/phpunit/php-token-stream/src/Private.php<��c<���/�1vendor/phpunit/php-token-stream/src/UnsetCast.php?��c?]XqD�5vendor/phpunit/php-token-stream/src/StringVarname.phpC��cCc�C/�-vendor/phpunit/php-token-stream/src/Caret.php:��c:�+):�+vendor/phpunit/php-token-stream/src/Pow.php8��c8�'W��0vendor/phpunit/php-token-stream/src/Ellipsis.php=��c=I����*vendor/phpunit/php-token-stream/src/Fn.php7��c7jtI+�0vendor/phpunit/php-token-stream/src/XorEqual.php>��c>�_��1vendor/phpunit/php-token-stream/src/Namespace.php+��c+���7�5vendor/phpunit/php-token-stream/src/NameQualified.phpC��cC�1�x�.vendor/phpunit/php-token-stream/src/Switch.php;��c;�:Ħ�+vendor/phpunit/php-token-stream/src/Inc.php8��c8ֆ��/vendor/phpunit/php-token-stream/src/Foreach.php<��c<���/vendor/phpunit/php-token-stream/src/Comment.php<��c<����3vendor/phpunit/php-token-stream/src/IncludeOnce.phpJ��cJ�i3��+vendor/phpunit/php-token-stream/src/New.php8��c8v9�ߤ/vendor/phpunit/php-token-stream/src/IntCast.php=��c=���.vendor/phpunit/php-token-stream/src/String.php;��c;�i�(�2vendor/phpunit/php-token-stream/src/EndHeredoc.php@��c@�&�*vendor/phpunit/php-token-stream/src/Sl.php7��c7�ES�.vendor/phpunit/php-token-stream/src/ClassC.php<��c<��-��/vendor/phpunit/php-token-stream/src/OrEqual.php=��c=�M��,vendor/phpunit/php-token-stream/src/Exit.php9��c9�w���0vendor/phpunit/php-token-stream/src/Includes.php���c��(�^�8vendor/phpunit/php-token-stream/src/IsGreaterOrEqual.phpH��cH�VM�4vendor/phpunit/php-token-stream/src/NameRelative.phpB��cBI��ݤ,vendor/phpunit/php-token-stream/src/Util.php���c�<���0vendor/phpunit/php-token-stream/src/BoolCast.php>��c>�r��2vendor/phpunit/php-token-stream/src/Whitespace.php?��c?�X�
�,vendor/phpunit/php-token-stream/src/Else.php9��c9�2j�/vendor/phpunit/php-token-stream/src/Lnumber.php<��c<*�*��=vendor/phpunit/php-token-stream/src/EncapsedAndWhitespace.phpL��cLmx�[�3vendor/phpunit/php-token-stream/src/IsIdentical.phpA��cA��*��6vendor/phpunit/php-token-stream/src/CachingFactory.php���c�5_Gl�3vendor/phpunit/php-token-stream/src/ConcatEqual.phpA��cA�5�Ԥ+vendor/phpunit/php-token-stream/src/Try.php8��c8����-vendor/phpunit/php-token-stream/src/While.php:��c:"AM�4vendor/phpunit/php-token-stream/src/BadCharacter.phpB��cB vH�-vendor/phpunit/php-token-stream/src/break.php:��c:N.ä2vendor/phpunit/php-token-stream/src/InlineHtml.php@��c@Bxc��,vendor/phpunit/php-token-stream/src/Pipe.php9��c9�o���0vendor/phpunit/php-token-stream/src/MulEqual.php>��c>�\S{�1vendor/phpunit/php-token-stream/src/Semicolon.php>��c>��x��-vendor/phpunit/php-token-stream/src/Isset.php:��c:@�P�2vendor/phpunit/php-token-stream/src/StringCast.php@��c@�i�/vendor/phpunit/php-token-stream/src/Finally.php<��c<t�r��4vendor/phpunit/php-token-stream/src/QuestionMark.phpB��cB�M7L�,vendor/phpunit/php-token-stream/src/Mult.php9��c95f���2vendor/phpunit/php-token-stream/src/Endforeach.php?��c?�-��,vendor/phpunit/php-token-stream/src/Line.php9��c9)��R�7vendor/phpunit/php-token-stream/src/ExclamationMark.phpE��cE�m<	�/vendor/phpunit/php-token-stream/src/MethodC.php=��c=��g��/vendor/phpunit/php-token-stream/src/Default.php<��c<j\�U�-vendor/phpunit/php-token-stream/src/Trait.phpD��cD�M��0vendor/phpunit/php-token-stream/src/Coalesce.php=��c=_�^J�-vendor/phpunit/php-token-stream/src/Tilde.php:��c:���|�/vendor/phpunit/php-token-stream/src/Percent.php<��c<K�-.�.vendor/phpunit/php-token-stream/src/Elseif.php;��c;�4�w�0vendor/phpunit/php-token-stream/src/Backtick.php=��c=��r��1vendor/phpunit/php-token-stream/src/PlusEqual.php?��c?���6�3vendor/phpunit/php-token-stream/src/CloseSquare.phpA��cA
L��0vendor/phpunit/php-token-stream/src/ModEqual.php>��c>�X�Ǥ'vendor/phpunit/phpunit/ChangeLog-8.5.md�5��c�5��r��vendor/phpunit/phpunit/LICENSE���c���$��)vendor/phpunit/phpunit/.phpstorm.meta.php���c�O��� vendor/phpunit/phpunit/README.md�
��c�
��T�vendor/phpunit/phpunit/phpunit&	��c&	h����"vendor/phpunit/phpunit/phpunit.xsd�B��c�B2A[��$vendor/phpunit/phpunit/composer.json���c���C��"vendor/phpunit/phpunit/SECURITY.md���c���bF�3vendor/phpunit/phpunit/src/TextUI/ResultPrinter.php�;��c�;y)�2�0vendor/phpunit/phpunit/src/TextUI/TestRunner.phpc���cc��綤*vendor/phpunit/phpunit/src/TextUI/Help.php�1��c�1�lNF�-vendor/phpunit/phpunit/src/TextUI/Command.phpD���cD��Ulz�/vendor/phpunit/phpunit/src/TextUI/Exception.php���c��+J�5vendor/phpunit/phpunit/src/Util/RegularExpression.php���c�#�4�(vendor/phpunit/phpunit/src/Util/Type.php���c�dq
�(vendor/phpunit/phpunit/src/Util/Json.phpf��cfI���.vendor/phpunit/phpunit/src/Util/FileLoader.php�	��c�	�X��.vendor/phpunit/phpunit/src/Util/Filesystem.php'��c'����:vendor/phpunit/phpunit/src/Util/ConfigurationGenerator.php7��c7(q�-vendor/phpunit/phpunit/src/Util/Blacklist.php9��c9/NH8�*vendor/phpunit/phpunit/src/Util/Getopt.php.��c.eH� �.vendor/phpunit/phpunit/src/Util/Reflection.php���c�b�ƙ�'vendor/phpunit/phpunit/src/Util/Xml.php~#��c~#e]�7vendor/phpunit/phpunit/src/Util/Annotation/Registry.phph
��ch
T�s�7vendor/phpunit/phpunit/src/Util/Annotation/DocBlock.php�O��c�O��1vendor/phpunit/phpunit/src/Util/Configuration.php���c���2=�9vendor/phpunit/phpunit/src/Util/PHP/WindowsPhpProcess.php��ccϑ��:vendor/phpunit/phpunit/src/Util/PHP/AbstractPhpProcess.php�+��c�+w����?vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tplX��cX�b��=vendor/phpunit/phpunit/src/Util/PHP/Template/PhptTestCase.tplb��cb���̤>vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseClass.tpl	��c	-5���9vendor/phpunit/phpunit/src/Util/PHP/DefaultPhpProcess.php���c��L��=vendor/phpunit/phpunit/src/Util/VersionComparisonOperator.php���c����i�(vendor/phpunit/phpunit/src/Util/Test.php}x��c}x�����/vendor/phpunit/phpunit/src/Util/GlobalState.php��c�}.p�)vendor/phpunit/phpunit/src/Util/Color.php���c�tqHH�9vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php���c�vȲ��=vendor/phpunit/phpunit/src/Util/TestDox/HtmlResultPrinter.php$��c$V�Τ=vendor/phpunit/phpunit/src/Util/TestDox/TextResultPrinter.php$��c$zi>��<vendor/phpunit/phpunit/src/Util/TestDox/XmlResultPrinter.php���c�-�^�=vendor/phpunit/phpunit/src/Util/TestDox/CliTestDoxPrinter.phpO+��cO+9�͉�:vendor/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php�"��c�"��TQ�:vendor/phpunit/phpunit/src/Util/TestDox/TestDoxPrinter.php?*��c?*BN�$�*vendor/phpunit/phpunit/src/Util/Filter.php@
��c@
[��C�7vendor/phpunit/phpunit/src/Util/XmlTestListRenderer.php�
��c�
�4�/�;vendor/phpunit/phpunit/src/Util/InvalidDataSetException.php���c����X�0vendor/phpunit/phpunit/src/Util/Log/TeamCity.php{)��c{)7��S�-vendor/phpunit/phpunit/src/Util/Log/JUnit.php,.��c,. ��0vendor/phpunit/phpunit/src/Util/ErrorHandler.php���c�T��-vendor/phpunit/phpunit/src/Util/Exception.php���c�.��2�+vendor/phpunit/phpunit/src/Util/Printer.php���c��B!B�?vendor/phpunit/phpunit/src/Util/XdebugFilterScriptGenerator.php���c�"e@��8vendor/phpunit/phpunit/src/Util/TextTestListRenderer.php���c���ͤ5vendor/phpunit/phpunit/src/Framework/TestListener.php ��c ,JWL�3vendor/phpunit/phpunit/src/Framework/TestResult.php)���c)�oȱf�Jvendor/phpunit/phpunit/src/Framework/TestListenerDefaultImplementation.php���c��\n��:vendor/phpunit/phpunit/src/Framework/TestSuiteIterator.php���c����!�2vendor/phpunit/phpunit/src/Framework/TestSuite.php#X��c#X�&r��7vendor/phpunit/phpunit/src/Framework/SelfDescribing.php��c�F��7vendor/phpunit/phpunit/src/Framework/IncompleteTest.php���c�#9d��4vendor/phpunit/phpunit/src/Framework/TestBuilder.php���c��c�¤9vendor/phpunit/phpunit/src/Framework/ExceptionWrapper.php���c��:#��Gvendor/phpunit/phpunit/src/Framework/InvalidParameterGroupException.php���c�}��#�9vendor/phpunit/phpunit/src/Framework/Assert/Functions.php�y��c�y�K֤>vendor/phpunit/phpunit/src/Framework/DataProviderTestSuite.php���c�PP�/vendor/phpunit/phpunit/src/Framework/Assert.php\���c\�5���4vendor/phpunit/phpunit/src/Framework/SkippedTest.php���c�)ً�-vendor/phpunit/phpunit/src/Framework/Test.php��c�8�=vendor/phpunit/phpunit/src/Framework/MockObject/MockClass.php���c��
:8�Hvendor/phpunit/phpunit/src/Framework/MockObject/MethodNameConstraint.php,��c,9�ܤ>vendor/phpunit/phpunit/src/Framework/MockObject/MockObject.php
��c
�r��<vendor/phpunit/phpunit/src/Framework/MockObject/MockType.php���c��'�5�>vendor/phpunit/phpunit/src/Framework/MockObject/Invocation.phpm��cmZ���?vendor/phpunit/phpunit/src/Framework/MockObject/MockBuilder.php�+��c�+E"饤Avendor/phpunit/phpunit/src/Framework/MockObject/MockMethodSet.php��c�Tp_�Cvendor/phpunit/phpunit/src/Framework/MockObject/Rule/MethodName.php���c�W�ᠤNvendor/phpunit/phpunit/src/Framework/MockObject/Rule/ConsecutiveParameters.phpz��cz멹��Gvendor/phpunit/phpunit/src/Framework/MockObject/Rule/ParametersRule.php���c���B��Hvendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvocationOrder.php���c����ȤHvendor/phpunit/phpunit/src/Framework/MockObject/Rule/AnyInvokedCount.phpD��cDM���Kvendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastOnce.php&��c&�W�Y�Fvendor/phpunit/phpunit/src/Framework/MockObject/Rule/AnyParameters.php���c���;��Kvendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtMostCount.php���c���l�Gvendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtIndex.php���c���Q�Lvendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastCount.php���c���Cvendor/phpunit/phpunit/src/Framework/MockObject/Rule/Parameters.php3��c3�=�u�Evendor/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedCount.phpP
��cP
���j�Kvendor/phpunit/phpunit/src/Framework/MockObject/Generator/mocked_method.tplM��cM�7i�Jvendor/phpunit/phpunit/src/Framework/MockObject/Generator/mocked_class.tpl���c��wZ�Ivendor/phpunit/phpunit/src/Framework/MockObject/Generator/wsdl_method.tpl<��c<��i��Lvendor/phpunit/phpunit/src/Framework/MockObject/Generator/proxied_method.tpl���c��񻕤Hvendor/phpunit/phpunit/src/Framework/MockObject/Generator/wsdl_class.tpl���c�����Ivendor/phpunit/phpunit/src/Framework/MockObject/Generator/trait_class.tplQ��cQ�<�ȤQvendor/phpunit/phpunit/src/Framework/MockObject/Generator/proxied_method_void.tpl}��c}&����Ivendor/phpunit/phpunit/src/Framework/MockObject/Generator/deprecation.tpl;��c;O5�s�Rvendor/phpunit/phpunit/src/Framework/MockObject/Generator/mocked_static_method.tpl���c� 4�R�Pvendor/phpunit/phpunit/src/Framework/MockObject/Generator/mocked_method_void.tpl��c �ΤFvendor/phpunit/phpunit/src/Framework/MockObject/ConfigurableMethod.php���c����;vendor/phpunit/phpunit/src/Framework/MockObject/Matcher.php��cN=)��Cvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnStub.php���c���
�Ivendor/phpunit/phpunit/src/Framework/MockObject/Stub/ConsecutiveCalls.php���c��53��Gvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnArgument.php���c���ŤHvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnReference.php��c�V��Gvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnValueMap.php���c�UG��Gvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnCallback.php:��c:�ߤCvendor/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnSelf.php��c��	�=vendor/phpunit/phpunit/src/Framework/MockObject/Stub/Stub.php2��c27�c�Bvendor/phpunit/phpunit/src/Framework/MockObject/Stub/Exception.php��c�P<פ>vendor/phpunit/phpunit/src/Framework/MockObject/Api/Method.php���c����;vendor/phpunit/phpunit/src/Framework/MockObject/Api/Api.php���c�F��8vendor/phpunit/phpunit/src/Framework/MockObject/Stub.php���c��Pl?�>vendor/phpunit/phpunit/src/Framework/MockObject/MockMethod.php/��c/b�^n�=vendor/phpunit/phpunit/src/Framework/MockObject/Generator.php����c���(�7�Evendor/phpunit/phpunit/src/Framework/MockObject/InvocationHandler.php��c�H�Mvendor/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationStubber.php���c������Lvendor/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationMocker.php���c���ʤKvendor/phpunit/phpunit/src/Framework/MockObject/Builder/ParametersMatch.php���c�#A�i�Dvendor/phpunit/phpunit/src/Framework/MockObject/Builder/Identity.php���c���}"�@vendor/phpunit/phpunit/src/Framework/MockObject/Builder/Stub.php���c��?��Bvendor/phpunit/phpunit/src/Framework/MockObject/Builder/Match_.php���c�a���Kvendor/phpunit/phpunit/src/Framework/MockObject/Builder/MethodNameMatch.phpO��cO�}l2�lvendor/phpunit/phpunit/src/Framework/MockObject/Exception/ConfigurableMethodsAlreadyInitializedException.php��c�}-�Nvendor/phpunit/phpunit/src/Framework/MockObject/Exception/RuntimeException.php���c�"bB��^vendor/phpunit/phpunit/src/Framework/MockObject/Exception/IncompatibleReturnValueException.php���c�t���Tvendor/phpunit/phpunit/src/Framework/MockObject/Exception/BadMethodCallException.php���c����i�Gvendor/phpunit/phpunit/src/Framework/MockObject/Exception/Exception.php���c�N�,�>vendor/phpunit/phpunit/src/Framework/MockObject/Verifiable.php���c���/v�=vendor/phpunit/phpunit/src/Framework/MockObject/MockTrait.php���c���U��6vendor/phpunit/phpunit/src/Framework/Error/Warning.phpG��cG��}�4vendor/phpunit/phpunit/src/Framework/Error/Error.phpW��cW �uͤ5vendor/phpunit/phpunit/src/Framework/Error/Notice.phpF��cF�"o��9vendor/phpunit/phpunit/src/Framework/Error/Deprecated.phpJ��cJ����1vendor/phpunit/phpunit/src/Framework/TestCase.php�6��c�6�.�ݤ:vendor/phpunit/phpunit/src/Framework/Exception/Warning.phpc��cc �J�Rvendor/phpunit/phpunit/src/Framework/Exception/UnintentionallyCoveredCodeError.php���c�i�t�Mvendor/phpunit/phpunit/src/Framework/Exception/ExpectationFailedException.php���c�Ky�äHvendor/phpunit/phpunit/src/Framework/Exception/SyntheticSkippedError.php���c���ӏ�Hvendor/phpunit/phpunit/src/Framework/Exception/SkippedTestSuiteError.php���c�f���>vendor/phpunit/phpunit/src/Framework/Exception/OutputError.php���c���:t�Fvendor/phpunit/phpunit/src/Framework/Exception/IncompleteTestError.php���c��)R�Avendor/phpunit/phpunit/src/Framework/Exception/RiskyTestError.php���c�9�d��Cvendor/phpunit/phpunit/src/Framework/Exception/SkippedTestError.php���c�=�@��Avendor/phpunit/phpunit/src/Framework/Exception/SyntheticError.php&��c&i�٤Kvendor/phpunit/phpunit/src/Framework/Exception/PHPTAssertionFailedError.php ��c >��G�Hvendor/phpunit/phpunit/src/Framework/Exception/CodeCoverageException.php���c�<߆]�Rvendor/phpunit/phpunit/src/Framework/Exception/CoveredCodeNotExecutedException.php���c��p��Kvendor/phpunit/phpunit/src/Framework/Exception/InvalidArgumentException.php��c
%��Lvendor/phpunit/phpunit/src/Framework/Exception/NoChildTestSuiteException.php���c���]N�Ovendor/phpunit/phpunit/src/Framework/Exception/InvalidDataProviderException.php���c����R�Ovendor/phpunit/phpunit/src/Framework/Exception/InvalidCoversTargetException.php���c��U���Svendor/phpunit/phpunit/src/Framework/Exception/MissingCoversAnnotationException.php���c�1�Ȥ<vendor/phpunit/phpunit/src/Framework/Exception/Exception.php�	��c�	���Gvendor/phpunit/phpunit/src/Framework/Exception/AssertionFailedError.phpj��cj�ZY��8vendor/phpunit/phpunit/src/Framework/WarningTestCase.php���c�'b�Evendor/phpunit/phpunit/src/Framework/Constraint/RegularExpression.phpc��cc�X�ؤ@vendor/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.php���c����a�Pvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContainsIdentical.php���c����>vendor/phpunit/phpunit/src/Framework/Constraint/IsReadable.php���c�/�KH�;vendor/phpunit/phpunit/src/Framework/Constraint/IsFalse.php1��c1���<vendor/phpunit/phpunit/src/Framework/Constraint/LessThan.php���c��
4�Uvendor/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegularExpression.php���c����ĤCvendor/phpunit/phpunit/src/Framework/Constraint/DirectoryExists.php���c���=vendor/phpunit/phpunit/src/Framework/Constraint/LogicalOr.php�
��c�
�o��>vendor/phpunit/phpunit/src/Framework/Constraint/IsAnything.php ��c �}~��Dvendor/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.phpn��cn��Kvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php���c��MI��Kvendor/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.phpM��cM�,D�:vendor/phpunit/phpunit/src/Framework/Constraint/IsTrue.php-��c-�2Đ�>vendor/phpunit/phpunit/src/Framework/Constraint/LogicalAnd.php���c�ݓu�?vendor/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.php.��c.��h�=vendor/phpunit/phpunit/src/Framework/Constraint/Composite.phpe��ce�	�Dvendor/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php��cG{��:vendor/phpunit/phpunit/src/Framework/Constraint/IsJson.phpk��ck��	Ť?vendor/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php���c��1���=vendor/phpunit/phpunit/src/Framework/Constraint/Attribute.php���c�Yc�ä>vendor/phpunit/phpunit/src/Framework/Constraint/LogicalXor.phpn��cnr8��:vendor/phpunit/phpunit/src/Framework/Constraint/IsType.php���c�0�sv�;vendor/phpunit/phpunit/src/Framework/Constraint/IsEmpty.php���c��Q\`�Gvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContains.phpo
��co
�pE��;vendor/phpunit/phpunit/src/Framework/Constraint/IsEqual.php���c���s�Rvendor/phpunit/phpunit/src/Framework/Constraint/StringMatchesFormatDescription.php��co|2"�9vendor/phpunit/phpunit/src/Framework/Constraint/IsNan.php?��c?ʹ�d�Evendor/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php
	��c
	��>vendor/phpunit/phpunit/src/Framework/Constraint/Constraint.phpd��cdZ��4�9vendor/phpunit/phpunit/src/Framework/Constraint/Count.phpR��cR���Lvendor/phpunit/phpunit/src/Framework/Constraint/TraversableContainsEqual.php	��c	5_+�Fvendor/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.phpb��cb��t`�>vendor/phpunit/phpunit/src/Framework/Constraint/IsInfinite.phpX��cX�L]{�Bvendor/phpunit/phpunit/src/Framework/Constraint/StringContains.php,��c,��^�?vendor/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php���c���p��Svendor/phpunit/phpunit/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php	��c	1��u�:vendor/phpunit/phpunit/src/Framework/Constraint/IsNull.php-��c-ɭw��?vendor/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php���c���<vendor/phpunit/phpunit/src/Framework/Constraint/SameSize.php���c��i*��=vendor/phpunit/phpunit/src/Framework/Constraint/Exception.php��cn�~��>vendor/phpunit/phpunit/src/Framework/Constraint/IsWritable.php���c�g�¤Avendor/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.php`��c`p��<vendor/phpunit/phpunit/src/Framework/Constraint/Callback.php���c��𐶤>vendor/phpunit/phpunit/src/Framework/Constraint/LogicalNot.php=��c=;��?vendor/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php���c���ǤBvendor/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.phpx��cxQg��<vendor/phpunit/phpunit/src/Framework/Constraint/IsFinite.phpN��cNI��>vendor/phpunit/phpunit/src/Framework/Constraint/FileExists.php���c�w��Ф;vendor/phpunit/phpunit/src/Framework/IncompleteTestCase.phpw��cw�i�E�4vendor/phpunit/phpunit/src/Framework/TestFailure.php5��c5_-�ͤ8vendor/phpunit/phpunit/src/Framework/SkippedTestCase.phpq��cq��ޢ�5vendor/phpunit/phpunit/src/Runner/TestResultCache.php���c��Y)ɤ4vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php���c�<����:vendor/phpunit/phpunit/src/Runner/ResultCacheExtension.phpP
��cP
���W�2vendor/phpunit/phpunit/src/Runner/PhptTestCase.php�X��c�X 	���=vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php��cu��-vendor/phpunit/phpunit/src/Runner/Version.phpD��cDDv��5vendor/phpunit/phpunit/src/Runner/TestSuiteLoader.php8��c8+�$ˤ<vendor/phpunit/phpunit/src/Runner/DefaultTestResultCache.php���c�*E��5vendor/phpunit/phpunit/src/Runner/TestSuiteSorter.php�4��c�4��p�4vendor/phpunit/phpunit/src/Runner/Filter/Factory.php���c�j9�z�Gvendor/phpunit/phpunit/src/Runner/Filter/IncludeGroupFilterIterator.phpX��cX�L"��@vendor/phpunit/phpunit/src/Runner/Filter/GroupFilterIterator.php���c�	��?vendor/phpunit/phpunit/src/Runner/Filter/NameFilterIterator.php*��c*d�C�Gvendor/phpunit/phpunit/src/Runner/Filter/ExcludeGroupFilterIterator.phpY��cYՂDä9vendor/phpunit/phpunit/src/Runner/NullTestResultCache.phpv��cvr��/vendor/phpunit/phpunit/src/Runner/Exception.php���c�k���=vendor/phpunit/phpunit/src/Runner/Hook/AfterRiskyTestHook.php���c�|�"8�?vendor/phpunit/phpunit/src/Runner/Hook/AfterSkippedTestHook.php���c�vW�w�=vendor/phpunit/phpunit/src/Runner/Hook/AfterTestErrorHook.php���c�Z���/vendor/phpunit/phpunit/src/Runner/Hook/Hook.php(��c(2�!ڤ9vendor/phpunit/phpunit/src/Runner/Hook/BeforeTestHook.php~��c~��S�>vendor/phpunit/phpunit/src/Runner/Hook/TestListenerAdapter.php(��c(��F�?vendor/phpunit/phpunit/src/Runner/Hook/AfterTestWarningHook.php���c�X�d��3vendor/phpunit/phpunit/src/Runner/Hook/TestHook.php9��c99�}�8vendor/phpunit/phpunit/src/Runner/Hook/AfterTestHook.phpR��cR�}(դ<vendor/phpunit/phpunit/src/Runner/Hook/AfterLastTestHook.phpt��ct��	�?vendor/phpunit/phpunit/src/Runner/Hook/AfterTestFailureHook.php���c�����>vendor/phpunit/phpunit/src/Runner/Hook/BeforeFirstTestHook.phpx��cx�Mw�Bvendor/phpunit/phpunit/src/Runner/Hook/AfterIncompleteTestHook.php���c��X%��Bvendor/phpunit/phpunit/src/Runner/Hook/AfterSuccessfulTestHook.php���c�N��(vendor/phpunit/phpunit/src/Exception.php���c�(3�E�(vendor/phpunit/php-text-template/LICENSE��cS�:��*vendor/phpunit/php-text-template/README.md���c�[���+vendor/phpunit/php-text-template/.gitignore.��c.�-�/vendor/phpunit/php-text-template/.gitattributes��crsX�.vendor/phpunit/php-text-template/composer.json���c�&�{֤1vendor/phpunit/php-text-template/src/Template.php���c��w4��,vendor/phpunit/php-code-coverage/phpunit.xml���c�
�T��(vendor/phpunit/php-code-coverage/LICENSE��c��IR�-vendor/phpunit/php-code-coverage/ChangeLog.md���c����r�*vendor/phpunit/php-code-coverage/build.xml��c�Y|o�;vendor/phpunit/php-code-coverage/tests/tests/FilterTest.php ��c �h�ä9vendor/phpunit/php-code-coverage/tests/tests/TextTest.php���c�wd>S�9vendor/phpunit/php-code-coverage/tests/tests/HTMLTest.php�
��c�
��Wä9vendor/phpunit/php-code-coverage/tests/tests/UtilTest.php���c��#���;vendor/phpunit/php-code-coverage/tests/tests/CloverTest.phpn��cnq^BǤAvendor/phpunit/php-code-coverage/tests/tests/CodeCoverageTest.php#��c#���Ҥ;vendor/phpunit/php-code-coverage/tests/tests/Crap4jTest.php���c��I�V�bvendor/phpunit/php-code-coverage/tests/tests/Exception/UnintentionallyCoveredCodeExceptionTest.php#��c#�>:��8vendor/phpunit/php-code-coverage/tests/tests/XmlTest.php���c�:�8s�<vendor/phpunit/php-code-coverage/tests/tests/BuilderTest.php$��c$����4vendor/phpunit/php-code-coverage/tests/bootstrap.php���c�]�ؤVvendor/phpunit/php-code-coverage/tests/_files/class-with-anonymous-function-crap4j.xml(��c(��l�Mvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoveragePublicTest.php��c�y�l�Gvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoveredClass.php[��c[F�
��Gvendor/phpunit/php-code-coverage/tests/_files/source_with_namespace.php���c��I�Yvendor/phpunit/php-code-coverage/tests/_files/CoverageMethodParenthesesWhitespaceTest.php��c4�K�Bvendor/phpunit/php-code-coverage/tests/_files/CoverageNoneTest.php���c��>5�Lvendor/phpunit/php-code-coverage/tests/_files/source_with_use_statements.php���c��6��Avendor/phpunit/php-code-coverage/tests/_files/CoveredFunction.php$��c$�Y�Jvendor/phpunit/php-code-coverage/tests/_files/CoverageNotProtectedTest.php��c��XE�Rvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageCoversClassTest.php��c�Q~�Bvendor/phpunit/php-code-coverage/tests/_files/BankAccount-text.txt���c�<���Svendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageNotProtectedTest.php��ce�鵤Nvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoveragePrivateTest.php	��c	�ɶ4�Tvendor/phpunit/php-code-coverage/tests/_files/class-with-anonymous-function-text.txt���c����Qvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageNotPrivateTest.php
��c
�i��Qvendor/phpunit/php-code-coverage/tests/_files/source_with_oneline_annotations.php��c�r#�Evendor/phpunit/php-code-coverage/tests/_files/CoveragePrivateTest.php���c��c5}�Ovendor/phpunit/php-code-coverage/tests/_files/NotExistingCoveredElementTest.php���c�&�=G�Qvendor/phpunit/php-code-coverage/tests/_files/CoverageFunctionParenthesesTest.php���c��O�d�Dvendor/phpunit/php-code-coverage/tests/_files/CoveragePublicTest.php���c��W�p�Dvendor/phpunit/php-code-coverage/tests/_files/ignored-lines-text.txtw��cw�r��Tvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageClassExtendedTest.php��ca�*s�Pvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageProtectedTest.php
��c
��1�Dvendor/phpunit/php-code-coverage/tests/_files/BankAccount-crap4j.xmlF��cF�K��Tvendor/phpunit/php-code-coverage/tests/_files/CoverageTwoDefaultClassAnnotations.phpJ��cJ�ԤFvendor/phpunit/php-code-coverage/tests/_files/ignored-lines-clover.xmlb��cb��,ۤGvendor/phpunit/php-code-coverage/tests/_files/CoverageProtectedTest.php���c�`��Hvendor/phpunit/php-code-coverage/tests/_files/CoverageNotPrivateTest.php���c���e^�Evendor/phpunit/php-code-coverage/tests/_files/CoverageNothingTest.php��c��>�Dvendor/phpunit/php-code-coverage/tests/_files/CoverageMethodTest.php���c����Pvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageNotPublicTest.php��c��(ޤJvendor/phpunit/php-code-coverage/tests/_files/source_without_namespace.php���c�V�� �Gvendor/phpunit/php-code-coverage/tests/_files/CoverageNotPublicTest.php���c�͞�פOvendor/phpunit/php-code-coverage/tests/_files/CoverageMethodParenthesesTest.php��c7	���7vendor/phpunit/php-code-coverage/tests/_files/Crash.php��cy"�ϤDvendor/phpunit/php-code-coverage/tests/_files/BankAccount-clover.xml���c�SԷ�Xvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageCoversClassPublicTest.php7��c7lM}_�Fvendor/phpunit/php-code-coverage/tests/_files/ignored-lines-crap4j.xml��c/# ��Cvendor/phpunit/php-code-coverage/tests/_files/CoverageClassTest.php���c��8���Kvendor/phpunit/php-code-coverage/tests/_files/CoverageClassExtendedTest.php���c�0�U��Gvendor/phpunit/php-code-coverage/tests/_files/source_without_ignore.php,��c,[�6p�Fvendor/phpunit/php-code-coverage/tests/_files/CoverageFunctionTest.php���c�5�?�Vvendor/phpunit/php-code-coverage/tests/_files/class-with-anonymous-function-clover.xml8��c8�#O�dvendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForFileWithIgnoredLines/index.html���c�Dc��hvendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForFileWithIgnoredLines/dashboard.html���c���K��uvendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForFileWithIgnoredLines/source_with_ignore.php.htmlx6��cx6c�?դ[vendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForBankAccount/index.html%��c%�Gl�_vendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForBankAccount/dashboard.html���c�u��c�evendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForBankAccount/BankAccount.php.htmlVR��cVR����jvendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForClassWithAnonymousFunction/index.htmlW��cWL[�nvendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForClassWithAnonymousFunction/dashboard.html$��c$�:���vendor/phpunit/php-code-coverage/tests/_files/Report/HTML/CoverageForClassWithAnonymousFunction/source_with_class_and_anonymous_function.php.html5��c5a(�~�bvendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForFileWithIgnoredLines/index.xml���c���svendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForFileWithIgnoredLines/source_with_ignore.php.xml��c&�x��Yvendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForBankAccount/index.xml��c���cvendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForBankAccount/BankAccount.php.xmlr)��cr)��<��hvendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForClassWithAnonymousFunction/index.xml���c��ρ��vendor/phpunit/php-code-coverage/tests/_files/Report/XML/CoverageForClassWithAnonymousFunction/source_with_class_and_anonymous_function.php.xml
��c
mQ'�Mvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageMethodTest.php��c��Kh�Uvendor/phpunit/php-code-coverage/tests/_files/CoverageMethodOneLineAnnotationTest.php���c���A�Avendor/phpunit/php-code-coverage/tests/_files/BankAccountTest.php���c�`�S�[vendor/phpunit/php-code-coverage/tests/_files/CoverageFunctionParenthesesWhitespaceTest.php���c���CΤ=vendor/phpunit/php-code-coverage/tests/_files/BankAccount.phpv��cvwi�Lvendor/phpunit/php-code-coverage/tests/_files/NamespaceCoverageClassTest.php���c��YJ�>vendor/phpunit/php-code-coverage/tests/_files/CoveredClass.phpK��cKo���Dvendor/phpunit/php-code-coverage/tests/_files/source_with_ignore.php���c����|�Zvendor/phpunit/php-code-coverage/tests/_files/source_with_class_and_anonymous_function.php���c���ܤ3vendor/phpunit/php-code-coverage/tests/TestCase.php+��c+�b*�*vendor/phpunit/php-code-coverage/README.mdp��cpQ����+vendor/phpunit/php-code-coverage/.gitignore_��c_G�_�4vendor/phpunit/php-code-coverage/.github/FUNDING.yml��cô�:vendor/phpunit/php-code-coverage/.github/ISSUE_TEMPLATE.md���c���C�8vendor/phpunit/php-code-coverage/.github/CONTRIBUTING.md���c�nq6�/vendor/phpunit/php-code-coverage/.gitattributes%��c%�Ąr�*vendor/phpunit/php-code-coverage/phive.xml���c�I��(�,vendor/phpunit/php-code-coverage/.travis.yml���c�b�Ť.vendor/phpunit/php-code-coverage/composer.jsonR��cR����-vendor/phpunit/php-code-coverage/.php_cs.distK��cK[����5vendor/phpunit/php-code-coverage/src/CodeCoverage.phpGr��cGrxnRΤ4vendor/phpunit/php-code-coverage/src/Driver/PCOV.php���c�N�=�6vendor/phpunit/php-code-coverage/src/Driver/Driver.php��cN���6vendor/phpunit/php-code-coverage/src/Driver/PHPDBG.php�
��c�
d���6vendor/phpunit/php-code-coverage/src/Driver/Xdebug.phpM��cMK=٤0vendor/phpunit/php-code-coverage/src/Version.php���c�ı_q�/vendor/phpunit/php-code-coverage/src/Filter.phpE��cER}��6vendor/phpunit/php-code-coverage/src/Report/Clover.php�)��c�)DQ���Gvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Dashboard.phpp%��cp%��)��Bvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/File.php�I��c�I9�j�Vvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/dashboard.html.distG��cG��l�Yvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/coverage_bar.html.dist'��c'�O}�Xvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/css/bootstrap.min.cssn`��cn`�ӤQvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/css/custom.css��c�Tvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/css/nv.d3.min.cssX%��cX%�0,�Svendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/css/octicons.cssX��cX'#��Pvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/css/style.css���c���v�Qvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/file.html.dist
��c
�f
"�Vvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/file_item.html.distt��ct���Xvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/method_item.html.dist���c���s:�Rvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/nv.d3.min.js�R��c�R<Ms�Ovendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/d3.min.js�P��c�P�h�b�Svendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/jquery.min.jsQX��cQXQ��[�Vvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/bootstrap.min.js����c��'�^�Mvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/file.js���c�b�䆤Svendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/js/popper.min.js�R��c�RZ�\�[vendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/icons/file-directory.svg���c���Z��Vvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/icons/file-code.svg0��c0�QUU�[vendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/directory_item.html.distA��cAds�Vvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Template/directory.html.dist���c�G�M��Gvendor/phpunit/php-code-coverage/src/Report/Html/Renderer/Directory.php�
��c�
�c�~�=vendor/phpunit/php-code-coverage/src/Report/Html/Renderer.php�!��c�!�\x?�;vendor/phpunit/php-code-coverage/src/Report/Html/Facade.phpO��cO�lN�:vendor/phpunit/php-code-coverage/src/Report/Xml/Totals.php0��c0Z�h�8vendor/phpunit/php-code-coverage/src/Report/Xml/File.php���c���-ä:vendor/phpunit/php-code-coverage/src/Report/Xml/Method.php���c�3�1�8vendor/phpunit/php-code-coverage/src/Report/Xml/Unit.php�
��c�
m�lؤ9vendor/phpunit/php-code-coverage/src/Report/Xml/Tests.php���c�Q�l�;vendor/phpunit/php-code-coverage/src/Report/Xml/Project.php=	��c=	\�и�8vendor/phpunit/php-code-coverage/src/Report/Xml/Node.phpf��cf�aD��=vendor/phpunit/php-code-coverage/src/Report/Xml/Directory.phpp��cp �hˤ<vendor/phpunit/php-code-coverage/src/Report/Xml/Coverage.php���c�*'mc�:vendor/phpunit/php-code-coverage/src/Report/Xml/Source.php��cv��]�Dvendor/phpunit/php-code-coverage/src/Report/Xml/BuildInformation.php�	��c�	��X�:vendor/phpunit/php-code-coverage/src/Report/Xml/Report.php�	��c�	ۈ�|�:vendor/phpunit/php-code-coverage/src/Report/Xml/Facade.php� ��c� )"���3vendor/phpunit/php-code-coverage/src/Report/PHP.phpl��cl5^�-�4vendor/phpunit/php-code-coverage/src/Report/Text.phpk"��ck"�>�ܤ6vendor/phpunit/php-code-coverage/src/Report/Crap4j.phpv��cv�.�(�-vendor/phpunit/php-code-coverage/src/Util.phpf��cfQ9r�2vendor/phpunit/php-code-coverage/src/Node/File.php8@��c8@�l�5vendor/phpunit/php-code-coverage/src/Node/Builder.php���c�a6�Ҥ:vendor/phpunit/php-code-coverage/src/Node/AbstractNode.phpN��cNH�ʤ7vendor/phpunit/php-code-coverage/src/Node/Directory.phpq$��cq$nr)ä6vendor/phpunit/php-code-coverage/src/Node/Iterator.php:��c:�_�c�Vvendor/phpunit/php-code-coverage/src/Exception/UnintentionallyCoveredCodeException.phpM��cM)����Cvendor/phpunit/php-code-coverage/src/Exception/RuntimeException.php���c��bPD�Rvendor/phpunit/php-code-coverage/src/Exception/CoveredCodeNotExecutedException.php���c�X��Kvendor/phpunit/php-code-coverage/src/Exception/InvalidArgumentException.php��ce�Uu�Svendor/phpunit/php-code-coverage/src/Exception/MissingCoversAnnotationException.php���c�ʡ��<vendor/phpunit/php-code-coverage/src/Exception/Exception.php���c���~�,vendor/phpunit/php-file-iterator/phpunit.xml���c��􊓤(vendor/phpunit/php-file-iterator/LICENSE��cJ�U(�-vendor/phpunit/php-file-iterator/ChangeLog.md���c�U]]��6vendor/phpunit/php-file-iterator/tests/FactoryTest.php���c��AD�*vendor/phpunit/php-file-iterator/README.md;��c;"�䓤+vendor/phpunit/php-file-iterator/.gitignore7��c7	B�	�2vendor/phpunit/php-file-iterator/.github/stale.yml���c���9�/vendor/phpunit/php-file-iterator/.gitattributes��crsX�,vendor/phpunit/php-file-iterator/.travis.yml���c���z�.vendor/phpunit/php-file-iterator/composer.jsont��ct��-vendor/phpunit/php-file-iterator/.php_cs.dist���c��[�1�0vendor/phpunit/php-file-iterator/src/Factory.php���c���c�1vendor/phpunit/php-file-iterator/src/Iterator.phpR��cRlOD�/vendor/phpunit/php-file-iterator/src/Facade.php�	��c�	k*�̤%vendor/phar-io/manifest/composer.lock���c�� _�vendor/phar-io/manifest/LICENSE`��c`��p�$vendor/phar-io/manifest/CHANGELOG.md���c����!vendor/phar-io/manifest/README.md���c��Vh��%vendor/phar-io/manifest/composer.jsonj��cj�O聤,vendor/phar-io/manifest/src/values/Email.php9��c9�q�"�<vendor/phar-io/manifest/src/values/PhpVersionRequirement.php��c�d!�2vendor/phar-io/manifest/src/values/Application.php���c�Dh��Dvendor/phar-io/manifest/src/values/RequirementCollectionIterator.phpL��cL�#!0�?vendor/phar-io/manifest/src/values/AuthorCollectionIterator.php��c�#�Ф+vendor/phar-io/manifest/src/values/Type.php���c��4BJ�.vendor/phar-io/manifest/src/values/Library.php���c�����6vendor/phar-io/manifest/src/values/ApplicationName.phpP��cP��>vendor/phar-io/manifest/src/values/PhpExtensionRequirement.php���c�7
hD�/vendor/phar-io/manifest/src/values/Manifest.php
��c
-���*vendor/phar-io/manifest/src/values/Url.phpp��cpڤ:��<vendor/phar-io/manifest/src/values/RequirementCollection.php���c���蜤.vendor/phar-io/manifest/src/values/License.php���c�l��>�7vendor/phar-io/manifest/src/values/AuthorCollection.php���c���3�7vendor/phar-io/manifest/src/values/BundledComponent.php*��c*J<KǤ0vendor/phar-io/manifest/src/values/Extension.phpx��cx��TK�Ivendor/phar-io/manifest/src/values/BundledComponentCollectionIterator.php���c�
Gף�;vendor/phar-io/manifest/src/values/CopyrightInformation.php>��c>:��[�-vendor/phar-io/manifest/src/values/Author.php���c��8hZ�2vendor/phar-io/manifest/src/values/Requirement.php���c�g{���Avendor/phar-io/manifest/src/values/BundledComponentCollection.php��c�ŤBvendor/phar-io/manifest/src/exceptions/ManifestLoaderException.php���c��G#�Dvendor/phar-io/manifest/src/exceptions/ManifestDocumentException.php���c�YT��Jvendor/phar-io/manifest/src/exceptions/InvalidApplicationNameException.php���c�en��Jvendor/phar-io/manifest/src/exceptions/ManifestDocumentMapperException.php���c�\;/�Cvendor/phar-io/manifest/src/exceptions/ManifestElementException.php���c���m}�@vendor/phar-io/manifest/src/exceptions/InvalidEmailException.php���c��z�S�>vendor/phar-io/manifest/src/exceptions/InvalidUrlException.php���c�1O�6�Kvendor/phar-io/manifest/src/exceptions/ManifestDocumentLoadingException.php���c���*��4vendor/phar-io/manifest/src/exceptions/Exception.php���c��84��Evendor/phar-io/manifest/src/exceptions/ElementCollectionException.php���c�
����3vendor/phar-io/manifest/src/xml/ContainsElement.phpk��ck4�6�2vendor/phar-io/manifest/src/xml/LicenseElement.php^��c^��9�4vendor/phar-io/manifest/src/xml/ComponentElement.phph��ch�*�.vendor/phar-io/manifest/src/xml/PhpElement.php��cȂb�8vendor/phar-io/manifest/src/xml/ExtElementCollection.php,��c,֏i�1vendor/phar-io/manifest/src/xml/AuthorElement.phpa��ca�z�Y�5vendor/phar-io/manifest/src/xml/ElementCollection.php��c$��ۤ4vendor/phar-io/manifest/src/xml/ManifestDocument.php���c�/����2vendor/phar-io/manifest/src/xml/BundlesElement.php\��c\��p�;vendor/phar-io/manifest/src/xml/AuthorElementCollection.php5��c5�ʶ��>vendor/phar-io/manifest/src/xml/ComponentElementCollection.php>��c>�>_�4vendor/phar-io/manifest/src/xml/CopyrightElement.php���c�����.vendor/phar-io/manifest/src/xml/ExtElement.php���c�q��ߤ3vendor/phar-io/manifest/src/xml/RequiresElement.php-��c-&�'�4vendor/phar-io/manifest/src/xml/ExtensionElement.phpl��cls�x�3vendor/phar-io/manifest/src/xml/ManifestElement.php���c��dq�2vendor/phar-io/manifest/src/ManifestSerializer.php��c�J�7�.vendor/phar-io/manifest/src/ManifestLoader.phpl��cl1i���6vendor/phar-io/manifest/src/ManifestDocumentMapper.php���c�L�6�vendor/phar-io/version/LICENSE&��c&Ҫ	�#vendor/phar-io/version/CHANGELOG.md���c�\�� vendor/phar-io/version/README.md9	��c9	���$vendor/phar-io/version/composer.json���c���w¤6vendor/phar-io/version/src/VersionConstraintParser.php���c�<P6�?vendor/phar-io/version/src/constraints/AnyVersionConstraint.php@��c@�[�Dvendor/phar-io/version/src/constraints/AbstractVersionConstraint.php���c�oSMy�<vendor/phar-io/version/src/constraints/VersionConstraint.php���c����W�Pvendor/phar-io/version/src/constraints/GreaterThanOrEqualToVersionConstraint.php���c���^��Cvendor/phar-io/version/src/constraints/OrVersionConstraintGroup.php���c����ؤDvendor/phar-io/version/src/constraints/AndVersionConstraintGroup.php���c�/j-ҤAvendor/phar-io/version/src/constraints/ExactVersionConstraint.php���c�:B���Ivendor/phar-io/version/src/constraints/SpecificMajorVersionConstraint.php���c���Qvendor/phar-io/version/src/constraints/SpecificMajorAndMinorVersionConstraint.php���c�L�K�5vendor/phar-io/version/src/VersionConstraintValue.php&
��c&
P>13�,vendor/phar-io/version/src/BuildMetaData.php���c���H�Avendor/phar-io/version/src/exceptions/InvalidVersionException.php���c�|���Jvendor/phar-io/version/src/exceptions/InvalidPreReleaseSuffixException.php���c������Ovendor/phar-io/version/src/exceptions/UnsupportedVersionConstraintException.php���c��Gd�Evendor/phar-io/version/src/exceptions/NoPreReleaseSuffixException.php���c�XbpԤBvendor/phar-io/version/src/exceptions/NoBuildMetaDataException.php���c������3vendor/phar-io/version/src/exceptions/Exception.php���c���G��/vendor/phar-io/version/src/PreReleaseSuffix.php^��c^.�o�&vendor/phar-io/version/src/Version.php+��c+fr붤,vendor/phar-io/version/src/VersionNumber.php���c�J}�r�vendor/psr/log/LICENSE=��c=p��O�vendor/psr/log/README.mdB��cB��'��vendor/psr/log/.gitignore��c�s�f�/vendor/psr/log/Psr/Log/LoggerAwareInterface.php)��c)�j��#vendor/psr/log/Psr/Log/LogLevel.phpP��cP���3vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.php)��c)I\��*vendor/psr/log/Psr/Log/Test/TestLogger.php���c�� ��)vendor/psr/log/Psr/Log/Test/DummyTest.php���c�HTg�+vendor/psr/log/Psr/Log/LoggerAwareTrait.php���c�Q'��3vendor/psr/log/Psr/Log/InvalidArgumentException.php`��c` �X1�%vendor/psr/log/Psr/Log/NullLogger.php���c����I�*vendor/psr/log/Psr/Log/LoggerInterface.php*��c*1b!q�&vendor/psr/log/Psr/Log/LoggerTrait.phpW
��cW
�W�j�)vendor/psr/log/Psr/Log/AbstractLogger.php ��c G���vendor/psr/log/composer.json2��c2�՞ڤvendor/monolog/monolog/.php_csL��cL�w��&vendor/monolog/monolog/CHANGELOG.mdown%?��c%?�Bq�vendor/monolog/monolog/LICENSE'��c'�1K�#vendor/monolog/monolog/CHANGELOG.md�`��c�`	\�Lvendor/monolog/monolog/tests/Monolog/Handler/WhatFailureGroupHandlerTest.phpX��cX���Evendor/monolog/monolog/tests/Monolog/Handler/ChromePHPHandlerTest.php���c�@e
ΤFvendor/monolog/monolog/tests/Monolog/Handler/PHPConsoleHandlerTest.php�&��c�&I��)�Fvendor/monolog/monolog/tests/Monolog/Handler/LogEntriesHandlerTest.php_	��c_	��Evendor/monolog/monolog/tests/Monolog/Handler/FleepHookHandlerTest.php���c��{��Jvendor/monolog/monolog/tests/Monolog/Handler/FingersCrossedHandlerTest.php�&��c�&\��=�Cvendor/monolog/monolog/tests/Monolog/Handler/HandlerWrapperTest.php���c��xޤDvendor/monolog/monolog/tests/Monolog/Handler/SamplingHandlerTest.phpM��cMp�9�Bvendor/monolog/monolog/tests/Monolog/Handler/StreamHandlerTest.php���c���	Y�Bvendor/monolog/monolog/tests/Monolog/Handler/SocketHandlerTest.php�!��c�!��<t�Dvendor/monolog/monolog/tests/Monolog/Handler/PushoverHandlerTest.php���c��(�Dvendor/monolog/monolog/tests/Monolog/Handler/NewRelicHandlerTest.php���c�|!�&�@vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerTest.php;
��c;
���Ivendor/monolog/monolog/tests/Monolog/Handler/ElasticSearchHandlerTest.php��c7vQ�Avendor/monolog/monolog/tests/Monolog/Handler/RavenHandlerTest.php���c��ع��Dvendor/monolog/monolog/tests/Monolog/Handler/AbstractHandlerTest.php���c���oS�@vendor/monolog/monolog/tests/Monolog/Handler/AmqpHandlerTest.phpa��caQ+s(�@vendor/monolog/monolog/tests/Monolog/Handler/MailHandlerTest.php���c��|d�Fvendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerLegacyTest.phpw��cw7�NߤNvendor/monolog/monolog/tests/Monolog/Handler/AbstractProcessingHandlerTest.php`
��c`
6^�R�Dvendor/monolog/monolog/tests/Monolog/Handler/ErrorLogHandlerTest.phpc��cc��d�Avendor/monolog/monolog/tests/Monolog/Handler/GroupHandlerTest.phpW��cW�=+�?vendor/monolog/monolog/tests/Monolog/Handler/PsrHandlerTest.php��c��4P�Hvendor/monolog/monolog/tests/Monolog/Handler/RotatingFileHandlerTest.php9��c9l�y�Hvendor/monolog/monolog/tests/Monolog/Handler/NativeMailerHandlerTest.phpZ��cZ�{��Evendor/monolog/monolog/tests/Monolog/Handler/SyslogUdpHandlerTest.php���c���9�Cvendor/monolog/monolog/tests/Monolog/Handler/MongoDBHandlerTest.php���c�D��|�Bvendor/monolog/monolog/tests/Monolog/Handler/SyslogHandlerTest.php��cM`�:�Avendor/monolog/monolog/tests/Monolog/Handler/SlackHandlerTest.php-��c-�m�v�Cvendor/monolog/monolog/tests/Monolog/Handler/HipChatHandlerTest.phpz'��cz'?�N�Kvendor/monolog/monolog/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php���c�����Cvendor/monolog/monolog/tests/Monolog/Handler/FirePHPHandlerTest.php���c��m�ݤ@vendor/monolog/monolog/tests/Monolog/Handler/TestHandlerTest.php}	��c}	nܿ��Bvendor/monolog/monolog/tests/Monolog/Handler/BufferHandlerTest.php���c���_��Avendor/monolog/monolog/tests/Monolog/Handler/RedisHandlerTest.phpR��cR՗�z�Ivendor/monolog/monolog/tests/Monolog/Handler/GelfMockMessagePublisher.php���c������Dvendor/monolog/monolog/tests/Monolog/Handler/FlowdockHandlerTest.php#
��c#
�:�>vendor/monolog/monolog/tests/Monolog/Handler/Fixtures/.gitkeep��c�>vendor/monolog/monolog/tests/Monolog/Handler/UdpSocketTest.php���c����K�Gvendor/monolog/monolog/tests/Monolog/Handler/SwiftMailerHandlerTest.php���c�}��y�@vendor/monolog/monolog/tests/Monolog/Handler/MockRavenClient.php=��c=6d��Bvendor/monolog/monolog/tests/Monolog/Handler/FilterHandlerTest.php��c��9�Gvendor/monolog/monolog/tests/Monolog/Handler/ZendMonitorHandlerTest.php���c�5]-��Jvendor/monolog/monolog/tests/Monolog/Handler/BrowserConsoleHandlerTest.phpk��ck�˖S�Cvendor/monolog/monolog/tests/Monolog/Handler/CouchDBHandlerTest.php���c��T/��Dvendor/monolog/monolog/tests/Monolog/Handler/DynamoDbHandlerTest.php���c����h�@vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php���c����Mvendor/monolog/monolog/tests/Monolog/Processor/PsrLogMessageProcessorTest.php ��c ��Zh�Ivendor/monolog/monolog/tests/Monolog/Processor/ProcessIdProcessorTest.phpL��cL�	��Ovendor/monolog/monolog/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.phpQ��cQE��Cvendor/monolog/monolog/tests/Monolog/Processor/WebProcessorTest.php�
��c�
��H�Cvendor/monolog/monolog/tests/Monolog/Processor/TagProcessorTest.phpG��cG	�IͤMvendor/monolog/monolog/tests/Monolog/Processor/IntrospectionProcessorTest.phpQ��cQe��k�Cvendor/monolog/monolog/tests/Monolog/Processor/UidProcessorTest.php���c�a���Cvendor/monolog/monolog/tests/Monolog/Processor/GitProcessorTest.php���c�Ejd�Kvendor/monolog/monolog/tests/Monolog/Processor/MemoryUsageProcessorTest.php$��c$4��u�5vendor/monolog/monolog/tests/Monolog/RegistryTest.php���c���֮�Ivendor/monolog/monolog/tests/Monolog/Formatter/ChromePHPFormatterTest.php���c��한�Hvendor/monolog/monolog/tests/Monolog/Formatter/WildfireFormatterTest.php���c��C^��Kvendor/monolog/monolog/tests/Monolog/Formatter/GelfMessageFormatterTest.php���c�S
m�Fvendor/monolog/monolog/tests/Monolog/Formatter/ScalarFormatterTest.php���c�Nz5;�Fvendor/monolog/monolog/tests/Monolog/Formatter/LogglyFormatterTest.php���c�s��Hvendor/monolog/monolog/tests/Monolog/Formatter/LogstashFormatterTest.php�-��c�-a�7�Jvendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php�0��c�0�o�9�Hvendor/monolog/monolog/tests/Monolog/Formatter/ElasticaFormatterTest.php4	��c4	Q��y�Dvendor/monolog/monolog/tests/Monolog/Formatter/LineFormatterTest.php���c�k���Dvendor/monolog/monolog/tests/Monolog/Formatter/JsonFormatterTest.php���c����/�Gvendor/monolog/monolog/tests/Monolog/Formatter/FluentdFormatterTest.php���c�v��'�Gvendor/monolog/monolog/tests/Monolog/Formatter/MongoDBFormatterTest.php$��c${CI��Hvendor/monolog/monolog/tests/Monolog/Formatter/FlowdockFormatterTest.php	��c	Ri��9vendor/monolog/monolog/tests/Monolog/PsrLogCompatTest.php���c������9vendor/monolog/monolog/tests/Monolog/ErrorHandlerTest.php���c��$�=�3vendor/monolog/monolog/tests/Monolog/LoggerTest.phpA��cA�u���1vendor/monolog/monolog/tests/Monolog/TestCase.phpm��cm��;�� vendor/monolog/monolog/README.md@��c@ˆ��#vendor/monolog/monolog/README.mdown���c�@ї�(vendor/monolog/monolog/phpstan.neon.dist���c��9G�&vendor/monolog/monolog/doc/01-usage.md!��c!��A�?vendor/monolog/monolog/doc/02-handlers-formatters-processors.md#��c#�=ı�%vendor/monolog/monolog/doc/sockets.md���c�.�\Y�*vendor/monolog/monolog/doc/04-extending.mdo��co����*vendor/monolog/monolog/doc/03-utilities.md��c8KiȤ'vendor/monolog/monolog/phpunit.xml.dist���c�F¬�$vendor/monolog/monolog/composer.json���c�q>�@vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.phpR��cR�.0�:vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php��cr��-�;vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php[��c[�f�<vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.phpT&��cT&k����>vendor/monolog/monolog/src/Monolog/Handler/SlackbotHandler.phpL	��cL	��`�<vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php���c�;Hդ<vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php3��c3��VƤ=vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.phpf��cf���Dvendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php���c�Ս4�=vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php>	��c>	�H�Yvendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php���c���m{�Zvendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php���c�V	vܤ\vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php���c�o�V��;vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php�
��c�
��ˤCvendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.phpU
��cU
�9�>vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php���c�ŧ���>vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php&��c&p�Ȧ�Avendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.phpl
��cl
�
Ƥ>vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php6
��c6
B�B8�>vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php���c�EU��Jvendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php���c�ĩ0�Hvendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php���c���]��Dvendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php+
��c+
��Ѥ;vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php���c��ƔT�?vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php���c����j�Dvendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php���c�Θ�֤<vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php��c�Γ�Bvendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php0��c0�G��Bvendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.phpV��cV���Ť=vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.phpF��cF�/g�Fvendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.phpr��cr���Q�:vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php���c��ܕ��Avendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php���c�EE�m�@vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php+'��c+'W�,�>vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php@	��c@	��}O�@vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.phpO��cO�V��Cvendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.phpg��cgʚ0�=vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.phpV��cV��Ȥ8vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php���c����Evendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php���c�~���>vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php�	��c�	&HɅ�Jvendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php���c���,�:vendor/monolog/monolog/src/Monolog/Handler/MailHandler.phpV��cVY�yW�<vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.phpQ��cQ�P0�<vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php;
��c;
WߤBvendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php��c7��Fvendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php1��c1M�9Ҥ?vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php��c���G�@vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php� ��c� ;*[.�9vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php���c��(r�>vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.phpf��cf�Š�Fvendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php?��c?�N{�?vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php
��c
$�sդ;vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.phpO��cO�ď�=vendor/monolog/monolog/src/Monolog/Handler/HipChatHandler.php�*��c�*�$]��?vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php#
��c#
3��֤:vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php���c��u�f�:vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php��czY�M�>vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php	��c	y��ǤHvendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php���c��唘�=vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php���c�c��#�;vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php���c��2�:vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php6��c6[��Bvendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.phpy��cyk�M�-vendor/monolog/monolog/src/Monolog/Logger.phpMW��cMW	ȡ�/vendor/monolog/monolog/src/Monolog/Registry.php���c����դGvendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php�	��c�	eO�=vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php���c�KDZS�Ivendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php��c���@�Cvendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php\��c\�ם�Cvendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php���c�u�_�=vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.phpR��cR�dd�=vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php���c���W�@vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php)��c)��y�Gvendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php�
��c�
��p+�=vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php���c��)��Cvendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php	��c	\e3��Evendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php��caoOD�:vendor/monolog/monolog/src/Monolog/ResettableInterface.php���c��4n�4vendor/monolog/monolog/src/Monolog/SignalHandler.phpm��cm�+d0�Bvendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php-��c-�����>vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php���c��K��>vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php��c�RCS�Bvendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php�	��c�	}*�3�Cvendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php��c�Wܑ�Bvendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php���c�.�hݤ@vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php*��c*w���@vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php��c�^��Avendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php���c��.S�Cvendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php���c�;`ai�Avendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php���c��w�c�Evendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php8��c8�1l�Bvendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php���c���(�Dvendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php���c�N��>vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php��c;�e'�3vendor/monolog/monolog/src/Monolog/ErrorHandler.php�!��c�!9}�Ӥ,vendor/monolog/monolog/src/Monolog/Utils.phpd��cd��(ݤ<vendor/symfony/event-dispatcher/EventDispatcherInterface.php�
��c�
WHCܤ)vendor/symfony/event-dispatcher/Event.php�
��c�
�P��Avendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php���c��N�'vendor/symfony/event-dispatcher/LICENSE)��c)NUN��,vendor/symfony/event-dispatcher/CHANGELOG.md���c�ѯ�3vendor/symfony/event-dispatcher/Tests/EventTest.php���c����%�=vendor/symfony/event-dispatcher/Tests/EventDispatcherTest.php���c��/�{�Evendor/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php7��c7/��:vendor/symfony/event-dispatcher/Tests/GenericEventTest.php��cdJ��Kvendor/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php� ��c� Se�Wvendor/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php���c�O���Fvendor/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php���c��)�T�Lvendor/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php�&��c�&�ȻJ�3vendor/symfony/event-dispatcher/EventDispatcher.php��c�9�)vendor/symfony/event-dispatcher/README.mdb��cb�ʼn�*vendor/symfony/event-dispatcher/.gitignore"��c"�U�<vendor/symfony/event-dispatcher/EventSubscriberInterface.php��c����0vendor/symfony/event-dispatcher/phpunit.xml.dist}��c}7*���<vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php~��c~Ñ�_�0vendor/symfony/event-dispatcher/GenericEvent.php{��c{��d��Mvendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php���c�q$z�-vendor/symfony/event-dispatcher/composer.jsono��co[��~�Bvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.phpI,��cI,O�S��9vendor/symfony/event-dispatcher/Debug/WrappedListener.php���c��4��Kvendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php#��c#�Ӗc�#vendor/sebastian/comparator/LICENSE	��c	�q��(vendor/sebastian/comparator/ChangeLog.md�	��c�	^ُ��%vendor/sebastian/comparator/README.mdw��cwVzu��)vendor/sebastian/comparator/composer.json���c���3vendor/sebastian/comparator/src/ArrayComparator.php���c�Lj:Q�2vendor/sebastian/comparator/src/TypeComparator.php���c�S��Ҥ+vendor/sebastian/comparator/src/Factory.php���c�k����6vendor/sebastian/comparator/src/ResourceComparator.php.��c.�K��8vendor/sebastian/comparator/src/MockObjectComparator.phpP��cP�PN�4vendor/sebastian/comparator/src/ObjectComparator.php��c�9�2�5vendor/sebastian/comparator/src/NumericComparator.phpv��cvU���6vendor/sebastian/comparator/src/DateTimeComparator.php���c��~�Ȥ4vendor/sebastian/comparator/src/ScalarComparator.php���c�)�
%�7vendor/sebastian/comparator/src/ExceptionComparator.php���c�ѕ���.vendor/sebastian/comparator/src/Comparator.php\��c\8�9�4vendor/sebastian/comparator/src/DoubleComparator.php���c�#�{
�5vendor/sebastian/comparator/src/DOMNodeComparator.php�
��c�
8���5vendor/sebastian/comparator/src/ComparisonFailure.php���c��I�>vendor/sebastian/comparator/src/SplObjectStorageComparator.php���c� ��)vendor/sebastian/global-state/phpunit.xml���c�k���%vendor/sebastian/global-state/LICENSE��c�J���*vendor/sebastian/global-state/ChangeLog.md���c�?>��'vendor/sebastian/global-state/build.xml���c��e@��5vendor/sebastian/global-state/tests/BlacklistTest.php���c�����4vendor/sebastian/global-state/tests/RestorerTest.php���c�Q�.��4vendor/sebastian/global-state/tests/SnapshotTest.php>��c>����8vendor/sebastian/global-state/tests/CodeExporterTest.php���c��.�K�Evendor/sebastian/global-state/tests/_fixture/BlacklistedInterface.phpe��cec_'�Avendor/sebastian/global-state/tests/_fixture/BlacklistedClass.php|��c|�ߊ��>vendor/sebastian/global-state/tests/_fixture/SnapshotTrait.phpZ��cZ�o��Fvendor/sebastian/global-state/tests/_fixture/BlacklistedChildClass.php{��c{ǓФBvendor/sebastian/global-state/tests/_fixture/SnapshotFunctions.phph��chnaYD�Gvendor/sebastian/global-state/tests/_fixture/BlacklistedImplementor.php���c���}��>vendor/sebastian/global-state/tests/_fixture/SnapshotClass.php��c����Dvendor/sebastian/global-state/tests/_fixture/SnapshotDomDocument.php���c��Z�h�'vendor/sebastian/global-state/README.md{��c{��YD�(vendor/sebastian/global-state/.gitignoreM��cMR�h�/vendor/sebastian/global-state/.github/stale.yml���c���9�)vendor/sebastian/global-state/.travis.yml|��c|3e�B�+vendor/sebastian/global-state/composer.jsonF��cFJ�C��*vendor/sebastian/global-state/.php_cs.dist>��c>s�?C�.vendor/sebastian/global-state/src/Restorer.php��c6��k�2vendor/sebastian/global-state/src/CodeExporter.phpj	��cj	7g�Ѥ.vendor/sebastian/global-state/src/Snapshot.phpj)��cj)I�ᚤ/vendor/sebastian/global-state/src/Blacklist.php�
��c�
=ŵ@�Avendor/sebastian/global-state/src/exceptions/RuntimeException.php���c�p��Ƥ:vendor/sebastian/global-state/src/exceptions/Exception.phpN��cNch5�*vendor/sebastian/object-enumerator/.php_cs���c���T�.vendor/sebastian/object-enumerator/phpunit.xml���c��*vendor/sebastian/object-enumerator/LICENSE��c�f�Τ/vendor/sebastian/object-enumerator/ChangeLog.mdA��cA����,vendor/sebastian/object-enumerator/build.xml��c�I֙�;vendor/sebastian/object-enumerator/tests/EnumeratorTest.php#
��c#
+� s�Fvendor/sebastian/object-enumerator/tests/_fixture/ExceptionThrower.php��c�$I�,vendor/sebastian/object-enumerator/README.md���c��‚5�-vendor/sebastian/object-enumerator/.gitignoree��ce5h�=�.vendor/sebastian/object-enumerator/.travis.yml���c���
ޤ0vendor/sebastian/object-enumerator/composer.jsonT��cTV�<�Cvendor/sebastian/object-enumerator/src/InvalidArgumentException.phpx��cx��'�5vendor/sebastian/object-enumerator/src/Enumerator.phpr��crz�\��4vendor/sebastian/object-enumerator/src/Exception.php6��c6n$*a�)vendor/sebastian/object-reflector/.php_cs���c���<R�-vendor/sebastian/object-reflector/phpunit.xml���c��:��)vendor/sebastian/object-reflector/LICENSE
��c
�F���.vendor/sebastian/object-reflector/ChangeLog.md���c�܌��+vendor/sebastian/object-reflector/build.xml��c@C<�?vendor/sebastian/object-reflector/tests/ObjectReflectorTest.php���c�H�y�Rvendor/sebastian/object-reflector/tests/_fixture/ClassWithIntegerAttributeName.php���c����?vendor/sebastian/object-reflector/tests/_fixture/ChildClass.phpA��cA����@vendor/sebastian/object-reflector/tests/_fixture/ParentClass.php���c����+vendor/sebastian/object-reflector/README.md���c�'6�Ƥ,vendor/sebastian/object-reflector/.gitignore-��c-��<�-vendor/sebastian/object-reflector/.travis.yml���c���
ޤ/vendor/sebastian/object-reflector/composer.json���c�S��:�9vendor/sebastian/object-reflector/src/ObjectReflector.php���c��"�Bvendor/sebastian/object-reflector/src/InvalidArgumentException.php���c�Y�J�3vendor/sebastian/object-reflector/src/Exception.phpN��cN� ^�1vendor/sebastian/code-unit-reverse-lookup/.php_cs���c���T�5vendor/sebastian/code-unit-reverse-lookup/phpunit.xml��cS���1vendor/sebastian/code-unit-reverse-lookup/LICENSE��cXX��6vendor/sebastian/code-unit-reverse-lookup/ChangeLog.md���c���?	�3vendor/sebastian/code-unit-reverse-lookup/build.xml"��c"bx0��>vendor/sebastian/code-unit-reverse-lookup/tests/WizardTest.php���c� ��դ3vendor/sebastian/code-unit-reverse-lookup/README.md���c��[��4vendor/sebastian/code-unit-reverse-lookup/.gitignore��c7�5=�5vendor/sebastian/code-unit-reverse-lookup/.travis.ymlp��cp�{z��7vendor/sebastian/code-unit-reverse-lookup/composer.json���c�D���8vendor/sebastian/code-unit-reverse-lookup/src/Wizard.phpe��ce���!vendor/sebastian/diff/phpunit.xml���c��􊓤vendor/sebastian/diff/LICENSE
��c
Dte#�"vendor/sebastian/diff/ChangeLog.md���c�q���vendor/sebastian/diff/build.xml��c��(vendor/sebastian/diff/tests/DiffTest.phpu��cu�����Evendor/sebastian/diff/tests/Output/AbstractChunkOutputBuilderTest.php)��c)�R~�@vendor/sebastian/diff/tests/Output/DiffOnlyOutputBuilderTest.phpd��cdz6|�Ivendor/sebastian/diff/tests/Output/StrictUnifiedDiffOutputBuilderTest.phpVD��cVD��+ݤQvendor/sebastian/diff/tests/Output/StrictUnifiedDiffOutputBuilderDataProvider.php&
��c&
���(�Zvendor/sebastian/diff/tests/Output/Integration/UnifiedDiffOutputBuilderIntegrationTest.php���c��0��`vendor/sebastian/diff/tests/Output/Integration/StrictUnifiedDiffOutputBuilderIntegrationTest.php<'��c<'�ܫ��Cvendor/sebastian/diff/tests/Output/UnifiedDiffOutputBuilderTest.phpV	��cV	zl�ĤKvendor/sebastian/diff/tests/Output/UnifiedDiffOutputBuilderDataProvider.php���c�2otA�@vendor/sebastian/diff/tests/Utils/UnifiedDiffAssertTraitTest.phpd,��cd,�����/vendor/sebastian/diff/tests/Utils/FileUtils.php���c���k�<vendor/sebastian/diff/tests/Utils/UnifiedDiffAssertTrait.php�+��c�+"�ڤKvendor/sebastian/diff/tests/Utils/UnifiedDiffAssertTraitIntegrationTest.php���c��
�*vendor/sebastian/diff/tests/ParserTest.php��c�8��?vendor/sebastian/diff/tests/TimeEfficientImplementationTest.phpy��cy�$ޤ(vendor/sebastian/diff/tests/LineTest.php���c����ƤAvendor/sebastian/diff/tests/MemoryEfficientImplementationTest.php��c%y��Rvendor/sebastian/diff/tests/fixtures/UnifiedDiffAssertTraitIntegrationTest/2_b.txt#��c#�2�Rvendor/sebastian/diff/tests/fixtures/UnifiedDiffAssertTraitIntegrationTest/2_a.txtE��cE&�/�Rvendor/sebastian/diff/tests/fixtures/UnifiedDiffAssertTraitIntegrationTest/1_b.txt��c�Rvendor/sebastian/diff/tests/fixtures/UnifiedDiffAssertTraitIntegrationTest/1_a.txt��cC���6vendor/sebastian/diff/tests/fixtures/out/.editorconfig��cs'D��3vendor/sebastian/diff/tests/fixtures/out/.gitignoreD��cD���դ2vendor/sebastian/diff/tests/fixtures/.editorconfig��cs'D��/vendor/sebastian/diff/tests/fixtures/patch2.txt���c�@k鐤.vendor/sebastian/diff/tests/fixtures/patch.txt���c��U$�8vendor/sebastian/diff/tests/fixtures/serialized_diff.bin/��c/Z$�>�)vendor/sebastian/diff/tests/ChunkTest.php���c�Y0MäFvendor/sebastian/diff/tests/Exception/InvalidArgumentExceptionTest.php���c�7,�8�Dvendor/sebastian/diff/tests/Exception/ConfigurationExceptionTest.php^��c^?澚�*vendor/sebastian/diff/tests/DifferTest.php�.��c�.���<vendor/sebastian/diff/tests/LongestCommonSubsequenceTest.php���c�x����vendor/sebastian/diff/README.md��c*�_٤ vendor/sebastian/diff/.gitignoreR��cR%����'vendor/sebastian/diff/.github/stale.yml���c��˱��!vendor/sebastian/diff/.travis.yml���c���I�#vendor/sebastian/diff/composer.jsonn��cn�[^�"vendor/sebastian/diff/.php_cs.dist
��c
��S�"vendor/sebastian/diff/src/Diff.php���c�3߬�$vendor/sebastian/diff/src/Parser.php���c�G�2�Mvendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php��cv�<�:vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php���c��28>�?vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php
��c
�zk�=vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php* ��c* ����Cvendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php�(��c�(�N�?vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.phpO��cOE�l�@vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php<��c<����#vendor/sebastian/diff/src/Chunk.phpm��cm�A��$vendor/sebastian/diff/src/Differ.php9%��c9%��D�"vendor/sebastian/diff/src/Line.phpO��cO'��	�>vendor/sebastian/diff/src/Exception/ConfigurationException.phpC��cC<� 1�@vendor/sebastian/diff/src/Exception/InvalidArgumentException.php���c�g����1vendor/sebastian/diff/src/Exception/Exception.php@��c@g�դOvendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.phpV��cVfդ.vendor/sebastian/recursion-context/phpunit.xml���c��:��*vendor/sebastian/recursion-context/LICENSE��c��>�,vendor/sebastian/recursion-context/build.xml���c�.�>�8vendor/sebastian/recursion-context/tests/ContextTest.php��c���,vendor/sebastian/recursion-context/README.md���c��b�Ԥ-vendor/sebastian/recursion-context/.gitignore��cI�&�.vendor/sebastian/recursion-context/.travis.ymlg��cg��5��0vendor/sebastian/recursion-context/composer.jsonJ��cJ}��Cvendor/sebastian/recursion-context/src/InvalidArgumentException.php���c�mH�2vendor/sebastian/recursion-context/src/Context.php{��c{����4vendor/sebastian/recursion-context/src/Exception.phpJ��cJ���!vendor/sebastian/type/phpunit.xml6��c64�2��vendor/sebastian/type/LICENSE��c$��1�"vendor/sebastian/type/ChangeLog.md���c����vendor/sebastian/type/build.xml��c��ù�1vendor/sebastian/type/tests/unit/NullTypeTest.php���c����1vendor/sebastian/type/tests/unit/VoidTypeTest.php���c�u����5vendor/sebastian/type/tests/unit/IterableTypeTest.php�	��c�	�p�P�5vendor/sebastian/type/tests/unit/CallableTypeTest.php'��c'
�)2�3vendor/sebastian/type/tests/unit/ObjectTypeTest.php���c�*術�1vendor/sebastian/type/tests/unit/TypeNameTest.phpd��cd�'���-vendor/sebastian/type/tests/unit/TypeTest.php���c�פ4vendor/sebastian/type/tests/unit/UnknownTypeTest.php���c����,�3vendor/sebastian/type/tests/unit/SimpleTypeTest.php���c��3e�:vendor/sebastian/type/tests/unit/GenericObjectTypeTest.phpa��caZ[vA�Avendor/sebastian/type/tests/_fixture/ClassWithCallbackMethods.php���c���ڤ:vendor/sebastian/type/tests/_fixture/callback_function.phpZ��cZ�a�!�3vendor/sebastian/type/tests/_fixture/ChildClass.php\��c\ �8�4vendor/sebastian/type/tests/_fixture/ParentClass.phpu��cu��L�1vendor/sebastian/type/tests/_fixture/Iterator.phpK��cK�|�Ӥ>vendor/sebastian/type/tests/_fixture/ClassWithInvokeMethod.php���c���Nˤvendor/sebastian/type/README.md���c�h�Ѥ vendor/sebastian/type/.gitignore���c��LϤ)vendor/sebastian/type/.github/FUNDING.yml��c1�S)�$vendor/sebastian/type/.gitattributes��c��e9�vendor/sebastian/type/phive.xml ��c ɝݤ!vendor/sebastian/type/.travis.yml���c��~��#vendor/sebastian/type/composer.jsond��cd5
Y�"vendor/sebastian/type/.php_cs.dist���c�o�XB�vendor/sebastian/type/psalm.xml��c$vendor/sebastian/type/.idea/type.iml�
��c�
��e�Bvendor/sebastian/type/.idea/inspectionProfiles/Project_Default.xmln���cn����#vendor/sebastian/type/.idea/vcs.xml���c��cܞ�;vendor/sebastian/type/.idea/php-inspections-ea-ultimate.xml&��c&�.]�'vendor/sebastian/type/.idea/modules.xml��cȶ�i�#vendor/sebastian/type/.idea/php.xmlH	��cH	v�W�$vendor/sebastian/type/.idea/misc.xml���c��B"1�/vendor/sebastian/type/src/GenericObjectType.php���c�����(vendor/sebastian/type/src/SimpleType.php���c�g���"vendor/sebastian/type/src/Type.php���c�k��5�&vendor/sebastian/type/src/NullType.php[��c[9�o�(vendor/sebastian/type/src/ObjectType.php���c�Ř1ߤ*vendor/sebastian/type/src/CallableType.php���c�Ί]��)vendor/sebastian/type/src/UnknownType.phpE��cE����&vendor/sebastian/type/src/TypeName.php��c�N�>�&vendor/sebastian/type/src/VoidType.php[��c[)T�8vendor/sebastian/type/src/exception/RuntimeException.phpw��cw56���1vendor/sebastian/type/src/exception/Exception.php?��c?Pm{�*vendor/sebastian/type/src/IterableType.phpQ��cQ���q� vendor/sebastian/version/.php_cs��c��oX� vendor/sebastian/version/LICENSE��cn�"vendor/sebastian/version/README.md���c�|�Qs�#vendor/sebastian/version/.gitignore��c=vk�'vendor/sebastian/version/.gitattributes��crsX�&vendor/sebastian/version/composer.json���c�a�ʤ(vendor/sebastian/version/src/Version.php���c�N\Ǥ(vendor/sebastian/environment/phpunit.xml���c�J����$vendor/sebastian/environment/LICENSE��cI���)vendor/sebastian/environment/ChangeLog.md���c��́_�&vendor/sebastian/environment/build.xml���c�^1-Ǥ2vendor/sebastian/environment/tests/ConsoleTest.php��c�&��:vendor/sebastian/environment/tests/OperatingSystemTest.php���c��&��2vendor/sebastian/environment/tests/RuntimeTest.php���c�T�~l�&vendor/sebastian/environment/README.md���c��I�'vendor/sebastian/environment/.gitignoreS��cS}5�0vendor/sebastian/environment/.github/FUNDING.yml��cô�(vendor/sebastian/environment/.travis.yml0��c0��f�*vendor/sebastian/environment/composer.jsonK��cK_kȤ)vendor/sebastian/environment/.php_cs.distb��cbWl��,vendor/sebastian/environment/src/Runtime.php���c��P��4vendor/sebastian/environment/src/OperatingSystem.php���c��`���,vendor/sebastian/environment/src/Console.php��cB�s�!vendor/sebastian/exporter/LICENSE��c	5٤&vendor/sebastian/exporter/ChangeLog.md��c�)|��#vendor/sebastian/exporter/README.md�
��c�
���b�'vendor/sebastian/exporter/composer.json���c���Yd�*vendor/sebastian/exporter/src/Exporter.php,+��c,+�m�ݤ,vendor/sebastian/resource-operations/LICENSE��c��r�1vendor/sebastian/resource-operations/ChangeLog.md��c�yW��.vendor/sebastian/resource-operations/build.xml���c��6�Evendor/sebastian/resource-operations/tests/ResourceOperationsTest.php���c�Cb�.vendor/sebastian/resource-operations/README.md���c�_{���/vendor/sebastian/resource-operations/.gitignoreM��cML�¤6vendor/sebastian/resource-operations/.github/stale.yml���c���9�7vendor/sebastian/resource-operations/build/generate.php���c����q�2vendor/sebastian/resource-operations/composer.json���c��hP�1vendor/sebastian/resource-operations/.php_cs.distm��cm�y=��?vendor/sebastian/resource-operations/src/ResourceOperations.phpi��ci6G�vendor/guzzle/guzzle/LICENSEW��cW�[��!vendor/guzzle/guzzle/CHANGELOG.md���c��_�D�vendor/guzzle/guzzle/build.xml���c�^�?.�"vendor/guzzle/guzzle/phar-stub.phpQ��cQ^ib7�(vendor/guzzle/guzzle/tests/bootstrap.php���c����Cvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service2.json]��c]�`�R�>vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/mock_response#��c#@}Q��Dvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service_3.json���c��P<�Evendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/baz.json-��c-$?Y��Kvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/recursive.json!��c!OIC��Evendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/foo.json���c��<8��Evendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/bar.json!��c!OIC��=vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/FileBody.txt��c�Bvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service.json���c�c�@�Gvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/services.json���c�8�sȤDvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json1.json���c����)�Dvendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json2.json���c�:o�G�Evendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php���c�C>*^�Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.phpL
��cL
����Bvendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php���c����Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php[��c[�H�1�Fvendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php��c���/�:vendor/guzzle/guzzle/tests/Guzzle/Tests/GuzzleTestCase.php���c���:vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockMulti.php���c�׵��>vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php���c����,�=vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.phpC��cC�ǖw�Bvendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php���c���f�Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php���c�/%��<vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.phph��chsq�Ǥ=vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php���c��c耤Nvendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php���c���Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php�-��c�-�>��Yvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.phpz��cz��^�Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php���c�S$&��Zvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php���c�1�)��Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php���c�>�4v�Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php"
��c"
0��ˤRvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.phpb��cb\q���Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.phpI��cI�� �Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php2��c2''zW�Wvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php���c�p��5�Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php���c�!
�?�Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php���c��P蛤Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php���c�KI�ŤHvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php\2��c\2�|�Uvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php�	��c�	&̛P�Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php��ch����Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php	Q��c	QMR�+�Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php���c�H�N��Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php���c�mr�¤Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php'��c'iM�!�Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.phpC��cCM�i�Xvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php���c�Z>�Fvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php���c�[��Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php���c�j�1H�Nvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php���c�b^c�Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.phpa��caR�IƤDvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.phpt��ct�:��Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php���c���R��Jvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php���c����Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php�5��c�5�9��Uvendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.phpi��ci(0�ߤDvendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php���c����Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php���c����Ovendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php��c����Evendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php+��c+�E���Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php>��c>'��Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php���c�@K��Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.phpB ��cB �_�դNvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserProvider.php�7��c�7��낤Jvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php��cY|�ФNvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php���c����6�Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php���c�����Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.phpZ��cZ�E�x�<vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php���c�=W)ʤ>vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php��c�r�դLvendor/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php[��c[:�N�Avendor/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php�C��c�CP崤Wvendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.phpd��cd���7�Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php4
��c4
X�>�Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php���c�JE�9�Gvendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php���c�y �C�Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php~��c~n���Gvendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php���c�ڄX�Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.phpk��ck���Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.phpb��cbk+�Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php`��c`�Ql{�Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php���c�i��Xvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.phpp��cpM���7vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php��c��H��>vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php��c��HF�6vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/server.jsd��cdS`;1�Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php�/��c�/�灤Evendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.phpb��cb���Kvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php
g��c
g�g�w�Evendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php�]��c�]����Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.phpu��cu_��!�Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.phprf��crf�An�Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.phpn��cnևo��Svendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php�@��c�@��n�Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php���c��ꢧ�Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php��c|-,:�Qvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.phpi��ci#�M�Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php���c���w�Fvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php#��c#�8��?vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php���c���ФHvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php���c��ƿ|�@vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php���c��'��Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php�D��c�Do�¤Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php	��c	;���Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php
��c
-��c�Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php���c���x��Evendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php���c�
���8vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php�/��c�/�O�M�Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php���c��>lJ�Uvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.phpr��cr��1��Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php���c��q��Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php���c���N8�;vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php�Y��c�Y�4�ޤAvendor/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php!	��c!	HbYǤDvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php��c���ѤFvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.phpN��cN�8�9�Bvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php���c���FJ�Bvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php!
��c!
�} `�Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php���c��3rʤJvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.phpr	��cr	,���Ivendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.phpc��cc�ФJvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php�	��c�	un	�Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php$��c$|R�ͤMvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php9��c9�9�;vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php��c�b.ǤJvendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php���c���"�Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php���c���w��Avendor/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php#��c#��虤Dvendor/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.phpf��cf1���Evendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php'��c'bӔ�Avendor/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php���c�R���Cvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/MockClient.php���c��c��Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.phpp��cp�b��Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.phpJ��cJ%%	�Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php��cŲ|��Hvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php���c��c٥�Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.phpu��cu�1���Mvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php�,��c�,�/ ҤMvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php�6��c�6�����\vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php���c��c��Vvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php!��c!7� �Svendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php�0��c�0�!��Svendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php3��c3ۀq��Lvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php���c���U�Gvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php<��c<~Жg�Xvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php���c��٢�Wvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.phpf7��cf76�`6�Pvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php5��c5Ly+<�Uvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php���c��q�Ovendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php���c���U!�Nvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php3��c35�ߧ�\vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php���c�b�ͤTvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.phpc	��cc	Nv8�Rvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php���c�ϸ�&�avendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php
��c
����Xvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php���c��
�[�`vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.phpK��cK�"��pvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php���c���O��dvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php���c��r��fvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php+
��c+
���Ƥdvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php��c`�X�cvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php�<��c�<�e��jvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php���c�&^�ۤlvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php���c���Ҟ�kvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php���c��H�פhvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php���c��Vl�kvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php���c�o0c$�cvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php�	��c�	"�+T�evendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php���c���RU�cvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.phpf	��cf	0`�bvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php�T��c�Ty�ρ�dvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php���c���ࠤgvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php,��c,��f�Fvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php���c�K�#L�Qvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php���c��Op�]vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php���c���pӤ[vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.phpJ��cJj�%�avendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php8��c8�摤Tvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php���c�ؤ ��Nvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.phpk+��ck+a:퍤Uvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php���c�8-a��Zvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php
��c
05�ݤevendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php���c�\f �>vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php�+��c�+O�Kvendor/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php���c��N�Ivendor/guzzle/guzzle/docs/webservice-client/using-the-service-builder.rstg5��cg5ޤ��Kvendor/guzzle/guzzle/docs/webservice-client/guzzle-service-descriptions.rst�u��c�uW7��Avendor/guzzle/guzzle/docs/webservice-client/webservice-client.rst_p��c_p���&�#vendor/guzzle/guzzle/docs/index.rst}��c}�F	�;vendor/guzzle/guzzle/docs/_downloads/guzzle-schema-1.0.json�"��c�"�
�r�*vendor/guzzle/guzzle/docs/requirements.txt)��c)\#�6vendor/guzzle/guzzle/docs/plugins/curl-auth-plugin.rst��c����6vendor/guzzle/guzzle/docs/plugins/plugins-overview.rst���c�^Mvf�2vendor/guzzle/guzzle/docs/plugins/oauth-plugin.rstL��cL���4vendor/guzzle/guzzle/docs/plugins/history-plugin.rst���c��?�:vendor/guzzle/guzzle/docs/plugins/md5-validator-plugin.rst��c�Bw��3vendor/guzzle/guzzle/docs/plugins/cookie-plugin.rst+��c+��? �6vendor/guzzle/guzzle/docs/plugins/plugins-list.rst.inc!��c!�V'��1vendor/guzzle/guzzle/docs/plugins/mock-plugin.rstf��cf�#`{�2vendor/guzzle/guzzle/docs/plugins/async-plugin.rst���c�)�mJ�6vendor/guzzle/guzzle/docs/plugins/creating-plugins.rst�
��c�
��ݒ�2vendor/guzzle/guzzle/docs/plugins/cache-plugin.rst���c��)OI�4vendor/guzzle/guzzle/docs/plugins/backoff-plugin.rst���c�"�P�0vendor/guzzle/guzzle/docs/plugins/log-plugin.rst���c�A�U�/vendor/guzzle/guzzle/docs/_templates/index.html���c�׽R�1vendor/guzzle/guzzle/docs/_templates/leftbar.html��c�3vendor/guzzle/guzzle/docs/_templates/nav_links.html<��c<A� ٤"vendor/guzzle/guzzle/docs/Makefile���c��
+�!vendor/guzzle/guzzle/docs/conf.py���c�$����-vendor/guzzle/guzzle/docs/_static/prettify.js@5��c@5;�J�.vendor/guzzle/guzzle/docs/_static/homepage.cssq	��cq	WV�Ƥ.vendor/guzzle/guzzle/docs/_static/prettify.cssR��cR�Ѥ*vendor/guzzle/guzzle/docs/_static/logo.png~���c~�+8K��1vendor/guzzle/guzzle/docs/_static/guzzle-icon.png#��c#x��Ƥ2vendor/guzzle/guzzle/docs/testing/unit-testing.rst&��c&����"vendor/guzzle/guzzle/docs/docs.rst*��c*�`τ�6vendor/guzzle/guzzle/docs/getting-started/overview.rst6��c6x�#z�:vendor/guzzle/guzzle/docs/getting-started/installation.rst!$��c!$YKN��1vendor/guzzle/guzzle/docs/getting-started/faq.rstJ��cJ�,���/vendor/guzzle/guzzle/docs/batching/batching.rst��c$�_g�2vendor/guzzle/guzzle/docs/http-client/response.rst���c�2F��7vendor/guzzle/guzzle/docs/http-client/uri-templates.rst	��c	P����8vendor/guzzle/guzzle/docs/http-client/http-redirects.rstV
��cV
����1vendor/guzzle/guzzle/docs/http-client/request.rst~��c~��C�7vendor/guzzle/guzzle/docs/http-client/entity-bodies.rst���c�Y�6Ƥ0vendor/guzzle/guzzle/docs/http-client/client.rst�\��c�\\�|N�:vendor/guzzle/guzzle/docs/iterators/resource-iterators.rstw��cw/%Wp�8vendor/guzzle/guzzle/docs/iterators/guzzle-iterators.rstn	��cn	�hw�vendor/guzzle/guzzle/README.md�	��c�	!�m�vendor/guzzle/guzzle/.gitignorep��cp�}ͤ7vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.php�*��c�*��B
�>vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php�.��c�.
�o̤5vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php`��c`Wa�Τ-vendor/guzzle/guzzle/phing/imports/deploy.xmlc��ccL0'̤3vendor/guzzle/guzzle/phing/imports/dependencies.xml#��c#���J�0vendor/guzzle/guzzle/phing/build.properties.dist���c�'NQ]�%vendor/guzzle/guzzle/phpunit.xml.distJ	��cJ	��J�!vendor/guzzle/guzzle/UPGRADING.mdT��cT3{��� vendor/guzzle/guzzle/.travis.yml;��c;��ي�"vendor/guzzle/guzzle/composer.json�	��c�	�ya�9vendor/guzzle/guzzle/src/Guzzle/Cache/Zf1CacheAdapter.php���c�Z㍼�=vendor/guzzle/guzzle/src/Guzzle/Cache/ClosureCacheAdapter.php^��c^���Τ?vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php���c����=vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php���c�:��ä:vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php��c���9vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php���c��I�̤>vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.phpe��ce�S�ޤ>vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.phpG��cG!��3vendor/guzzle/guzzle/src/Guzzle/Cache/composer.json���c�I�0e�:vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php8��c81���1vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.php��c���|�Bvendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php%��c%-��Hvendor/guzzle/guzzle/src/Guzzle/Stream/StreamRequestFactoryInterface.php[��c[4�4vendor/guzzle/guzzle/src/Guzzle/Stream/composer.json���c���"U�Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.php���c��>��Svendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php��c�|�Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php���c�
j�v�Kvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php���c�X�|�Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php���c�#Ǧ�Nvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php���c�� sW�Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.phpI��cI��Z4�@vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php=��c=Z�m�Kvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php���c��AQp�Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php���c�T�#�Mvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php���c�m�hS�Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php���c�%+��@vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php	��c	(�*��<vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/composer.json���c�"��Avendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.phpu
��cu
�Nm��Fvendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php���c��'f��8vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/composer.json���c��m���<vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php((��c((=,���:vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/composer.json���c�>7��Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.php���c���V��Ivendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.php���c�,\�p�<vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CachePlugin.php:3��c:3P��Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php���c��k�ˤFvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/RevalidationInterface.phpN��cN��D��Hvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php���c������Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php���c���[�Avendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/SkipRevalidation.php���c�Nt�Dvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php���c����ܤAvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php���c���Dvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php� ��c� �ڤ:vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/composer.json���c��äFvendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php���c�]�9�Lvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php��cd�'��Xvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.phpV��cV|�F��Yvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php���c���ҙ�Bvendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/composer.json���c�[y��9vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/composer.json���c�~=�x�:vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.phpN��cNp��<vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php���c���`��:vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/composer.json���c���E �Bvendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.phpl��cl˞��=vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/composer.json���c��6�@vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.phpQ��cQDS�+�<vendor/guzzle/guzzle/src/Guzzle/Plugin/History/composer.json���c��:��8vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php���c��A"ڤ8vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/composer.json���c�<�i�>vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php���c�L"]��8vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php21��c21��Jvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php@��c@�6.~�Nvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.phpj��cj4`ۤIvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php���c�t2L�Rvendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php���c�!m|��;vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/composer.json���c���R�4vendor/guzzle/guzzle/src/Guzzle/Plugin/composer.jsonT��cTo&��Avendor/guzzle/guzzle/src/Guzzle/Inflection/MemoizingInflector.php���c�l�_t�Cvendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php���c�\:��Avendor/guzzle/guzzle/src/Guzzle/Inflection/InflectorInterface.php>��c>ָ�k�8vendor/guzzle/guzzle/src/Guzzle/Inflection/composer.jsonr��croR��8vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.phpS��cSB#c��9vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php���c����Ivendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php���c�(5�;�Hvendor/guzzle/guzzle/src/Guzzle/Parser/Message/PeclHttpMessageParser.php���c����Hvendor/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.php���c��J2�@vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php+
��c+
�d��8vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParser.php���c�loV2�Avendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php��c�"��Gvendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php���c��=�>vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.phpz��cz�����4vendor/guzzle/guzzle/src/Guzzle/Parser/composer.json���c�;�`��Bvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplate.php ��c Y���Fvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php���c���QѤKvendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php���c�[��0vendor/guzzle/guzzle/src/Guzzle/Common/Event.php(��c(��kۤ;vendor/guzzle/guzzle/src/Guzzle/Common/ToArrayInterface.php���c���N�@vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php���c�%�;��2vendor/guzzle/guzzle/src/Guzzle/Common/Version.php���c����5vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php-��c-��E�>vendor/guzzle/guzzle/src/Guzzle/Common/FromConfigInterface.php���c���1r�Avendor/guzzle/guzzle/src/Guzzle/Common/HasDispatcherInterface.phpN��cN�3��Dvendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.phpd��cd�ؤMvendor/guzzle/guzzle/src/Guzzle/Common/Exception/UnexpectedValueException.php���c��e���Evendor/guzzle/guzzle/src/Guzzle/Common/Exception/RuntimeException.phpz��czh^�w�Mvendor/guzzle/guzzle/src/Guzzle/Common/Exception/InvalidArgumentException.php���c��VǤKvendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php���c��qS��Hvendor/guzzle/guzzle/src/Guzzle/Common/Exception/ExceptionCollection.php��c�A˲�4vendor/guzzle/guzzle/src/Guzzle/Common/composer.json���c��>x��<vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php��cGZ���;vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php���c�����8vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.phpT��cTR`1q�2vendor/guzzle/guzzle/src/Guzzle/Iterator/README.md���c��ɧQ�;vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php���c�ڬ���@vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.phpb��cb]���6vendor/guzzle/guzzle/src/Guzzle/Iterator/composer.json���c�s�@�2vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php����c����Qvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php���c�)��Hvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php��c�^<ͤFvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.phpt��ct�$��Lvendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php<��c<9�|\�3vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php���c��á�9vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem���c�c�9vendor/guzzle/guzzle/src/Guzzle/Http/Message/Response.php�f��c�f��礤Bvendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php���c�Ӑ¤Avendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestInterface.php7!��c7!��Օ�9vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFile.php���c�M.>�8vendor/guzzle/guzzle/src/Guzzle/Http/Message/Request.php�K��c�K1�Wߤ7vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php���c��S�@vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php#��c#�C}#�?vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php�2��c�2�h�Avendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php	��c	ۓ`��Gvendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php���c��'DU�Pvendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php���c��Gvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderInterface.phpP��cP�(��Hvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php ��c ��hɤ<vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/Link.php���c������Dvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php�
��c�
��O�Evendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php���c��┤Nvendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php���c������Hvendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.phpx��cx�&ۤ,vendor/guzzle/guzzle/src/Guzzle/Http/Url.php"9��c"9+a�_�=vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php]��c]T�š�8vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlHandle.php�=��c�=���9vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php���c���\�7vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php�8��c�8dq�̤<vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiProxy.php��c���D�@vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php=��c=�њO�8vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php�&��c�&Pg5�<vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.phps	��cs	����:vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.phpz��cz��b�4vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php*"��c*"���ä=vendor/guzzle/guzzle/src/Guzzle/Http/IoEmittingEntityBody.php���c��c�"�5vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.php'��c'�Z�!�Ovendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php���c�5"�ڤ@vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php���c���Gvendor/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php4��c4��=�Lvendor/guzzle/guzzle/src/Guzzle/Http/Exception/TooManyRedirectsException.phpi��ciǸ��Ovendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php���c�Wp�Ivendor/guzzle/guzzle/src/Guzzle/Http/Exception/MultiTransferException.php�
��c�
[ڒ��@vendor/guzzle/guzzle/src/Guzzle/Http/Exception/CurlException.phpC��cC&Y��Pvendor/guzzle/guzzle/src/Guzzle/Http/Exception/CouldNotRewindStreamException.php���c��n��Cvendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php��c�o~�7vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php{'��c{'s�;��2vendor/guzzle/guzzle/src/Guzzle/Http/composer.json(��c(W�M�/vendor/guzzle/guzzle/src/Guzzle/Http/Client.php�A��c�AF����Dvendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php���c��a��<vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php#
��c#
`.��=vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.phpt��ctzHF�@vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php���c��?��/vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.php���c��s��>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchRequestTransfer.php���c��q;�8vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php���c��j��:vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.phpk��ckd�j��?vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php���c���~��8vendor/guzzle/guzzle/src/Guzzle/Batch/BatchInterface.phpM��cMƿs|�>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php���c���֤>vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php���c���2�7vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php���c�ۆ�P�Avendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php���c��E$��6vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php���c�`B2�Jvendor/guzzle/guzzle/src/Guzzle/Batch/Exception/BatchTransferException.php�
��c�
&���@vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php��c��#T�3vendor/guzzle/guzzle/src/Guzzle/Batch/composer.json/��c/V�y�6vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php���c��;ͤ;vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php���c��\:�9vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php���c�+$�Y�9vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.phpG��cG��#p�7vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.phpg��cgx�c�5vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php^��c^�����:vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php ��c p��-�5vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php���c�>'���8vendor/guzzle/guzzle/src/Guzzle/Log/MessageFormatter.php���c��B�5vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php���c���Yڤ1vendor/guzzle/guzzle/src/Guzzle/Log/composer.json���c�<��:�Avendor/guzzle/guzzle/src/Guzzle/Service/ConfigLoaderInterface.php���c�VQ�h�?vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php���c��Gvendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php���c��/lF�Gvendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.phpj.��cj.Cc�ޤJvendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php���c�e� �Pvendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionLoader.php�	��c�	%��@�Svendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php���c�/S��Jvendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php���c��b��Jvendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php���c���#ŤAvendor/guzzle/guzzle/src/Guzzle/Service/Description/Operation.phpv=��cv=���Avendor/guzzle/guzzle/src/Guzzle/Service/Description/Parameter.php�a��c�a[���;vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php�
��c�
���Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php���c��9�[�Ivendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php���c��.'|�Nvendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php���c�ÖEk�Bvendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php��c���.�Jvendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseClassInterface.php���c�s�o�Dvendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php�	��c�	�Y���Kvendor/guzzle/guzzle/src/Guzzle/Service/Command/ResponseParserInterface.php���c�w��{�Cvendor/guzzle/guzzle/src/Guzzle/Service/Command/AbstractCommand.php40��c40Qb���Kvendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php���c�R��Dvendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php�
��c�
%����Pvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.phpE��cE��=�Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php���c�ϠYc�Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php��cj1̤Uvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.phpm��cm����Hvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php`��c`d���Fvendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/MapFactory.php��c�	���`vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.phpH��cH��1�evendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php2��c2��[�dvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.phpf��cf}��M�Zvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php��c�տ�Wvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php���c�
�i��Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php3��c3����Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php�
��c�
�貤^vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.phpB��cB�x�@�[vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php���c���$p�\vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php
��c
˱�Ԥbvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php���c���Zv�_vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php���c�V����Xvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php��c=����Yvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php���c� ϶q�cvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php7��c7{�HƤVvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php���c����Wvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php�	��c�	Y4��Wvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php���c���a
�Tvendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php���c���Q�Lvendor/guzzle/guzzle/src/Guzzle/Service/Command/CreateResponseClassEvent.php<��c< 8+�Uvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php��c癤Ѥ:vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php��cBpQ��Evendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php\��c\K�ˤQvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php���c�q���Uvendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php���c��쾒�Qvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.phpS
��cS

֜��Tvendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php��c`�Ovendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php���c������Nvendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorInterface.php��c�2�P�Kvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php���c��S�)�Hvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderLoader.phpD
��cD
��_�Bvendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php��c����Lvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php���c�#��N�Nvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceNotFoundException.phpn��cn�S�h�Fvendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandException.php���c���կ�Ivendor/guzzle/guzzle/src/Guzzle/Service/Exception/ValidationException.php��cb�d�Mvendor/guzzle/guzzle/src/Guzzle/Service/Exception/ServiceBuilderException.php���c���NΤQvendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php���c�ƣ��Nvendor/guzzle/guzzle/src/Guzzle/Service/Exception/CommandTransferException.php���c�V��ϤYvendor/guzzle/guzzle/src/Guzzle/Service/Exception/InconsistentClientTransferException.php���c�y���5vendor/guzzle/guzzle/src/Guzzle/Service/composer.json��c<��x�@vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.phpq��cq��7�2vendor/guzzle/guzzle/src/Guzzle/Service/Client.php%��c%�
�W�src/BaiduBce/Bce.phpg��cgI��src/BaiduBce/Util/MimeTypes.php:��c:��;�src/BaiduBce/Util/HashUtils.phpQ��cQm]��� src/BaiduBce/Util/mime.types.php���c��g}C�src/BaiduBce/Util/DateUtils.php���c�+)O�'src/BaiduBce/Util/GenerateMimeTypes.php���c�����src/BaiduBce/Util/HttpUtils.php���c��q��!src/BaiduBce/Util/StringUtils.phpN��cN���!src/BaiduBce/Auth/SignOptions.php���c��}�y�%src/BaiduBce/Auth/SignerInterface.php���c���i}�!src/BaiduBce/Auth/BceV1Signer.php1��c1dlF� src/BaiduBce/BceHttpResponse.phpx��cx$���&src/BaiduBce/Http/HttpContentTypes.php���c��"��!src/BaiduBce/Http/HttpHeaders.php���c�Z�<��#src/BaiduBce/Http/BceHttpClient.phpA&��cA&����&src/BaiduBce/Http/GuzzleLogAdapter.php#��c#���� src/BaiduBce/Http/HttpMethod.php���c�ga�'src/BaiduBce/BceClientConfigOptions.phpI��cI� ���#src/BaiduBce/Log/NullLogFactory.php���c��}I|�src/BaiduBce/Log/LogFactory.php�
��c�
@����#src/BaiduBce/Log/MonoLogFactory.php���c��[�f�(src/BaiduBce/Log/LogFactoryInterface.php��c�E���src/BaiduBce/BceBaseClient.php@��c@d���+src/BaiduBce/Exception/BceBaseException.phpi��ci��!��.src/BaiduBce/Exception/BceServiceException.php���c�	�-src/BaiduBce/Exception/BceClientException.phps��cs?��*�'src/BaiduBce/Services/Dcc/DccClient.phpZ��cZA<�ͤ'src/BaiduBce/Services/Blb/BlbClient.php^���c^��ԁ�1src/BaiduBce/Services/Blb/model/BackendServer.php���c���t��+src/BaiduBce/Services/Route/RouteClient.php� ��c� �+��+src/BaiduBce/Services/EipTp/EipTpClient.phph!��ch!�?�'src/BaiduBce/Services/Sms/SmsClient.php�Q��c�Q�.�P�-src/BaiduBce/Services/Vpn/util/CheckUtils.phpe��ce[��'src/BaiduBce/Services/Vpn/VpnClient.php
Y��c
YѤ�-�/src/BaiduBce/Services/Vpn/model/Reservation.php��cU�oݤ/src/BaiduBce/Services/Vpn/model/IpsecConfig.php���c�{e|j�-src/BaiduBce/Services/Vpn/model/IkeConfig.phpE��cE�S촤+src/BaiduBce/Services/Vpn/model/Billing.php���c�zI$�'src/BaiduBce/Services/Nat/NatClient.php����c��ao:/�/src/BaiduBce/Services/Nat/model/Reservation.php��c��a�+src/BaiduBce/Services/Nat/model/Billing.php���c�% ��+src/BaiduBce/Services/EipBp/EipBpClient.phpN8��cN8���Ȥ'src/BaiduBce/Services/Mms/MmsClient.php�!��c�!�V���'src/BaiduBce/Services/Vcr/VcrClient.php�e��c�e��Y��4src/BaiduBce/Services/PeerConn/model/Reservation.php��c���0src/BaiduBce/Services/PeerConn/model/Billing.php��c�~
�1src/BaiduBce/Services/PeerConn/PeerConnClient.php�[��c�[�(
�'src/BaiduBce/Services/Vca/VcaClient.php�9��c�9QP��'src/BaiduBce/Services/Vod/VodClient.php���c����<�'src/BaiduBce/Services/Cdn/CdnClient.php���c��i�x�'src/BaiduBce/Services/Mvs/MvsClient.phpX"��cX"F�P��'src/BaiduBce/Services/Bcc/BccClient.phpm��cm��N�1src/BaiduBce/Services/Bcc/model/EphemeralDisk.php���c�%��*�/src/BaiduBce/Services/Bcc/model/Reservation.php��c�h�ʤ:src/BaiduBce/Services/Bcc/model/SecurityGroupRuleModel.php���c�e��_�+src/BaiduBce/Services/Bcc/model/Billing.php���c��?��*src/BaiduBce/Services/Bos/StorageClass.php��c]���'src/BaiduBce/Services/Bos/CannedAcl.php��cZ�\�'src/BaiduBce/Services/Bos/BosClient.phpՍ��cՍ�5��(src/BaiduBce/Services/Bos/BosOptions.php���c��ES�'src/BaiduBce/Services/Vpc/VpcClient.php�-��c�-o���-src/BaiduBce/Services/Subnet/SubnetClient.php+��c+�ty�'src/BaiduBce/Services/Lss/LssClient.php,V��c,V�~���'src/BaiduBce/Services/Acl/AclClient.php(��c(�W�I�+src/BaiduBce/Services/Acl/model/AclRule.php#��c#Vj�F�'src/BaiduBce/Services/Eip/EipClient.php�:��c�:�����/src/BaiduBce/Services/Eip/model/Reservation.php��cr��+src/BaiduBce/Services/Eip/model/Billing.php��c��)�1src/BaiduBce/Services/EipGroup/EipGroupClient.phpj?��cj?+�KH�4src/BaiduBce/Services/EipGroup/model/Reservation.php��cٓ��0src/BaiduBce/Services/EipGroup/model/Billing.php)��c)��d�'src/BaiduBce/Services/Sts/StsClient.php"��c"}��P�+src/BaiduBce/Services/Media/MediaClient.phpb���cb�����<?php
//vendor
require_once __DIR__.'/vendor/autoload.php';
//auth
require_once __DIR__.'/src/BaiduBce/Auth/SignerInterface.php';
require_once __DIR__.'/src/BaiduBce/Auth/SignOptions.php';
require_once __DIR__.'/src/BaiduBce/Auth/BceV1Signer.php';
//Exception
require_once __DIR__.'/src/BaiduBce/Exception/BceBaseException.php';
require_once __DIR__.'/src/BaiduBce/Exception/BceClientException.php';
require_once __DIR__.'/src/BaiduBce/Exception/BceServiceException.php';
//Log
require_once __DIR__.'/src/BaiduBce/Log/LogFactoryInterface.php';
require_once __DIR__.'/src/BaiduBce/Log/LogFactory.php';
require_once __DIR__.'/src/BaiduBce/Log/MonoLogFactory.php';
require_once __DIR__.'/src/BaiduBce/Log/NullLogFactory.php';
//Util
require_once __DIR__.'/src/BaiduBce/Util/DateUtils.php';
//require_once __DIR__.'/src/BaiduBce/Util/GenerateMimeTypes.php';
require_once __DIR__.'/src/BaiduBce/Util/HashUtils.php';
require_once __DIR__.'/src/BaiduBce/Util/HttpUtils.php';
require_once __DIR__.'/src/BaiduBce/Util/mime.types.php';
require_once __DIR__.'/src/BaiduBce/Util/MimeTypes.php';
require_once __DIR__.'/src/BaiduBce/Util/StringUtils.php';
//PWD
require_once __DIR__.'/src/BaiduBce/Bce.php';
require_once __DIR__.'/src/BaiduBce/BceBaseClient.php';
require_once __DIR__.'/src/BaiduBce/BceClientConfigOptions.php';
require_once __DIR__.'/src/BaiduBce/BceHttpResponse.php';
//Http
require_once __DIR__.'/src/BaiduBce/Http/BceHttpClient.php';
require_once __DIR__.'/src/BaiduBce/Http/GuzzleLogAdapter.php';
require_once __DIR__.'/src/BaiduBce/Http/HttpContentTypes.php';
require_once __DIR__.'/src/BaiduBce/Http/HttpHeaders.php';
require_once __DIR__.'/src/BaiduBce/Http/HttpMethod.php';
//Services/bos
require_once __DIR__.'/src/BaiduBce/Services/Bos/BosClient.php';
require_once __DIR__.'/src/BaiduBce/Services/Bos/BosOptions.php';
require_once __DIR__.'/src/BaiduBce/Services/Bos/CannedAcl.php';
//Services/sts
require_once __DIR__.'/src/BaiduBce/Services/Sts/StsClient.php';The MIT License (MIT)

Copyright (c) 2013 My C-Sense

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# DeepCopy

DeepCopy helps you create deep copies (clones) of your objects. It is designed to handle cycles in the association graph.

[![Total Downloads](https://poser.pugx.org/myclabs/deep-copy/downloads.svg)](https://packagist.org/packages/myclabs/deep-copy)
[![Integrate](https://github.com/myclabs/DeepCopy/workflows/ci/badge.svg?branch=1.x)](https://github.com/myclabs/DeepCopy/actions)

## Table of Contents

1. [How](#how)
1. [Why](#why)
    1. [Using simply `clone`](#using-simply-clone)
    1. [Overriding `__clone()`](#overriding-__clone)
    1. [With `DeepCopy`](#with-deepcopy)
1. [How it works](#how-it-works)
1. [Going further](#going-further)
    1. [Matchers](#matchers)
        1. [Property name](#property-name)
        1. [Specific property](#specific-property)
        1. [Type](#type)
    1. [Filters](#filters)
        1. [`SetNullFilter`](#setnullfilter-filter)
        1. [`KeepFilter`](#keepfilter-filter)
        1. [`DoctrineCollectionFilter`](#doctrinecollectionfilter-filter)
        1. [`DoctrineEmptyCollectionFilter`](#doctrineemptycollectionfilter-filter)
        1. [`DoctrineProxyFilter`](#doctrineproxyfilter-filter)
        1. [`ReplaceFilter`](#replacefilter-type-filter)
        1. [`ShallowCopyFilter`](#shallowcopyfilter-type-filter)
1. [Edge cases](#edge-cases)
1. [Contributing](#contributing)
    1. [Tests](#tests)


## How?

Install with Composer:

```
composer require myclabs/deep-copy
```

Use it:

```php
use DeepCopy\DeepCopy;

$copier = new DeepCopy();
$myCopy = $copier->copy($myObject);
```


## Why?

- How do you create copies of your objects?

```php
$myCopy = clone $myObject;
```

- How do you create **deep** copies of your objects (i.e. copying also all the objects referenced in the properties)?

You use [`__clone()`](http://www.php.net/manual/en/language.oop5.cloning.php#object.clone) and implement the behavior
yourself.

- But how do you handle **cycles** in the association graph?

Now you're in for a big mess :(

![association graph](doc/graph.png)


### Using simply `clone`

![Using clone](doc/clone.png)


### Overriding `__clone()`

![Overriding __clone](doc/deep-clone.png)


### With `DeepCopy`

![With DeepCopy](doc/deep-copy.png)


## How it works

DeepCopy recursively traverses all the object's properties and clones them. To avoid cloning the same object twice it
keeps a hash map of all instances and thus preserves the object graph.

To use it:

```php
use function DeepCopy\deep_copy;

$copy = deep_copy($var);
```

Alternatively, you can create your own `DeepCopy` instance to configure it differently for example:

```php
use DeepCopy\DeepCopy;

$copier = new DeepCopy(true);

$copy = $copier->copy($var);
```

You may want to roll your own deep copy function:

```php
namespace Acme;

use DeepCopy\DeepCopy;

function deep_copy($var)
{
    static $copier = null;
    
    if (null === $copier) {
        $copier = new DeepCopy(true);
    }
    
    return $copier->copy($var);
}
```


## Going further

You can add filters to customize the copy process.

The method to add a filter is `DeepCopy\DeepCopy::addFilter($filter, $matcher)`,
with `$filter` implementing `DeepCopy\Filter\Filter`
and `$matcher` implementing `DeepCopy\Matcher\Matcher`.

We provide some generic filters and matchers.


### Matchers

  - `DeepCopy\Matcher` applies on a object attribute.
  - `DeepCopy\TypeMatcher` applies on any element found in graph, including array elements.


#### Property name

The `PropertyNameMatcher` will match a property by its name:

```php
use DeepCopy\Matcher\PropertyNameMatcher;

// Will apply a filter to any property of any objects named "id"
$matcher = new PropertyNameMatcher('id');
```


#### Specific property

The `PropertyMatcher` will match a specific property of a specific class:

```php
use DeepCopy\Matcher\PropertyMatcher;

// Will apply a filter to the property "id" of any objects of the class "MyClass"
$matcher = new PropertyMatcher('MyClass', 'id');
```


#### Type

The `TypeMatcher` will match any element by its type (instance of a class or any value that could be parameter of
[gettype()](http://php.net/manual/en/function.gettype.php) function):

```php
use DeepCopy\TypeMatcher\TypeMatcher;

// Will apply a filter to any object that is an instance of Doctrine\Common\Collections\Collection
$matcher = new TypeMatcher('Doctrine\Common\Collections\Collection');
```


### Filters

- `DeepCopy\Filter` applies a transformation to the object attribute matched by `DeepCopy\Matcher`
- `DeepCopy\TypeFilter` applies a transformation to any element matched by `DeepCopy\TypeMatcher`


#### `SetNullFilter` (filter)

Let's say for example that you are copying a database record (or a Doctrine entity), so you want the copy not to have
any ID:

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\SetNullFilter;
use DeepCopy\Matcher\PropertyNameMatcher;

$object = MyClass::load(123);
echo $object->id; // 123

$copier = new DeepCopy();
$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id'));

$copy = $copier->copy($object);

echo $copy->id; // null
```


#### `KeepFilter` (filter)

If you want a property to remain untouched (for example, an association to an object):

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\KeepFilter;
use DeepCopy\Matcher\PropertyMatcher;

$copier = new DeepCopy();
$copier->addFilter(new KeepFilter(), new PropertyMatcher('MyClass', 'category'));

$copy = $copier->copy($object);
// $copy->category has not been touched
```


#### `DoctrineCollectionFilter` (filter)

If you use Doctrine and want to copy an entity, you will need to use the `DoctrineCollectionFilter`:

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\Doctrine\DoctrineCollectionFilter;
use DeepCopy\Matcher\PropertyTypeMatcher;

$copier = new DeepCopy();
$copier->addFilter(new DoctrineCollectionFilter(), new PropertyTypeMatcher('Doctrine\Common\Collections\Collection'));

$copy = $copier->copy($object);
```


#### `DoctrineEmptyCollectionFilter` (filter)

If you use Doctrine and want to copy an entity who contains a `Collection` that you want to be reset, you can use the
`DoctrineEmptyCollectionFilter`

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\Doctrine\DoctrineEmptyCollectionFilter;
use DeepCopy\Matcher\PropertyMatcher;

$copier = new DeepCopy();
$copier->addFilter(new DoctrineEmptyCollectionFilter(), new PropertyMatcher('MyClass', 'myProperty'));

$copy = $copier->copy($object);

// $copy->myProperty will return an empty collection
```


#### `DoctrineProxyFilter` (filter)

If you use Doctrine and use cloning on lazy loaded entities, you might encounter errors mentioning missing fields on a
Doctrine proxy class (...\\\_\_CG\_\_\Proxy).
You can use the `DoctrineProxyFilter` to load the actual entity behind the Doctrine proxy class.
**Make sure, though, to put this as one of your very first filters in the filter chain so that the entity is loaded
before other filters are applied!**

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher;

$copier = new DeepCopy();
$copier->addFilter(new DoctrineProxyFilter(), new DoctrineProxyMatcher());

$copy = $copier->copy($object);

// $copy should now contain a clone of all entities, including those that were not yet fully loaded.
```


#### `ReplaceFilter` (type filter)

1. If you want to replace the value of a property:

```php
use DeepCopy\DeepCopy;
use DeepCopy\Filter\ReplaceFilter;
use DeepCopy\Matcher\PropertyMatcher;

$copier = new DeepCopy();
$callback = function ($currentValue) {
  return $currentValue . ' (copy)'
};
$copier->addFilter(new ReplaceFilter($callback), new PropertyMatcher('MyClass', 'title'));

$copy = $copier->copy($object);

// $copy->title will contain the data returned by the callback, e.g. 'The title (copy)'
```

2. If you want to replace whole element:

```php
use DeepCopy\DeepCopy;
use DeepCopy\TypeFilter\ReplaceFilter;
use DeepCopy\TypeMatcher\TypeMatcher;

$copier = new DeepCopy();
$callback = function (MyClass $myClass) {
  return get_class($myClass);
};
$copier->addTypeFilter(new ReplaceFilter($callback), new TypeMatcher('MyClass'));

$copy = $copier->copy([new MyClass, 'some string', new MyClass]);

// $copy will contain ['MyClass', 'some string', 'MyClass']
```


The `$callback` parameter of the `ReplaceFilter` constructor accepts any PHP callable.


#### `ShallowCopyFilter` (type filter)

Stop *DeepCopy* from recursively copying element, using standard `clone` instead:

```php
use DeepCopy\DeepCopy;
use DeepCopy\TypeFilter\ShallowCopyFilter;
use DeepCopy\TypeMatcher\TypeMatcher;
use Mockery as m;

$this->deepCopy = new DeepCopy();
$this->deepCopy->addTypeFilter(
	new ShallowCopyFilter,
	new TypeMatcher(m\MockInterface::class)
);

$myServiceWithMocks = new MyService(m::mock(MyDependency1::class), m::mock(MyDependency2::class));
// All mocks will be just cloned, not deep copied
```


## Edge cases

The following structures cannot be deep-copied with PHP Reflection. As a result they are shallow cloned and filters are
not applied. There is two ways for you to handle them:

- Implement your own `__clone()` method
- Use a filter with a type matcher


## Contributing

DeepCopy is distributed under the MIT license.


### Tests

Running the tests is simple:

```php
vendor/bin/phpunit
```

### Support

Get professional support via [the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-myclabs-deep-copy?utm_source=packagist-myclabs-deep-copy&utm_medium=referral&utm_campaign=readme).
# These are supported funding model platforms

github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: "packagist/myclabs/deep-copy"
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
name: "Continuous Integration"

on:
  - pull_request
  - push

env:
  COMPOSER_ROOT_VERSION: 1.99

jobs:
  composer-json-lint:
    name: "Lint composer.json"

    runs-on: "ubuntu-latest"

    strategy:
      matrix:
        php-version:
          - "8.1"

    steps:
      - name: "Checkout"
        uses: "actions/checkout@v2"

      - name: "Install PHP"
        uses: "shivammathur/setup-php@v2"
        with:
          coverage: "none"
          php-version: "${{ matrix.php-version }}"
          tools: composer-normalize

      - name: "Get composer cache directory"
        id: composercache
        run: echo "::set-output name=dir::$(composer config cache-files-dir)"

      - name: "Cache dependencies"
        uses: actions/cache@v2
        with:
          path: ${{ steps.composercache.outputs.dir }}
          key: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ matrix.dependencies }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ matrix.dependencies }}-composer-

      - name: "Install dependencies"
        run: "composer update --no-interaction --no-progress"

      - name: "Validate composer.json"
        run: "composer validate --strict"

      - name: "Normalize composer.json"
        run: "composer-normalize --dry-run"

  tests:
    name: "Tests"

    runs-on: "ubuntu-latest"

    strategy:
      matrix:
        php-version:
          - "7.1"
          - "7.2"
          - "7.3"
          - "7.4"
          - "8.0"
          - "8.1"
        dependencies:
          - "lowest"
          - "highest"

    steps:
      - name: "Checkout"
        uses: "actions/checkout@v2"

      - name: "Install PHP"
        uses: "shivammathur/setup-php@v2"
        with:
          php-version: "${{ matrix.php-version }}"
          ini-values: zend.assertions=1

      - name: "Get composer cache directory"
        id: composercache
        run: echo "::set-output name=dir::$(composer config cache-files-dir)"

      - name: "Cache dependencies"
        uses: actions/cache@v2
        with:
          path: ${{ steps.composercache.outputs.dir }}
          key: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ matrix.dependencies }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ matrix.dependencies }}-composer-

      - name: "Install lowest dependencies"
        if: ${{ matrix.dependencies == 'lowest' }}
        run: "composer update --no-interaction --no-progress --prefer-lowest"

      - name: "Install highest dependencies"
        if: ${{ matrix.dependencies == 'highest' }}
        run: "composer update --no-interaction --no-progress"

      - name: "Run tests"
        timeout-minutes: 3
        run: "vendor/bin/phpunit"
{
    "name": "myclabs/deep-copy",
    "description": "Create deep copies (clones) of your objects",
    "license": "MIT",
    "type": "library",
    "keywords": [
        "clone",
        "copy",
        "duplicate",
        "object",
        "object graph"
    ],
    "require": {
        "php": "^7.1 || ^8.0"
    },
    "require-dev": {
        "doctrine/collections": "^1.6.8",
        "doctrine/common": "^2.13.3 || ^3.2.2",
        "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
    },
    "conflict": {
        "doctrine/collections": "<1.6.8",
        "doctrine/common": "<2.13.3 || >=3,<3.2.2"
    },
    "autoload": {
        "psr-4": {
            "DeepCopy\\": "src/DeepCopy/"
        },
        "files": [
            "src/DeepCopy/deep_copy.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "DeepCopy\\": "fixtures/",
            "DeepCopyTest\\": "tests/DeepCopyTest/"
        }
    },
    "config": {
        "sort-packages": true
    }
}
<?php

namespace DeepCopy;

use function function_exists;

if (false === function_exists('DeepCopy\deep_copy')) {
    /**
     * Deep copies the given value.
     *
     * @param mixed $value
     * @param bool  $useCloneMethod
     *
     * @return mixed
     */
    function deep_copy($value, $useCloneMethod = false)
    {
        return (new DeepCopy($useCloneMethod))->copy($value);
    }
}
<?php

namespace DeepCopy\Matcher;

/**
 * @final
 */
class PropertyMatcher implements Matcher
{
    /**
     * @var string
     */
    private $class;

    /**
     * @var string
     */
    private $property;

    /**
     * @param string $class    Class name
     * @param string $property Property name
     */
    public function __construct($class, $property)
    {
        $this->class = $class;
        $this->property = $property;
    }

    /**
     * Matches a specific property of a specific class.
     *
     * {@inheritdoc}
     */
    public function matches($object, $property)
    {
        return ($object instanceof $this->class) && $property == $this->property;
    }
}
<?php

namespace DeepCopy\Matcher\Doctrine;

use DeepCopy\Matcher\Matcher;
use Doctrine\Persistence\Proxy;

/**
 * @final
 */
class DoctrineProxyMatcher implements Matcher
{
    /**
     * Matches a Doctrine Proxy class.
     *
     * {@inheritdoc}
     */
    public function matches($object, $property)
    {
        return $object instanceof Proxy;
    }
}
<?php

namespace DeepCopy\Matcher;

interface Matcher
{
    /**
     * @param object $object
     * @param string $property
     *
     * @return boolean
     */
    public function matches($object, $property);
}
<?php

namespace DeepCopy\Matcher;

/**
 * @final
 */
class PropertyNameMatcher implements Matcher
{
    /**
     * @var string
     */
    private $property;

    /**
     * @param string $property Property name
     */
    public function __construct($property)
    {
        $this->property = $property;
    }

    /**
     * Matches a property by its name.
     *
     * {@inheritdoc}
     */
    public function matches($object, $property)
    {
        return $property == $this->property;
    }
}
<?php

namespace DeepCopy\Matcher;

use DeepCopy\Reflection\ReflectionHelper;
use ReflectionException;

/**
 * Matches a property by its type.
 *
 * It is recommended to use {@see DeepCopy\TypeFilter\TypeFilter} instead, as it applies on all occurrences
 * of given type in copied context (eg. array elements), not just on object properties.
 *
 * @final
 */
class PropertyTypeMatcher implements Matcher
{
    /**
     * @var string
     */
    private $propertyType;

    /**
     * @param string $propertyType Property type
     */
    public function __construct($propertyType)
    {
        $this->propertyType = $propertyType;
    }

    /**
     * {@inheritdoc}
     */
    public function matches($object, $property)
    {
        try {
            $reflectionProperty = ReflectionHelper::getProperty($object, $property);
        } catch (ReflectionException $exception) {
            return false;
        }

        $reflectionProperty->setAccessible(true);

        // Uninitialized properties (for PHP >7.4)
        if (method_exists($reflectionProperty, 'isInitialized') && !$reflectionProperty->isInitialized($object)) {
            // null instanceof $this->propertyType
            return false;
        }

        return $reflectionProperty->getValue($object) instanceof $this->propertyType;
    }
}
<?php

namespace DeepCopy;

use ArrayObject;
use DateInterval;
use DateTimeInterface;
use DateTimeZone;
use DeepCopy\Exception\CloneException;
use DeepCopy\Filter\Filter;
use DeepCopy\Matcher\Matcher;
use DeepCopy\Reflection\ReflectionHelper;
use DeepCopy\TypeFilter\Date\DateIntervalFilter;
use DeepCopy\TypeFilter\Spl\ArrayObjectFilter;
use DeepCopy\TypeFilter\Spl\SplDoublyLinkedListFilter;
use DeepCopy\TypeFilter\TypeFilter;
use DeepCopy\TypeMatcher\TypeMatcher;
use ReflectionObject;
use ReflectionProperty;
use SplDoublyLinkedList;

/**
 * @final
 */
class DeepCopy
{
    /**
     * @var object[] List of objects copied.
     */
    private $hashMap = [];

    /**
     * Filters to apply.
     *
     * @var array Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
     */
    private $filters = [];

    /**
     * Type Filters to apply.
     *
     * @var array Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
     */
    private $typeFilters = [];

    /**
     * @var bool
     */
    private $skipUncloneable = false;

    /**
     * @var bool
     */
    private $useCloneMethod;

    /**
     * @param bool $useCloneMethod   If set to true, when an object implements the __clone() function, it will be used
     *                               instead of the regular deep cloning.
     */
    public function __construct($useCloneMethod = false)
    {
        $this->useCloneMethod = $useCloneMethod;

        $this->addTypeFilter(new ArrayObjectFilter($this), new TypeMatcher(ArrayObject::class));
        $this->addTypeFilter(new DateIntervalFilter(), new TypeMatcher(DateInterval::class));
        $this->addTypeFilter(new SplDoublyLinkedListFilter($this), new TypeMatcher(SplDoublyLinkedList::class));
    }

    /**
     * If enabled, will not throw an exception when coming across an uncloneable property.
     *
     * @param $skipUncloneable
     *
     * @return $this
     */
    public function skipUncloneable($skipUncloneable = true)
    {
        $this->skipUncloneable = $skipUncloneable;

        return $this;
    }

    /**
     * Deep copies the given object.
     *
     * @param mixed $object
     *
     * @return mixed
     */
    public function copy($object)
    {
        $this->hashMap = [];

        return $this->recursiveCopy($object);
    }

    public function addFilter(Filter $filter, Matcher $matcher)
    {
        $this->filters[] = [
            'matcher' => $matcher,
            'filter'  => $filter,
        ];
    }

    public function prependFilter(Filter $filter, Matcher $matcher)
    {
        array_unshift($this->filters, [
            'matcher' => $matcher,
            'filter'  => $filter,
        ]);
    }

    public function addTypeFilter(TypeFilter $filter, TypeMatcher $matcher)
    {
        $this->typeFilters[] = [
            'matcher' => $matcher,
            'filter'  => $filter,
        ];
    }

    private function recursiveCopy($var)
    {
        // Matches Type Filter
        if ($filter = $this->getFirstMatchedTypeFilter($this->typeFilters, $var)) {
            return $filter->apply($var);
        }

        // Resource
        if (is_resource($var)) {
            return $var;
        }

        // Array
        if (is_array($var)) {
            return $this->copyArray($var);
        }

        // Scalar
        if (! is_object($var)) {
            return $var;
        }

        // Enum
        if (PHP_VERSION_ID >= 80100 && enum_exists(get_class($var))) {
            return $var;
        }

        // Object
        return $this->copyObject($var);
    }

    /**
     * Copy an array
     * @param array $array
     * @return array
     */
    private function copyArray(array $array)
    {
        foreach ($array as $key => $value) {
            $array[$key] = $this->recursiveCopy($value);
        }

        return $array;
    }

    /**
     * Copies an object.
     *
     * @param object $object
     *
     * @throws CloneException
     *
     * @return object
     */
    private function copyObject($object)
    {
        $objectHash = spl_object_hash($object);

        if (isset($this->hashMap[$objectHash])) {
            return $this->hashMap[$objectHash];
        }

        $reflectedObject = new ReflectionObject($object);
        $isCloneable = $reflectedObject->isCloneable();

        if (false === $isCloneable) {
            if ($this->skipUncloneable) {
                $this->hashMap[$objectHash] = $object;

                return $object;
            }

            throw new CloneException(
                sprintf(
                    'The class "%s" is not cloneable.',
                    $reflectedObject->getName()
                )
            );
        }

        $newObject = clone $object;
        $this->hashMap[$objectHash] = $newObject;

        if ($this->useCloneMethod && $reflectedObject->hasMethod('__clone')) {
            return $newObject;
        }

        if ($newObject instanceof DateTimeInterface || $newObject instanceof DateTimeZone) {
            return $newObject;
        }

        foreach (ReflectionHelper::getProperties($reflectedObject) as $property) {
            $this->copyObjectProperty($newObject, $property);
        }

        return $newObject;
    }

    private function copyObjectProperty($object, ReflectionProperty $property)
    {
        // Ignore static properties
        if ($property->isStatic()) {
            return;
        }

        // Apply the filters
        foreach ($this->filters as $item) {
            /** @var Matcher $matcher */
            $matcher = $item['matcher'];
            /** @var Filter $filter */
            $filter = $item['filter'];

            if ($matcher->matches($object, $property->getName())) {
                $filter->apply(
                    $object,
                    $property->getName(),
                    function ($object) {
                        return $this->recursiveCopy($object);
                    }
                );

                // If a filter matches, we stop processing this property
                return;
            }
        }

        $property->setAccessible(true);

        // Ignore uninitialized properties (for PHP >7.4)
        if (method_exists($property, 'isInitialized') && !$property->isInitialized($object)) {
            return;
        }

        $propertyValue = $property->getValue($object);

        // Copy the property
        $property->setValue($object, $this->recursiveCopy($propertyValue));
    }

    /**
     * Returns first filter that matches variable, `null` if no such filter found.
     *
     * @param array $filterRecords Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and
     *                             'matcher' with value of type {@see TypeMatcher}
     * @param mixed $var
     *
     * @return TypeFilter|null
     */
    private function getFirstMatchedTypeFilter(array $filterRecords, $var)
    {
        $matched = $this->first(
            $filterRecords,
            function (array $record) use ($var) {
                /* @var TypeMatcher $matcher */
                $matcher = $record['matcher'];

                return $matcher->matches($var);
            }
        );

        return isset($matched) ? $matched['filter'] : null;
    }

    /**
     * Returns first element that matches predicate, `null` if no such element found.
     *
     * @param array    $elements Array of ['filter' => Filter, 'matcher' => Matcher] pairs.
     * @param callable $predicate Predicate arguments are: element.
     *
     * @return array|null Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and 'matcher'
     *                    with value of type {@see TypeMatcher} or `null`.
     */
    private function first(array $elements, callable $predicate)
    {
        foreach ($elements as $element) {
            if (call_user_func($predicate, $element)) {
                return $element;
            }
        }

        return null;
    }
}
<?php

namespace DeepCopy\Filter;

use DeepCopy\Reflection\ReflectionHelper;

/**
 * @final
 */
class ReplaceFilter implements Filter
{
    /**
     * @var callable
     */
    protected $callback;

    /**
     * @param callable $callable Will be called to get the new value for each property to replace
     */
    public function __construct(callable $callable)
    {
        $this->callback = $callable;
    }

    /**
     * Replaces the object property by the result of the callback called with the object property.
     *
     * {@inheritdoc}
     */
    public function apply($object, $property, $objectCopier)
    {
        $reflectionProperty = ReflectionHelper::getProperty($object, $property);
        $reflectionProperty->setAccessible(true);

        $value = call_user_func($this->callback, $reflectionProperty->getValue($object));

        $reflectionProperty->setValue($object, $value);
    }
}
<?php

namespace DeepCopy\Filter;

class KeepFilter implements Filter
{
    /**
     * Keeps the value of the object property.
     *
     * {@inheritdoc}
     */
    public function apply($object, $property, $objectCopier)
    {
        // Nothing to do
    }
}
<?php

namespace DeepCopy\Filter\Doctrine;

use DeepCopy\Filter\Filter;
use DeepCopy\Reflection\ReflectionHelper;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @final
 */
class DoctrineEmptyCollectionFilter implements Filter
{
    /**
     * Sets the object property to an empty doctrine collection.
     *
     * @param object   $object
     * @param string   $property
     * @param callable $objectCopier
     */
    public function apply($object, $property, $objectCopier)
    {
        $reflectionProperty = ReflectionHelper::getProperty($object, $property);
        $reflectionProperty->setAccessible(true);

        $reflectionProperty->setValue($object, new ArrayCollection());
    }
} <?php

namespace DeepCopy\Filter\Doctrine;

use DeepCopy\Filter\Filter;
use DeepCopy\Reflection\ReflectionHelper;

/**
 * @final
 */
class DoctrineCollectionFilter implements Filter
{
    /**
     * Copies the object property doctrine collection.
     *
     * {@inheritdoc}
     */
    public function apply($object, $property, $objectCopier)
    {
        $reflectionProperty = ReflectionHelper::getProperty($object, $property);

        $reflectionProperty->setAccessible(true);
        $oldCollection = $reflectionProperty->getValue($object);

        $newCollection = $oldCollection->map(
            function ($item) use ($objectCopier) {
                return $objectCopier($item);
            }
        );

        $reflectionProperty->setValue($object, $newCollection);
    }
}
<?php

namespace DeepCopy\Filter\Doctrine;

use DeepCopy\Filter\Filter;

/**
 * @final
 */
class DoctrineProxyFilter implements Filter
{
    /**
     * Triggers the magic method __load() on a Doctrine Proxy class to load the
     * actual entity from the database.
     *
     * {@inheritdoc}
     */
    public function apply($object, $property, $objectCopier)
    {
        $object->__load();
    }
}
<?php

namespace DeepCopy\Filter;

/**
 * Filter to apply to a property while copying an object
 */
interface Filter
{
    /**
     * Applies the filter to the object.
     *
     * @param object   $object
     * @param string   $property
     * @param callable $objectCopier
     */
    public function apply($object, $property, $objectCopier);
}
<?php

namespace DeepCopy\Filter;

use DeepCopy\Reflection\ReflectionHelper;

/**
 * @final
 */
class SetNullFilter implements Filter
{
    /**
     * Sets the object property to null.
     *
     * {@inheritdoc}
     */
    public function apply($object, $property, $objectCopier)
    {
        $reflectionProperty = ReflectionHelper::getProperty($object, $property);

        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($object, null);
    }
}
<?php

namespace DeepCopy\TypeMatcher;

class TypeMatcher
{
    /**
     * @var string
     */
    private $type;

    /**
     * @param string $type
     */
    public function __construct($type)
    {
        $this->type = $type;
    }

    /**
     * @param mixed $element
     *
     * @return boolean
     */
    public function matches($element)
    {
        return is_object($element) ? is_a($element, $this->type) : gettype($element) === $this->type;
    }
}
<?php

namespace DeepCopy\Exception;

use UnexpectedValueException;

class CloneException extends UnexpectedValueException
{
} <?php

namespace DeepCopy\Exception;

use ReflectionException;

class PropertyException extends ReflectionException
{
}
<?php

namespace DeepCopy\Reflection;

use DeepCopy\Exception\PropertyException;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
use ReflectionProperty;

class ReflectionHelper
{
    /**
     * Retrieves all properties (including private ones), from object and all its ancestors.
     *
     * Standard \ReflectionClass->getProperties() does not return private properties from ancestor classes.
     *
     * @author muratyaman@gmail.com
     * @see http://php.net/manual/en/reflectionclass.getproperties.php
     *
     * @param ReflectionClass $ref
     *
     * @return ReflectionProperty[]
     */
    public static function getProperties(ReflectionClass $ref)
    {
        $props = $ref->getProperties();
        $propsArr = array();

        foreach ($props as $prop) {
            $propertyName = $prop->getName();
            $propsArr[$propertyName] = $prop;
        }

        if ($parentClass = $ref->getParentClass()) {
            $parentPropsArr = self::getProperties($parentClass);
            foreach ($propsArr as $key => $property) {
                $parentPropsArr[$key] = $property;
            }

            return $parentPropsArr;
        }

        return $propsArr;
    }

    /**
     * Retrieves property by name from object and all its ancestors.
     *
     * @param object|string $object
     * @param string $name
     *
     * @throws PropertyException
     * @throws ReflectionException
     *
     * @return ReflectionProperty
     */
    public static function getProperty($object, $name)
    {
        $reflection = is_object($object) ? new ReflectionObject($object) : new ReflectionClass($object);

        if ($reflection->hasProperty($name)) {
            return $reflection->getProperty($name);
        }

        if ($parentClass = $reflection->getParentClass()) {
            return self::getProperty($parentClass->getName(), $name);
        }

        throw new PropertyException(
            sprintf(
                'The class "%s" doesn\'t have a property with the given name: "%s".',
                is_object($object) ? get_class($object) : $object,
                $name
            )
        );
    }
}
<?php

namespace DeepCopy\TypeFilter;

/**
 * @final
 */
class ReplaceFilter implements TypeFilter
{
    /**
     * @var callable
     */
    protected $callback;

    /**
     * @param callable $callable Will be called to get the new value for each element to replace
     */
    public function __construct(callable $callable)
    {
        $this->callback = $callable;
    }

    /**
     * {@inheritdoc}
     */
    public function apply($element)
    {
        return call_user_func($this->callback, $element);
    }
}
<?php

namespace DeepCopy\TypeFilter\Spl;

use Closure;
use DeepCopy\DeepCopy;
use DeepCopy\TypeFilter\TypeFilter;
use SplDoublyLinkedList;

/**
 * @final
 */
class SplDoublyLinkedListFilter implements TypeFilter
{
    private $copier;

    public function __construct(DeepCopy $copier)
    {
        $this->copier = $copier;
    }

    /**
     * {@inheritdoc}
     */
    public function apply($element)
    {
        $newElement = clone $element;

        $copy = $this->createCopyClosure();

        return $copy($newElement);
    }

    private function createCopyClosure()
    {
        $copier = $this->copier;

        $copy = function (SplDoublyLinkedList $list) use ($copier) {
            // Replace each element in the list with a deep copy of itself
            for ($i = 1; $i <= $list->count(); $i++) {
                $copy = $copier->recursiveCopy($list->shift());

                $list->push($copy);
            }

            return $list;
        };

        return Closure::bind($copy, null, DeepCopy::class);
    }
}
<?php

namespace DeepCopy\TypeFilter\Spl;

/**
 * @deprecated Use {@see SplDoublyLinkedListFilter} instead.
 */
class SplDoublyLinkedList extends SplDoublyLinkedListFilter
{
}
<?php
namespace DeepCopy\TypeFilter\Spl;

use DeepCopy\DeepCopy;
use DeepCopy\TypeFilter\TypeFilter;

/**
 * In PHP 7.4 the storage of an ArrayObject isn't returned as
 * ReflectionProperty. So we deep copy its array copy.
 */
final class ArrayObjectFilter implements TypeFilter
{
    /**
     * @var DeepCopy
     */
    private $copier;

    public function __construct(DeepCopy $copier)
    {
        $this->copier = $copier;
    }

    /**
     * {@inheritdoc}
     */
    public function apply($arrayObject)
    {
        $clone = clone $arrayObject;
        foreach ($arrayObject->getArrayCopy() as $k => $v) {
            $clone->offsetSet($k, $this->copier->copy($v));
        }

        return $clone;
    }
}

<?php

namespace DeepCopy\TypeFilter\Date;

use DateInterval;
use DeepCopy\TypeFilter\TypeFilter;

/**
 * @final
 *
 * @deprecated Will be removed in 2.0. This filter will no longer be necessary in PHP 7.1+.
 */
class DateIntervalFilter implements TypeFilter
{

    /**
     * {@inheritdoc}
     *
     * @param DateInterval $element
     *
     * @see http://news.php.net/php.bugs/205076
     */
    public function apply($element)
    {
        $copy = new DateInterval('P0D');

        foreach ($element as $propertyName => $propertyValue) {
            $copy->{$propertyName} = $propertyValue;
        }

        return $copy;
    }
}
<?php

namespace DeepCopy\TypeFilter;

/**
 * @final
 */
class ShallowCopyFilter implements TypeFilter
{
    /**
     * {@inheritdoc}
     */
    public function apply($element)
    {
        return clone $element;
    }
}
<?php

namespace DeepCopy\TypeFilter;

interface TypeFilter
{
    /**
     * Applies the filter to the object.
     *
     * @param mixed $element
     */
    public function apply($element);
}
<?php

// autoload.php @generated by Composer

if (PHP_VERSION_ID < 50600) {
    if (!headers_sent()) {
        header('HTTP/1.1 500 Internal Server Error');
    }
    $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
    if (!ini_get('display_errors')) {
        if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
            fwrite(STDERR, $err);
        } elseif (!headers_sent()) {
            echo $err;
        }
    }
    trigger_error(
        $err,
        E_USER_ERROR
    );
}

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit5d90551c137e56c44ad81de477daaa67::getLoader();
#!/usr/bin/env php
<?php

/**
 * Proxy PHP file generated by Composer
 *
 * This file includes the referenced bin path (../phpunit/phpunit/phpunit)
 * using a stream wrapper to prevent the shebang from being output on PHP<8
 *
 * @generated
 */

namespace Composer;

$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
$GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST'] = $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'] = array(realpath(__DIR__ . '/..'.'/phpunit/phpunit/phpunit'));

if (PHP_VERSION_ID < 80000) {
    if (!class_exists('Composer\BinProxyWrapper')) {
        /**
         * @internal
         */
        final class BinProxyWrapper
        {
            private $handle;
            private $position;
            private $realpath;

            public function stream_open($path, $mode, $options, &$opened_path)
            {
                // get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
                $opened_path = substr($path, 17);
                $this->realpath = realpath($opened_path) ?: $opened_path;
                $opened_path = 'phpvfscomposer://'.$this->realpath;
                $this->handle = fopen($this->realpath, $mode);
                $this->position = 0;

                return (bool) $this->handle;
            }

            public function stream_read($count)
            {
                $data = fread($this->handle, $count);

                if ($this->position === 0) {
                    $data = preg_replace('{^#!.*\r?\n}', '', $data);
                }
                $data = str_replace('__DIR__', var_export(dirname($this->realpath), true), $data);
                $data = str_replace('__FILE__', var_export($this->realpath, true), $data);

                $this->position += strlen($data);

                return $data;
            }

            public function stream_cast($castAs)
            {
                return $this->handle;
            }

            public function stream_close()
            {
                fclose($this->handle);
            }

            public function stream_lock($operation)
            {
                return $operation ? flock($this->handle, $operation) : true;
            }

            public function stream_seek($offset, $whence)
            {
                if (0 === fseek($this->handle, $offset, $whence)) {
                    $this->position = ftell($this->handle);
                    return true;
                }

                return false;
            }

            public function stream_tell()
            {
                return $this->position;
            }

            public function stream_eof()
            {
                return feof($this->handle);
            }

            public function stream_stat()
            {
                return array();
            }

            public function stream_set_option($option, $arg1, $arg2)
            {
                return true;
            }

            public function url_stat($path, $flags)
            {
                $path = substr($path, 17);
                if (file_exists($path)) {
                    return stat($path);
                }

                return false;
            }
        }
    }

    if (
        (function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
        || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
    ) {
        include("phpvfscomposer://" . __DIR__ . '/..'.'/phpunit/phpunit/phpunit');
        exit(0);
    }
}

include __DIR__ . '/..'.'/phpunit/phpunit/phpunit';
{
    "_readme": [
        "This file locks the dependencies of your project to a known state",
        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
        "This file is @generated automatically"
    ],
    "content-hash": "b010f1b3d9d47d431ee1cb54ac1de755",
    "packages": [],
    "packages-dev": [],
    "aliases": [],
    "minimum-stability": "stable",
    "stability-flags": [],
    "prefer-stable": false,
    "prefer-lowest": false,
    "platform": {
        "php": "^7.2 || ^8.0",
        "ext-xmlwriter": "*",
        "ext-dom": "*",
        "ext-tokenizer": "*"
    },
    "platform-dev": []
}
Tokenizer

Copyright (c) 2017 Arne Blankerts <arne@blankerts.de> and contributors
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 Arne Blankerts nor the names of 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 HOLDER OR 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.
# Changelog

All notable changes to Tokenizer are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.


## [1.2.1] - 2021-07-28

### Fixed

* [#13](https://github.com/theseer/tokenizer/issues/13): Fatal error when tokenizing files that contain only a single empty line


## [1.2.0] - 2020-07-13

This release is now PHP 8.0 compliant.

### Fixed

* Whitespace handling in general (only noticable in the intermediate `TokenCollection`) is now consitent  

### Changed

* Updated `Tokenizer` to deal with changed whitespace handling in PHP 8.0
  The XMLSerializer was unaffected.


## [1.1.3] - 2019-06-14

### Changed

* Ensure XMLSerializer can deal with empty token collections

### Fixed

* [#2](https://github.com/theseer/tokenizer/issues/2): Fatal error in infection / phpunit


## [1.1.2] - 2019-04-04

### Changed

* Reverted PHPUnit 8 test update to stay PHP 7.0 compliant


## [1.1.1] - 2019-04-03

### Fixed

* [#1](https://github.com/theseer/tokenizer/issues/1): Empty file causes invalid array read 

### Changed

* Tests should now be PHPUnit 8 compliant


## [1.1.0] - 2017-04-07

### Added

* Allow use of custom namespace for XML serialization


## [1.0.0] - 2017-04-05

Initial Release

[1.1.3]: https://github.com/theseer/tokenizer/compare/1.1.2...1.1.3
[1.1.2]: https://github.com/theseer/tokenizer/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/theseer/tokenizer/compare/1.1.0...1.1.1
[1.1.0]: https://github.com/theseer/tokenizer/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/theseer/tokenizer/compare/b2493e57de80c1b7414219b28503fa5c6b4d0a98...1.0.0
# Tokenizer

A small library for converting tokenized PHP source code into XML.

[![Test](https://github.com/theseer/tokenizer/actions/workflows/ci.yml/badge.svg)](https://github.com/theseer/tokenizer/actions/workflows/ci.yml)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/theseer/tokenizer/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/theseer/tokenizer/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/theseer/tokenizer/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/theseer/tokenizer/?branch=master)
[![Build Status](https://scrutinizer-ci.com/g/theseer/tokenizer/badges/build.png?b=master)](https://scrutinizer-ci.com/g/theseer/tokenizer/build-status/master)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require theseer/tokenizer

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev theseer/tokenizer

## Usage examples

```php
$tokenizer = new TheSeer\Tokenizer\Tokenizer();
$tokens = $tokenizer->parse(file_get_contents(__DIR__ . '/src/XMLSerializer.php'));

$serializer = new TheSeer\Tokenizer\XMLSerializer();
$xml = $serializer->toXML($tokens);

echo $xml;
```

The generated XML structure looks something like this:

```xml
<?xml version="1.0"?>
<source xmlns="https://github.com/theseer/tokenizer">
 <line no="1">
  <token name="T_OPEN_TAG">&lt;?php </token>
  <token name="T_DECLARE">declare</token>
  <token name="T_OPEN_BRACKET">(</token>
  <token name="T_STRING">strict_types</token>
  <token name="T_WHITESPACE"> </token>
  <token name="T_EQUAL">=</token>
  <token name="T_WHITESPACE"> </token>
  <token name="T_LNUMBER">1</token>
  <token name="T_CLOSE_BRACKET">)</token>
  <token name="T_SEMICOLON">;</token>
 </line>
</source>
```
{
  "name": "theseer/tokenizer",
  "description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
  "license": "BSD-3-Clause",
  "authors": [
    {
      "name": "Arne Blankerts",
      "email": "arne@blankerts.de",
      "role": "Developer"
    }
  ],
  "support": {
    "issues": "https://github.com/theseer/tokenizer/issues"
  },
  "require": {
    "php": "^7.2 || ^8.0",
    "ext-xmlwriter": "*",
    "ext-dom": "*",
    "ext-tokenizer": "*"
  },
  "autoload": {
    "classmap": [
      "src/"
    ]
  }
}

<?php

require __DIR__ . '/tools/php-cs-fixer.d/PhpdocSingleLineVarFixer.php';

return PhpCsFixer\Config::create()
    ->registerCustomFixers([
        new \PharIo\CSFixer\PhpdocSingleLineVarFixer()
    ])
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'PharIo/phpdoc_single_line_var_fixer'           => true,

            'align_multiline_comment'                       => true,
            'array_indentation'                             => true,
            'array_syntax'                                  => ['syntax' => 'short'],
            'binary_operator_spaces'                        => [
                'operators' => [
                    '='  => 'align_single_space_minimal',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace'                    => true,
            'blank_line_after_opening_tag'                  => false,
            'blank_line_before_statement'                   => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces'                                        => [
                'allow_single_line_closure'                   => false,
                'position_after_anonymous_constructs'         => 'same',
                'position_after_control_structures'           => 'same',
                'position_after_functions_and_oop_constructs' => 'same'
            ],
            'cast_spaces'                                   => ['space' => 'none'],

            // This fixer removes the blank line at class start, no way to disable that, so we disable the fixer :(
            //'class_attributes_separation'                   => ['elements' => ['const', 'method', 'property']],

            'combine_consecutive_issets'                    => true,
            'combine_consecutive_unsets'                    => true,
            'compact_nullable_typehint'                     => true,
            'concat_space'                                  => ['spacing' => 'one'],
            'date_time_immutable'                           => true,
            'declare_equal_normalize'                       => ['space' => 'single'],
            'declare_strict_types'                          => true,
            'dir_constant'                                  => true,
            'elseif'                                        => true,
            'encoding'                                      => true,
            'full_opening_tag'                              => true,
            'fully_qualified_strict_types'                  => true,
            'function_declaration'                          => [
                'closure_function_spacing' => 'one'
            ],
            'header_comment'                                => false,
            'indentation_type'                              => true,
            'is_null'                                       => true,
            'line_ending'                                   => true,
            'list_syntax'                                   => ['syntax' => 'short'],
            'logical_operators'                             => true,
            'lowercase_cast'                                => true,
            'lowercase_constants'                           => true,
            'lowercase_keywords'                            => true,
            'lowercase_static_reference'                    => true,
            'magic_constant_casing'                         => true,
            'method_argument_space'                         => ['ensure_fully_multiline' => true],
            'modernize_types_casting'                       => true,
            'multiline_comment_opening_closing'             => true,
            'multiline_whitespace_before_semicolons'        => true,
            'native_constant_invocation'                    => true,
            'native_function_casing'                        => true,
            'native_function_invocation'                    => true,
            'new_with_braces'                               => false,
            'no_alias_functions'                            => true,
            'no_alternative_syntax'                         => true,
            'no_blank_lines_after_class_opening'            => false,
            'no_blank_lines_after_phpdoc'                   => true,
            'no_blank_lines_before_namespace'               => true,
            'no_closing_tag'                                => true,
            'no_empty_comment'                              => true,
            'no_empty_phpdoc'                               => true,
            'no_empty_statement'                            => true,
            'no_extra_blank_lines'                          => true,
            'no_homoglyph_names'                            => true,
            'no_leading_import_slash'                       => true,
            'no_leading_namespace_whitespace'               => true,
            'no_mixed_echo_print'                           => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow'   => true,
            'no_null_property_initialization'               => true,
            'no_php4_constructor'                           => true,
            'no_short_bool_cast'                            => true,
            'no_short_echo_tag'                             => true,
            'no_singleline_whitespace_before_semicolons'    => true,
            'no_spaces_after_function_name'                 => true,
            'no_spaces_inside_parenthesis'                  => true,
            'no_superfluous_elseif'                         => true,
            'no_superfluous_phpdoc_tags'                    => true,
            'no_trailing_comma_in_list_call'                => true,
            'no_trailing_comma_in_singleline_array'         => true,
            'no_trailing_whitespace'                        => true,
            'no_trailing_whitespace_in_comment'             => true,
            'no_unneeded_control_parentheses'               => false,
            'no_unneeded_curly_braces'                      => false,
            'no_unneeded_final_method'                      => true,
            'no_unreachable_default_argument_value'         => true,
            'no_unset_on_property'                          => true,
            'no_unused_imports'                             => true,
            'no_useless_else'                               => true,
            'no_useless_return'                             => true,
            'no_whitespace_before_comma_in_array'           => true,
            'no_whitespace_in_blank_line'                   => true,
            'non_printable_character'                       => true,
            'normalize_index_brace'                         => true,
            'object_operator_without_whitespace'            => true,
            'ordered_class_elements'                        => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports'                               => true,
            'phpdoc_add_missing_param_annotation'           => true,
            'phpdoc_align'                                  => true,
            'phpdoc_annotation_without_dot'                 => true,
            'phpdoc_indent'                                 => true,
            'phpdoc_no_access'                              => true,
            'phpdoc_no_empty_return'                        => true,
            'phpdoc_no_package'                             => true,
            'phpdoc_order'                                  => true,
            'phpdoc_return_self_reference'                  => true,
            'phpdoc_scalar'                                 => true,
            'phpdoc_separation'                             => true,
            'phpdoc_single_line_var_spacing'                => true,
            'phpdoc_to_comment'                             => false,
            'phpdoc_trim'                                   => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types'                                  => ['groups' => ['simple', 'meta']],
            'phpdoc_types_order'                            => true,
            'phpdoc_to_return_type'                         => true,
            'phpdoc_var_without_name'                       => true,
            'pow_to_exponentiation'                         => true,
            'protected_to_private'                          => true,
            'return_assignment'                             => true,
            'return_type_declaration'                       => ['space_before' => 'none'],
            'self_accessor'                                 => false,
            'semicolon_after_instruction'                   => true,
            'set_type_to_cast'                              => true,
            'short_scalar_cast'                             => true,
            'simplified_null_return'                        => true,
            'single_blank_line_at_eof'                      => true,
            'single_import_per_statement'                   => true,
            'single_line_after_imports'                     => true,
            'single_quote'                                  => true,
            'standardize_not_equals'                        => true,
            'ternary_to_null_coalescing'                    => true,
            'trailing_comma_in_multiline_array'             => false,
            'trim_array_spaces'                             => true,
            'unary_operator_spaces'                         => true,
            'visibility_required'                           => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return'                                   => true,
            'whitespace_after_comma_in_array'               => true,
            'yoda_style'                                    => false
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
            ->files()
            ->in(__DIR__ . '/src')
            ->in(__DIR__ . '/tests')
            ->notName('*.phpt')
            ->notName('autoload.php')
    );
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class Token {

    /** @var int */
    private $line;

    /** @var string */
    private $name;

    /** @var string */
    private $value;

    /**
     * Token constructor.
     */
    public function __construct(int $line, string $name, string $value) {
        $this->line  = $line;
        $this->name  = $name;
        $this->value = $value;
    }

    public function getLine(): int {
        return $this->line;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getValue(): string {
        return $this->value;
    }
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class NamespaceUriException extends Exception {
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class TokenCollectionException extends Exception {
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class TokenCollection implements \ArrayAccess, \Iterator, \Countable {

    /** @var Token[] */
    private $tokens = [];

    /** @var int */
    private $pos;

    public function addToken(Token $token): void {
        $this->tokens[] = $token;
    }

    public function current(): Token {
        return \current($this->tokens);
    }

    public function key(): int {
        return \key($this->tokens);
    }

    public function next(): void {
        \next($this->tokens);
        $this->pos++;
    }

    public function valid(): bool {
        return $this->count() > $this->pos;
    }

    public function rewind(): void {
        \reset($this->tokens);
        $this->pos = 0;
    }

    public function count(): int {
        return \count($this->tokens);
    }

    public function offsetExists($offset): bool {
        return isset($this->tokens[$offset]);
    }

    /**
     * @throws TokenCollectionException
     */
    public function offsetGet($offset): Token {
        if (!$this->offsetExists($offset)) {
            throw new TokenCollectionException(
                \sprintf('No Token at offest %s', $offset)
            );
        }

        return $this->tokens[$offset];
    }

    /**
     * @param Token $value
     *
     * @throws TokenCollectionException
     */
    public function offsetSet($offset, $value): void {
        if (!\is_int($offset)) {
            $type = \gettype($offset);

            throw new TokenCollectionException(
                \sprintf(
                    'Offset must be of type integer, %s given',
                    $type === 'object' ? \get_class($value) : $type
                )
            );
        }

        if (!$value instanceof Token) {
            $type = \gettype($value);

            throw new TokenCollectionException(
                \sprintf(
                    'Value must be of type %s, %s given',
                    Token::class,
                    $type === 'object' ? \get_class($value) : $type
                )
            );
        }
        $this->tokens[$offset] = $value;
    }

    public function offsetUnset($offset): void {
        unset($this->tokens[$offset]);
    }
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class Tokenizer {

    /**
     * Token Map for "non-tokens"
     *
     * @var array
     */
    private $map = [
        '(' => 'T_OPEN_BRACKET',
        ')' => 'T_CLOSE_BRACKET',
        '[' => 'T_OPEN_SQUARE',
        ']' => 'T_CLOSE_SQUARE',
        '{' => 'T_OPEN_CURLY',
        '}' => 'T_CLOSE_CURLY',
        ';' => 'T_SEMICOLON',
        '.' => 'T_DOT',
        ',' => 'T_COMMA',
        '=' => 'T_EQUAL',
        '<' => 'T_LT',
        '>' => 'T_GT',
        '+' => 'T_PLUS',
        '-' => 'T_MINUS',
        '*' => 'T_MULT',
        '/' => 'T_DIV',
        '?' => 'T_QUESTION_MARK',
        '!' => 'T_EXCLAMATION_MARK',
        ':' => 'T_COLON',
        '"' => 'T_DOUBLE_QUOTES',
        '@' => 'T_AT',
        '&' => 'T_AMPERSAND',
        '%' => 'T_PERCENT',
        '|' => 'T_PIPE',
        '$' => 'T_DOLLAR',
        '^' => 'T_CARET',
        '~' => 'T_TILDE',
        '`' => 'T_BACKTICK'
    ];

    public function parse(string $source): TokenCollection {
        $result = new TokenCollection();

        if ($source === '') {
            return $result;
        }

        $tokens = \token_get_all($source);

        $lastToken = new Token(
            $tokens[0][2],
            'Placeholder',
            ''
        );

        foreach ($tokens as $pos => $tok) {
            if (\is_string($tok)) {
                $token = new Token(
                    $lastToken->getLine(),
                    $this->map[$tok],
                    $tok
                );
                $result->addToken($token);
                $lastToken = $token;

                continue;
            }

            $line   = $tok[2];
            $values = \preg_split('/\R+/Uu', $tok[1]);

            foreach ($values as $v) {
                $token = new Token(
                    $line,
                    \token_name($tok[0]),
                    $v
                );
                $lastToken = $token;
                $line++;

                if ($v === '') {
                    continue;
                }

                $result->addToken($token);
            }
        }

        return $this->fillBlanks($result, $lastToken->getLine());
    }

    private function fillBlanks(TokenCollection $tokens, int $maxLine): TokenCollection {
        $prev = new Token(
            0,
            'Placeholder',
            ''
        );

        $final = new TokenCollection();

        foreach ($tokens as $token) {
            if ($prev === null) {
                $final->addToken($token);
                $prev = $token;

                continue;
            }

            $gap = $token->getLine() - $prev->getLine();

            while ($gap > 1) {
                $linebreak = new Token(
                    $prev->getLine() + 1,
                    'T_WHITESPACE',
                    ''
                );
                $final->addToken($linebreak);
                $prev = $linebreak;
                $gap--;
            }

            $final->addToken($token);
            $prev = $token;
        }

        $gap = $maxLine - $prev->getLine();

        while ($gap > 0) {
            $linebreak = new Token(
                $prev->getLine() + 1,
                'T_WHITESPACE',
                ''
            );
            $final->addToken($linebreak);
            $prev = $linebreak;
            $gap--;
        }

        return $final;
    }
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

use DOMDocument;

class XMLSerializer {

    /** @var \XMLWriter */
    private $writer;

    /** @var Token */
    private $previousToken;

    /** @var NamespaceUri */
    private $xmlns;

    /**
     * XMLSerializer constructor.
     *
     * @param NamespaceUri $xmlns
     */
    public function __construct(NamespaceUri $xmlns = null) {
        if ($xmlns === null) {
            $xmlns = new NamespaceUri('https://github.com/theseer/tokenizer');
        }
        $this->xmlns = $xmlns;
    }

    public function toDom(TokenCollection $tokens): DOMDocument {
        $dom                     = new DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->loadXML($this->toXML($tokens));

        return $dom;
    }

    public function toXML(TokenCollection $tokens): string {
        $this->writer = new \XMLWriter();
        $this->writer->openMemory();
        $this->writer->setIndent(true);
        $this->writer->startDocument();
        $this->writer->startElement('source');
        $this->writer->writeAttribute('xmlns', $this->xmlns->asString());

        if (\count($tokens) > 0) {
            $this->writer->startElement('line');
            $this->writer->writeAttribute('no', '1');

            $this->previousToken = $tokens[0];

            foreach ($tokens as $token) {
                $this->addToken($token);
            }
        }

        $this->writer->endElement();
        $this->writer->endElement();
        $this->writer->endDocument();

        return $this->writer->outputMemory();
    }

    private function addToken(Token $token): void {
        if ($this->previousToken->getLine() < $token->getLine()) {
            $this->writer->endElement();

            $this->writer->startElement('line');
            $this->writer->writeAttribute('no', (string)$token->getLine());
            $this->previousToken = $token;
        }

        if ($token->getValue() !== '') {
            $this->writer->startElement('token');
            $this->writer->writeAttribute('name', $token->getName());
            $this->writer->writeRaw(\htmlspecialchars($token->getValue(), \ENT_NOQUOTES | \ENT_DISALLOWED | \ENT_XML1));
            $this->writer->endElement();
        }
    }
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class NamespaceUri {

    /** @var string */
    private $value;

    public function __construct(string $value) {
        $this->ensureValidUri($value);
        $this->value = $value;
    }

    public function asString(): string {
        return $this->value;
    }

    private function ensureValidUri($value): void {
        if (\strpos($value, ':') === false) {
            throw new NamespaceUriException(
                \sprintf("Namespace URI '%s' must contain at least one colon", $value)
            );
        }
    }
}
<?php declare(strict_types = 1);
namespace TheSeer\Tokenizer;

class Exception extends \Exception {
}
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'),
    'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'),
    'BaiduBce' => array($baseDir . '/src'),
);

Copyright (c) Nils Adermann, Jordi Boggiano

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Autoload;

/**
 * ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
 *
 *     $loader = new \Composer\Autoload\ClassLoader();
 *
 *     // register classes with namespaces
 *     $loader->add('Symfony\Component', __DIR__.'/component');
 *     $loader->add('Symfony',           __DIR__.'/framework');
 *
 *     // activate the autoloader
 *     $loader->register();
 *
 *     // to enable searching the include path (eg. for PEAR packages)
 *     $loader->setUseIncludePath(true);
 *
 * In this example, if you try to use a class in the Symfony\Component
 * namespace or one of its children (Symfony\Component\Console for instance),
 * the autoloader will first look for the class under the component/
 * directory, and it will then fallback to the framework/ directory if not
 * found before giving up.
 *
 * This class is loosely based on the Symfony UniversalClassLoader.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @see    https://www.php-fig.org/psr/psr-0/
 * @see    https://www.php-fig.org/psr/psr-4/
 */
class ClassLoader
{
    /** @var \Closure(string):void */
    private static $includeFile;

    /** @var ?string */
    private $vendorDir;

    // PSR-4
    /**
     * @var array[]
     * @psalm-var array<string, array<string, int>>
     */
    private $prefixLengthsPsr4 = array();
    /**
     * @var array[]
     * @psalm-var array<string, array<int, string>>
     */
    private $prefixDirsPsr4 = array();
    /**
     * @var array[]
     * @psalm-var array<string, string>
     */
    private $fallbackDirsPsr4 = array();

    // PSR-0
    /**
     * @var array[]
     * @psalm-var array<string, array<string, string[]>>
     */
    private $prefixesPsr0 = array();
    /**
     * @var array[]
     * @psalm-var array<string, string>
     */
    private $fallbackDirsPsr0 = array();

    /** @var bool */
    private $useIncludePath = false;

    /**
     * @var string[]
     * @psalm-var array<string, string>
     */
    private $classMap = array();

    /** @var bool */
    private $classMapAuthoritative = false;

    /**
     * @var bool[]
     * @psalm-var array<string, bool>
     */
    private $missingClasses = array();

    /** @var ?string */
    private $apcuPrefix;

    /**
     * @var self[]
     */
    private static $registeredLoaders = array();

    /**
     * @param ?string $vendorDir
     */
    public function __construct($vendorDir = null)
    {
        $this->vendorDir = $vendorDir;
        self::initializeIncludeClosure();
    }

    /**
     * @return string[]
     */
    public function getPrefixes()
    {
        if (!empty($this->prefixesPsr0)) {
            return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
        }

        return array();
    }

    /**
     * @return array[]
     * @psalm-return array<string, array<int, string>>
     */
    public function getPrefixesPsr4()
    {
        return $this->prefixDirsPsr4;
    }

    /**
     * @return array[]
     * @psalm-return array<string, string>
     */
    public function getFallbackDirs()
    {
        return $this->fallbackDirsPsr0;
    }

    /**
     * @return array[]
     * @psalm-return array<string, string>
     */
    public function getFallbackDirsPsr4()
    {
        return $this->fallbackDirsPsr4;
    }

    /**
     * @return string[] Array of classname => path
     * @psalm-return array<string, string>
     */
    public function getClassMap()
    {
        return $this->classMap;
    }

    /**
     * @param string[] $classMap Class to filename map
     * @psalm-param array<string, string> $classMap
     *
     * @return void
     */
    public function addClassMap(array $classMap)
    {
        if ($this->classMap) {
            $this->classMap = array_merge($this->classMap, $classMap);
        } else {
            $this->classMap = $classMap;
        }
    }

    /**
     * Registers a set of PSR-0 directories for a given prefix, either
     * appending or prepending to the ones previously set for this prefix.
     *
     * @param string          $prefix  The prefix
     * @param string[]|string $paths   The PSR-0 root directories
     * @param bool            $prepend Whether to prepend the directories
     *
     * @return void
     */
    public function add($prefix, $paths, $prepend = false)
    {
        if (!$prefix) {
            if ($prepend) {
                $this->fallbackDirsPsr0 = array_merge(
                    (array) $paths,
                    $this->fallbackDirsPsr0
                );
            } else {
                $this->fallbackDirsPsr0 = array_merge(
                    $this->fallbackDirsPsr0,
                    (array) $paths
                );
            }

            return;
        }

        $first = $prefix[0];
        if (!isset($this->prefixesPsr0[$first][$prefix])) {
            $this->prefixesPsr0[$first][$prefix] = (array) $paths;

            return;
        }
        if ($prepend) {
            $this->prefixesPsr0[$first][$prefix] = array_merge(
                (array) $paths,
                $this->prefixesPsr0[$first][$prefix]
            );
        } else {
            $this->prefixesPsr0[$first][$prefix] = array_merge(
                $this->prefixesPsr0[$first][$prefix],
                (array) $paths
            );
        }
    }

    /**
     * Registers a set of PSR-4 directories for a given namespace, either
     * appending or prepending to the ones previously set for this namespace.
     *
     * @param string          $prefix  The prefix/namespace, with trailing '\\'
     * @param string[]|string $paths   The PSR-4 base directories
     * @param bool            $prepend Whether to prepend the directories
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    public function addPsr4($prefix, $paths, $prepend = false)
    {
        if (!$prefix) {
            // Register directories for the root namespace.
            if ($prepend) {
                $this->fallbackDirsPsr4 = array_merge(
                    (array) $paths,
                    $this->fallbackDirsPsr4
                );
            } else {
                $this->fallbackDirsPsr4 = array_merge(
                    $this->fallbackDirsPsr4,
                    (array) $paths
                );
            }
        } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
            // Register directories for a new namespace.
            $length = strlen($prefix);
            if ('\\' !== $prefix[$length - 1]) {
                throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
            }
            $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
            $this->prefixDirsPsr4[$prefix] = (array) $paths;
        } elseif ($prepend) {
            // Prepend directories for an already registered namespace.
            $this->prefixDirsPsr4[$prefix] = array_merge(
                (array) $paths,
                $this->prefixDirsPsr4[$prefix]
            );
        } else {
            // Append directories for an already registered namespace.
            $this->prefixDirsPsr4[$prefix] = array_merge(
                $this->prefixDirsPsr4[$prefix],
                (array) $paths
            );
        }
    }

    /**
     * Registers a set of PSR-0 directories for a given prefix,
     * replacing any others previously set for this prefix.
     *
     * @param string          $prefix The prefix
     * @param string[]|string $paths  The PSR-0 base directories
     *
     * @return void
     */
    public function set($prefix, $paths)
    {
        if (!$prefix) {
            $this->fallbackDirsPsr0 = (array) $paths;
        } else {
            $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
        }
    }

    /**
     * Registers a set of PSR-4 directories for a given namespace,
     * replacing any others previously set for this namespace.
     *
     * @param string          $prefix The prefix/namespace, with trailing '\\'
     * @param string[]|string $paths  The PSR-4 base directories
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    public function setPsr4($prefix, $paths)
    {
        if (!$prefix) {
            $this->fallbackDirsPsr4 = (array) $paths;
        } else {
            $length = strlen($prefix);
            if ('\\' !== $prefix[$length - 1]) {
                throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
            }
            $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
            $this->prefixDirsPsr4[$prefix] = (array) $paths;
        }
    }

    /**
     * Turns on searching the include path for class files.
     *
     * @param bool $useIncludePath
     *
     * @return void
     */
    public function setUseIncludePath($useIncludePath)
    {
        $this->useIncludePath = $useIncludePath;
    }

    /**
     * Can be used to check if the autoloader uses the include path to check
     * for classes.
     *
     * @return bool
     */
    public function getUseIncludePath()
    {
        return $this->useIncludePath;
    }

    /**
     * Turns off searching the prefix and fallback directories for classes
     * that have not been registered with the class map.
     *
     * @param bool $classMapAuthoritative
     *
     * @return void
     */
    public function setClassMapAuthoritative($classMapAuthoritative)
    {
        $this->classMapAuthoritative = $classMapAuthoritative;
    }

    /**
     * Should class lookup fail if not found in the current class map?
     *
     * @return bool
     */
    public function isClassMapAuthoritative()
    {
        return $this->classMapAuthoritative;
    }

    /**
     * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
     *
     * @param string|null $apcuPrefix
     *
     * @return void
     */
    public function setApcuPrefix($apcuPrefix)
    {
        $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
    }

    /**
     * The APCu prefix in use, or null if APCu caching is not enabled.
     *
     * @return string|null
     */
    public function getApcuPrefix()
    {
        return $this->apcuPrefix;
    }

    /**
     * Registers this instance as an autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader or not
     *
     * @return void
     */
    public function register($prepend = false)
    {
        spl_autoload_register(array($this, 'loadClass'), true, $prepend);

        if (null === $this->vendorDir) {
            return;
        }

        if ($prepend) {
            self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
        } else {
            unset(self::$registeredLoaders[$this->vendorDir]);
            self::$registeredLoaders[$this->vendorDir] = $this;
        }
    }

    /**
     * Unregisters this instance as an autoloader.
     *
     * @return void
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));

        if (null !== $this->vendorDir) {
            unset(self::$registeredLoaders[$this->vendorDir]);
        }
    }

    /**
     * Loads the given class or interface.
     *
     * @param  string    $class The name of the class
     * @return true|null True if loaded, null otherwise
     */
    public function loadClass($class)
    {
        if ($file = $this->findFile($class)) {
            (self::$includeFile)($file);

            return true;
        }

        return null;
    }

    /**
     * Finds the path to the file where the class is defined.
     *
     * @param string $class The name of the class
     *
     * @return string|false The path if found, false otherwise
     */
    public function findFile($class)
    {
        // class map lookup
        if (isset($this->classMap[$class])) {
            return $this->classMap[$class];
        }
        if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
            return false;
        }
        if (null !== $this->apcuPrefix) {
            $file = apcu_fetch($this->apcuPrefix.$class, $hit);
            if ($hit) {
                return $file;
            }
        }

        $file = $this->findFileWithExtension($class, '.php');

        // Search for Hack files if we are running on HHVM
        if (false === $file && defined('HHVM_VERSION')) {
            $file = $this->findFileWithExtension($class, '.hh');
        }

        if (null !== $this->apcuPrefix) {
            apcu_add($this->apcuPrefix.$class, $file);
        }

        if (false === $file) {
            // Remember that this class does not exist.
            $this->missingClasses[$class] = true;
        }

        return $file;
    }

    /**
     * Returns the currently registered loaders indexed by their corresponding vendor directories.
     *
     * @return self[]
     */
    public static function getRegisteredLoaders()
    {
        return self::$registeredLoaders;
    }

    /**
     * @param  string       $class
     * @param  string       $ext
     * @return string|false
     */
    private function findFileWithExtension($class, $ext)
    {
        // PSR-4 lookup
        $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;

        $first = $class[0];
        if (isset($this->prefixLengthsPsr4[$first])) {
            $subPath = $class;
            while (false !== $lastPos = strrpos($subPath, '\\')) {
                $subPath = substr($subPath, 0, $lastPos);
                $search = $subPath . '\\';
                if (isset($this->prefixDirsPsr4[$search])) {
                    $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
                    foreach ($this->prefixDirsPsr4[$search] as $dir) {
                        if (file_exists($file = $dir . $pathEnd)) {
                            return $file;
                        }
                    }
                }
            }
        }

        // PSR-4 fallback dirs
        foreach ($this->fallbackDirsPsr4 as $dir) {
            if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
                return $file;
            }
        }

        // PSR-0 lookup
        if (false !== $pos = strrpos($class, '\\')) {
            // namespaced class name
            $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
                . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
        } else {
            // PEAR-like class name
            $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
        }

        if (isset($this->prefixesPsr0[$first])) {
            foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
                if (0 === strpos($class, $prefix)) {
                    foreach ($dirs as $dir) {
                        if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
                            return $file;
                        }
                    }
                }
            }
        }

        // PSR-0 fallback dirs
        foreach ($this->fallbackDirsPsr0 as $dir) {
            if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
                return $file;
            }
        }

        // PSR-0 include paths.
        if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
            return $file;
        }

        return false;
    }

    private static function initializeIncludeClosure(): void
    {
        if (self::$includeFile !== null) {
            return;
        }

        /**
         * Scope isolated include.
         *
         * Prevents access to $this/self from included files.
         *
         * @param  string $file
         * @return void
         */
        self::$includeFile = static function($file) {
            include $file;
        };
    }
}
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
    'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
    'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
);
<?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
    'PHPUnit\\Exception' => $vendorDir . '/phpunit/phpunit/src/Exception.php',
    'PHPUnit\\Framework\\Assert' => $vendorDir . '/phpunit/phpunit/src/Framework/Assert.php',
    'PHPUnit\\Framework\\AssertionFailedError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/AssertionFailedError.php',
    'PHPUnit\\Framework\\CodeCoverageException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/CodeCoverageException.php',
    'PHPUnit\\Framework\\Constraint\\ArrayHasKey' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.php',
    'PHPUnit\\Framework\\Constraint\\ArraySubset' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php',
    'PHPUnit\\Framework\\Constraint\\Attribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Attribute.php',
    'PHPUnit\\Framework\\Constraint\\Callback' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Callback.php',
    'PHPUnit\\Framework\\Constraint\\ClassHasAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php',
    'PHPUnit\\Framework\\Constraint\\ClassHasStaticAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.php',
    'PHPUnit\\Framework\\Constraint\\Composite' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Composite.php',
    'PHPUnit\\Framework\\Constraint\\Constraint' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Constraint.php',
    'PHPUnit\\Framework\\Constraint\\Count' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Count.php',
    'PHPUnit\\Framework\\Constraint\\DirectoryExists' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/DirectoryExists.php',
    'PHPUnit\\Framework\\Constraint\\Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Exception.php',
    'PHPUnit\\Framework\\Constraint\\ExceptionCode' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.php',
    'PHPUnit\\Framework\\Constraint\\ExceptionMessage' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.php',
    'PHPUnit\\Framework\\Constraint\\ExceptionMessageRegularExpression' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegularExpression.php',
    'PHPUnit\\Framework\\Constraint\\FileExists' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/FileExists.php',
    'PHPUnit\\Framework\\Constraint\\GreaterThan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php',
    'PHPUnit\\Framework\\Constraint\\IsAnything' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsAnything.php',
    'PHPUnit\\Framework\\Constraint\\IsEmpty' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsEmpty.php',
    'PHPUnit\\Framework\\Constraint\\IsEqual' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsEqual.php',
    'PHPUnit\\Framework\\Constraint\\IsFalse' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsFalse.php',
    'PHPUnit\\Framework\\Constraint\\IsFinite' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsFinite.php',
    'PHPUnit\\Framework\\Constraint\\IsIdentical' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php',
    'PHPUnit\\Framework\\Constraint\\IsInfinite' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsInfinite.php',
    'PHPUnit\\Framework\\Constraint\\IsInstanceOf' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.php',
    'PHPUnit\\Framework\\Constraint\\IsJson' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsJson.php',
    'PHPUnit\\Framework\\Constraint\\IsNan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsNan.php',
    'PHPUnit\\Framework\\Constraint\\IsNull' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsNull.php',
    'PHPUnit\\Framework\\Constraint\\IsReadable' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsReadable.php',
    'PHPUnit\\Framework\\Constraint\\IsTrue' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
    'PHPUnit\\Framework\\Constraint\\IsType' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
    'PHPUnit\\Framework\\Constraint\\IsWritable' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsWritable.php',
    'PHPUnit\\Framework\\Constraint\\JsonMatches' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
    'PHPUnit\\Framework\\Constraint\\JsonMatchesErrorMessageProvider' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php',
    'PHPUnit\\Framework\\Constraint\\LessThan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
    'PHPUnit\\Framework\\Constraint\\LogicalAnd' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LogicalAnd.php',
    'PHPUnit\\Framework\\Constraint\\LogicalNot' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LogicalNot.php',
    'PHPUnit\\Framework\\Constraint\\LogicalOr' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LogicalOr.php',
    'PHPUnit\\Framework\\Constraint\\LogicalXor' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LogicalXor.php',
    'PHPUnit\\Framework\\Constraint\\ObjectHasAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
    'PHPUnit\\Framework\\Constraint\\RegularExpression' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/RegularExpression.php',
    'PHPUnit\\Framework\\Constraint\\SameSize' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/SameSize.php',
    'PHPUnit\\Framework\\Constraint\\StringContains' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringContains.php',
    'PHPUnit\\Framework\\Constraint\\StringEndsWith' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php',
    'PHPUnit\\Framework\\Constraint\\StringMatchesFormatDescription' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringMatchesFormatDescription.php',
    'PHPUnit\\Framework\\Constraint\\StringStartsWith' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php',
    'PHPUnit\\Framework\\Constraint\\TraversableContains' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContains.php',
    'PHPUnit\\Framework\\Constraint\\TraversableContainsEqual' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsEqual.php',
    'PHPUnit\\Framework\\Constraint\\TraversableContainsIdentical' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsIdentical.php',
    'PHPUnit\\Framework\\Constraint\\TraversableContainsOnly' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
    'PHPUnit\\Framework\\CoveredCodeNotExecutedException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/CoveredCodeNotExecutedException.php',
    'PHPUnit\\Framework\\DataProviderTestSuite' => $vendorDir . '/phpunit/phpunit/src/Framework/DataProviderTestSuite.php',
    'PHPUnit\\Framework\\Error\\Deprecated' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Deprecated.php',
    'PHPUnit\\Framework\\Error\\Error' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Error.php',
    'PHPUnit\\Framework\\Error\\Notice' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Notice.php',
    'PHPUnit\\Framework\\Error\\Warning' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Warning.php',
    'PHPUnit\\Framework\\Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/Exception.php',
    'PHPUnit\\Framework\\ExceptionWrapper' => $vendorDir . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
    'PHPUnit\\Framework\\ExpectationFailedException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/ExpectationFailedException.php',
    'PHPUnit\\Framework\\IncompleteTest' => $vendorDir . '/phpunit/phpunit/src/Framework/IncompleteTest.php',
    'PHPUnit\\Framework\\IncompleteTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/IncompleteTestCase.php',
    'PHPUnit\\Framework\\IncompleteTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/IncompleteTestError.php',
    'PHPUnit\\Framework\\InvalidArgumentException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/InvalidArgumentException.php',
    'PHPUnit\\Framework\\InvalidCoversTargetException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/InvalidCoversTargetException.php',
    'PHPUnit\\Framework\\InvalidDataProviderException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/InvalidDataProviderException.php',
    'PHPUnit\\Framework\\InvalidParameterGroupException' => $vendorDir . '/phpunit/phpunit/src/Framework/InvalidParameterGroupException.php',
    'PHPUnit\\Framework\\MissingCoversAnnotationException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/MissingCoversAnnotationException.php',
    'PHPUnit\\Framework\\MockObject\\Api' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Api/Api.php',
    'PHPUnit\\Framework\\MockObject\\BadMethodCallException' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Exception/BadMethodCallException.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\Identity' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/Identity.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\InvocationMocker' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationMocker.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\InvocationStubber' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationStubber.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\Match_' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/Match_.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\MethodNameMatch' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/MethodNameMatch.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\ParametersMatch' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/ParametersMatch.php',
    'PHPUnit\\Framework\\MockObject\\Builder\\Stub' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Builder/Stub.php',
    'PHPUnit\\Framework\\MockObject\\ConfigurableMethod' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/ConfigurableMethod.php',
    'PHPUnit\\Framework\\MockObject\\ConfigurableMethodsAlreadyInitializedException' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Exception/ConfigurableMethodsAlreadyInitializedException.php',
    'PHPUnit\\Framework\\MockObject\\Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Exception/Exception.php',
    'PHPUnit\\Framework\\MockObject\\Generator' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Generator.php',
    'PHPUnit\\Framework\\MockObject\\IncompatibleReturnValueException' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Exception/IncompatibleReturnValueException.php',
    'PHPUnit\\Framework\\MockObject\\Invocation' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Invocation.php',
    'PHPUnit\\Framework\\MockObject\\InvocationHandler' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/InvocationHandler.php',
    'PHPUnit\\Framework\\MockObject\\Matcher' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Matcher.php',
    'PHPUnit\\Framework\\MockObject\\Method' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Api/Method.php',
    'PHPUnit\\Framework\\MockObject\\MethodNameConstraint' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MethodNameConstraint.php',
    'PHPUnit\\Framework\\MockObject\\MockBuilder' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockBuilder.php',
    'PHPUnit\\Framework\\MockObject\\MockClass' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockClass.php',
    'PHPUnit\\Framework\\MockObject\\MockMethod' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockMethod.php',
    'PHPUnit\\Framework\\MockObject\\MockMethodSet' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockMethodSet.php',
    'PHPUnit\\Framework\\MockObject\\MockObject' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockObject.php',
    'PHPUnit\\Framework\\MockObject\\MockTrait' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockTrait.php',
    'PHPUnit\\Framework\\MockObject\\MockType' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/MockType.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\AnyInvokedCount' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/AnyInvokedCount.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\AnyParameters' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/AnyParameters.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\ConsecutiveParameters' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/ConsecutiveParameters.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvocationOrder' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvocationOrder.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtIndex' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtIndex.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtLeastCount' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastCount.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtLeastOnce' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastOnce.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtMostCount' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtMostCount.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\InvokedCount' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedCount.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\MethodName' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/MethodName.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\Parameters' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/Parameters.php',
    'PHPUnit\\Framework\\MockObject\\Rule\\ParametersRule' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Rule/ParametersRule.php',
    'PHPUnit\\Framework\\MockObject\\RuntimeException' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Exception/RuntimeException.php',
    'PHPUnit\\Framework\\MockObject\\Stub' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ConsecutiveCalls' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ConsecutiveCalls.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/Exception.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnArgument' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnArgument.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnCallback' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnCallback.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnReference' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnReference.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnSelf' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnSelf.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnStub' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnStub.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\ReturnValueMap' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnValueMap.php',
    'PHPUnit\\Framework\\MockObject\\Stub\\Stub' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Stub/Stub.php',
    'PHPUnit\\Framework\\MockObject\\Verifiable' => $vendorDir . '/phpunit/phpunit/src/Framework/MockObject/Verifiable.php',
    'PHPUnit\\Framework\\NoChildTestSuiteException' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/NoChildTestSuiteException.php',
    'PHPUnit\\Framework\\OutputError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/OutputError.php',
    'PHPUnit\\Framework\\PHPTAssertionFailedError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/PHPTAssertionFailedError.php',
    'PHPUnit\\Framework\\RiskyTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/RiskyTestError.php',
    'PHPUnit\\Framework\\SelfDescribing' => $vendorDir . '/phpunit/phpunit/src/Framework/SelfDescribing.php',
    'PHPUnit\\Framework\\SkippedTest' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTest.php',
    'PHPUnit\\Framework\\SkippedTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTestCase.php',
    'PHPUnit\\Framework\\SkippedTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/SkippedTestError.php',
    'PHPUnit\\Framework\\SkippedTestSuiteError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/SkippedTestSuiteError.php',
    'PHPUnit\\Framework\\SyntheticError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/SyntheticError.php',
    'PHPUnit\\Framework\\SyntheticSkippedError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/SyntheticSkippedError.php',
    'PHPUnit\\Framework\\Test' => $vendorDir . '/phpunit/phpunit/src/Framework/Test.php',
    'PHPUnit\\Framework\\TestBuilder' => $vendorDir . '/phpunit/phpunit/src/Framework/TestBuilder.php',
    'PHPUnit\\Framework\\TestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/TestCase.php',
    'PHPUnit\\Framework\\TestFailure' => $vendorDir . '/phpunit/phpunit/src/Framework/TestFailure.php',
    'PHPUnit\\Framework\\TestListener' => $vendorDir . '/phpunit/phpunit/src/Framework/TestListener.php',
    'PHPUnit\\Framework\\TestListenerDefaultImplementation' => $vendorDir . '/phpunit/phpunit/src/Framework/TestListenerDefaultImplementation.php',
    'PHPUnit\\Framework\\TestResult' => $vendorDir . '/phpunit/phpunit/src/Framework/TestResult.php',
    'PHPUnit\\Framework\\TestSuite' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuite.php',
    'PHPUnit\\Framework\\TestSuiteIterator' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuiteIterator.php',
    'PHPUnit\\Framework\\UnintentionallyCoveredCodeError' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/UnintentionallyCoveredCodeError.php',
    'PHPUnit\\Framework\\Warning' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception/Warning.php',
    'PHPUnit\\Framework\\WarningTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/WarningTestCase.php',
    'PHPUnit\\Runner\\AfterIncompleteTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterIncompleteTestHook.php',
    'PHPUnit\\Runner\\AfterLastTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterLastTestHook.php',
    'PHPUnit\\Runner\\AfterRiskyTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterRiskyTestHook.php',
    'PHPUnit\\Runner\\AfterSkippedTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterSkippedTestHook.php',
    'PHPUnit\\Runner\\AfterSuccessfulTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterSuccessfulTestHook.php',
    'PHPUnit\\Runner\\AfterTestErrorHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterTestErrorHook.php',
    'PHPUnit\\Runner\\AfterTestFailureHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterTestFailureHook.php',
    'PHPUnit\\Runner\\AfterTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterTestHook.php',
    'PHPUnit\\Runner\\AfterTestWarningHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/AfterTestWarningHook.php',
    'PHPUnit\\Runner\\BaseTestRunner' => $vendorDir . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
    'PHPUnit\\Runner\\BeforeFirstTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/BeforeFirstTestHook.php',
    'PHPUnit\\Runner\\BeforeTestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/BeforeTestHook.php',
    'PHPUnit\\Runner\\DefaultTestResultCache' => $vendorDir . '/phpunit/phpunit/src/Runner/DefaultTestResultCache.php',
    'PHPUnit\\Runner\\Exception' => $vendorDir . '/phpunit/phpunit/src/Runner/Exception.php',
    'PHPUnit\\Runner\\Filter\\ExcludeGroupFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/ExcludeGroupFilterIterator.php',
    'PHPUnit\\Runner\\Filter\\Factory' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
    'PHPUnit\\Runner\\Filter\\GroupFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/GroupFilterIterator.php',
    'PHPUnit\\Runner\\Filter\\IncludeGroupFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/IncludeGroupFilterIterator.php',
    'PHPUnit\\Runner\\Filter\\NameFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/NameFilterIterator.php',
    'PHPUnit\\Runner\\Hook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/Hook.php',
    'PHPUnit\\Runner\\NullTestResultCache' => $vendorDir . '/phpunit/phpunit/src/Runner/NullTestResultCache.php',
    'PHPUnit\\Runner\\PhptTestCase' => $vendorDir . '/phpunit/phpunit/src/Runner/PhptTestCase.php',
    'PHPUnit\\Runner\\ResultCacheExtension' => $vendorDir . '/phpunit/phpunit/src/Runner/ResultCacheExtension.php',
    'PHPUnit\\Runner\\StandardTestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
    'PHPUnit\\Runner\\TestHook' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/TestHook.php',
    'PHPUnit\\Runner\\TestListenerAdapter' => $vendorDir . '/phpunit/phpunit/src/Runner/Hook/TestListenerAdapter.php',
    'PHPUnit\\Runner\\TestResultCache' => $vendorDir . '/phpunit/phpunit/src/Runner/TestResultCache.php',
    'PHPUnit\\Runner\\TestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
    'PHPUnit\\Runner\\TestSuiteSorter' => $vendorDir . '/phpunit/phpunit/src/Runner/TestSuiteSorter.php',
    'PHPUnit\\Runner\\Version' => $vendorDir . '/phpunit/phpunit/src/Runner/Version.php',
    'PHPUnit\\TextUI\\Command' => $vendorDir . '/phpunit/phpunit/src/TextUI/Command.php',
    'PHPUnit\\TextUI\\Exception' => $vendorDir . '/phpunit/phpunit/src/TextUI/Exception.php',
    'PHPUnit\\TextUI\\Help' => $vendorDir . '/phpunit/phpunit/src/TextUI/Help.php',
    'PHPUnit\\TextUI\\ResultPrinter' => $vendorDir . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
    'PHPUnit\\TextUI\\TestRunner' => $vendorDir . '/phpunit/phpunit/src/TextUI/TestRunner.php',
    'PHPUnit\\Util\\Annotation\\DocBlock' => $vendorDir . '/phpunit/phpunit/src/Util/Annotation/DocBlock.php',
    'PHPUnit\\Util\\Annotation\\Registry' => $vendorDir . '/phpunit/phpunit/src/Util/Annotation/Registry.php',
    'PHPUnit\\Util\\Blacklist' => $vendorDir . '/phpunit/phpunit/src/Util/Blacklist.php',
    'PHPUnit\\Util\\Color' => $vendorDir . '/phpunit/phpunit/src/Util/Color.php',
    'PHPUnit\\Util\\Configuration' => $vendorDir . '/phpunit/phpunit/src/Util/Configuration.php',
    'PHPUnit\\Util\\ConfigurationGenerator' => $vendorDir . '/phpunit/phpunit/src/Util/ConfigurationGenerator.php',
    'PHPUnit\\Util\\ErrorHandler' => $vendorDir . '/phpunit/phpunit/src/Util/ErrorHandler.php',
    'PHPUnit\\Util\\Exception' => $vendorDir . '/phpunit/phpunit/src/Util/Exception.php',
    'PHPUnit\\Util\\FileLoader' => $vendorDir . '/phpunit/phpunit/src/Util/FileLoader.php',
    'PHPUnit\\Util\\Filesystem' => $vendorDir . '/phpunit/phpunit/src/Util/Filesystem.php',
    'PHPUnit\\Util\\Filter' => $vendorDir . '/phpunit/phpunit/src/Util/Filter.php',
    'PHPUnit\\Util\\Getopt' => $vendorDir . '/phpunit/phpunit/src/Util/Getopt.php',
    'PHPUnit\\Util\\GlobalState' => $vendorDir . '/phpunit/phpunit/src/Util/GlobalState.php',
    'PHPUnit\\Util\\InvalidDataSetException' => $vendorDir . '/phpunit/phpunit/src/Util/InvalidDataSetException.php',
    'PHPUnit\\Util\\Json' => $vendorDir . '/phpunit/phpunit/src/Util/Json.php',
    'PHPUnit\\Util\\Log\\JUnit' => $vendorDir . '/phpunit/phpunit/src/Util/Log/JUnit.php',
    'PHPUnit\\Util\\Log\\TeamCity' => $vendorDir . '/phpunit/phpunit/src/Util/Log/TeamCity.php',
    'PHPUnit\\Util\\PHP\\AbstractPhpProcess' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/AbstractPhpProcess.php',
    'PHPUnit\\Util\\PHP\\DefaultPhpProcess' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/DefaultPhpProcess.php',
    'PHPUnit\\Util\\PHP\\WindowsPhpProcess' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/WindowsPhpProcess.php',
    'PHPUnit\\Util\\Printer' => $vendorDir . '/phpunit/phpunit/src/Util/Printer.php',
    'PHPUnit\\Util\\Reflection' => $vendorDir . '/phpunit/phpunit/src/Util/Reflection.php',
    'PHPUnit\\Util\\RegularExpression' => $vendorDir . '/phpunit/phpunit/src/Util/RegularExpression.php',
    'PHPUnit\\Util\\Test' => $vendorDir . '/phpunit/phpunit/src/Util/Test.php',
    'PHPUnit\\Util\\TestDox\\CliTestDoxPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/CliTestDoxPrinter.php',
    'PHPUnit\\Util\\TestDox\\HtmlResultPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/HtmlResultPrinter.php',
    'PHPUnit\\Util\\TestDox\\NamePrettifier' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php',
    'PHPUnit\\Util\\TestDox\\ResultPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php',
    'PHPUnit\\Util\\TestDox\\TestDoxPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/TestDoxPrinter.php',
    'PHPUnit\\Util\\TestDox\\TextResultPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/TextResultPrinter.php',
    'PHPUnit\\Util\\TestDox\\XmlResultPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/XmlResultPrinter.php',
    'PHPUnit\\Util\\TextTestListRenderer' => $vendorDir . '/phpunit/phpunit/src/Util/TextTestListRenderer.php',
    'PHPUnit\\Util\\Type' => $vendorDir . '/phpunit/phpunit/src/Util/Type.php',
    'PHPUnit\\Util\\VersionComparisonOperator' => $vendorDir . '/phpunit/phpunit/src/Util/VersionComparisonOperator.php',
    'PHPUnit\\Util\\XdebugFilterScriptGenerator' => $vendorDir . '/phpunit/phpunit/src/Util/XdebugFilterScriptGenerator.php',
    'PHPUnit\\Util\\Xml' => $vendorDir . '/phpunit/phpunit/src/Util/Xml.php',
    'PHPUnit\\Util\\XmlTestListRenderer' => $vendorDir . '/phpunit/phpunit/src/Util/XmlTestListRenderer.php',
    'PHP_Token' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
    'PHP_TokenWithScope' => $vendorDir . '/phpunit/php-token-stream/src/TokenWithScope.php',
    'PHP_TokenWithScopeAndVisibility' => $vendorDir . '/phpunit/php-token-stream/src/TokenWithScopeAndVisibility.php',
    'PHP_Token_ABSTRACT' => $vendorDir . '/phpunit/php-token-stream/src/Abstract.php',
    'PHP_Token_AMPERSAND' => $vendorDir . '/phpunit/php-token-stream/src/Ampersand.php',
    'PHP_Token_AND_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/AndEqual.php',
    'PHP_Token_ARRAY' => $vendorDir . '/phpunit/php-token-stream/src/Array.php',
    'PHP_Token_ARRAY_CAST' => $vendorDir . '/phpunit/php-token-stream/src/ArrayCast.php',
    'PHP_Token_AS' => $vendorDir . '/phpunit/php-token-stream/src/As.php',
    'PHP_Token_AT' => $vendorDir . '/phpunit/php-token-stream/src/At.php',
    'PHP_Token_BACKTICK' => $vendorDir . '/phpunit/php-token-stream/src/Backtick.php',
    'PHP_Token_BAD_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/BadCharacter.php',
    'PHP_Token_BOOLEAN_AND' => $vendorDir . '/phpunit/php-token-stream/src/BooleanAnd.php',
    'PHP_Token_BOOLEAN_OR' => $vendorDir . '/phpunit/php-token-stream/src/BooleanOr.php',
    'PHP_Token_BOOL_CAST' => $vendorDir . '/phpunit/php-token-stream/src/BoolCast.php',
    'PHP_Token_BREAK' => $vendorDir . '/phpunit/php-token-stream/src/break.php',
    'PHP_Token_CALLABLE' => $vendorDir . '/phpunit/php-token-stream/src/Callable.php',
    'PHP_Token_CARET' => $vendorDir . '/phpunit/php-token-stream/src/Caret.php',
    'PHP_Token_CASE' => $vendorDir . '/phpunit/php-token-stream/src/Case.php',
    'PHP_Token_CATCH' => $vendorDir . '/phpunit/php-token-stream/src/Catch.php',
    'PHP_Token_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/Character.php',
    'PHP_Token_CLASS' => $vendorDir . '/phpunit/php-token-stream/src/Class.php',
    'PHP_Token_CLASS_C' => $vendorDir . '/phpunit/php-token-stream/src/ClassC.php',
    'PHP_Token_CLASS_NAME_CONSTANT' => $vendorDir . '/phpunit/php-token-stream/src/ClassNameConstant.php',
    'PHP_Token_CLONE' => $vendorDir . '/phpunit/php-token-stream/src/Clone.php',
    'PHP_Token_CLOSE_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/CloseBracket.php',
    'PHP_Token_CLOSE_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/CloseCurly.php',
    'PHP_Token_CLOSE_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/CloseSquare.php',
    'PHP_Token_CLOSE_TAG' => $vendorDir . '/phpunit/php-token-stream/src/CloseTag.php',
    'PHP_Token_COALESCE' => $vendorDir . '/phpunit/php-token-stream/src/Coalesce.php',
    'PHP_Token_COALESCE_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/CoalesceEqual.php',
    'PHP_Token_COLON' => $vendorDir . '/phpunit/php-token-stream/src/Colon.php',
    'PHP_Token_COMMA' => $vendorDir . '/phpunit/php-token-stream/src/Comma.php',
    'PHP_Token_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/Comment.php',
    'PHP_Token_CONCAT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/ConcatEqual.php',
    'PHP_Token_CONST' => $vendorDir . '/phpunit/php-token-stream/src/Const.php',
    'PHP_Token_CONSTANT_ENCAPSED_STRING' => $vendorDir . '/phpunit/php-token-stream/src/ConstantEncapsedString.php',
    'PHP_Token_CONTINUE' => $vendorDir . '/phpunit/php-token-stream/src/Continue.php',
    'PHP_Token_CURLY_OPEN' => $vendorDir . '/phpunit/php-token-stream/src/CurlyOpen.php',
    'PHP_Token_DEC' => $vendorDir . '/phpunit/php-token-stream/src/Dec.php',
    'PHP_Token_DECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Declare.php',
    'PHP_Token_DEFAULT' => $vendorDir . '/phpunit/php-token-stream/src/Default.php',
    'PHP_Token_DIR' => $vendorDir . '/phpunit/php-token-stream/src/Dir.php',
    'PHP_Token_DIV' => $vendorDir . '/phpunit/php-token-stream/src/Div.php',
    'PHP_Token_DIV_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/DivEqual.php',
    'PHP_Token_DNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/DNumber.php',
    'PHP_Token_DO' => $vendorDir . '/phpunit/php-token-stream/src/Do.php',
    'PHP_Token_DOC_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/DocComment.php',
    'PHP_Token_DOLLAR' => $vendorDir . '/phpunit/php-token-stream/src/Dollar.php',
    'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => $vendorDir . '/phpunit/php-token-stream/src/DollarOpenCurlyBraces.php',
    'PHP_Token_DOT' => $vendorDir . '/phpunit/php-token-stream/src/Dot.php',
    'PHP_Token_DOUBLE_ARROW' => $vendorDir . '/phpunit/php-token-stream/src/DoubleArrow.php',
    'PHP_Token_DOUBLE_CAST' => $vendorDir . '/phpunit/php-token-stream/src/DoubleCast.php',
    'PHP_Token_DOUBLE_COLON' => $vendorDir . '/phpunit/php-token-stream/src/DoubleColon.php',
    'PHP_Token_DOUBLE_QUOTES' => $vendorDir . '/phpunit/php-token-stream/src/DoubleQuotes.php',
    'PHP_Token_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/Echo.php',
    'PHP_Token_ELLIPSIS' => $vendorDir . '/phpunit/php-token-stream/src/Ellipsis.php',
    'PHP_Token_ELSE' => $vendorDir . '/phpunit/php-token-stream/src/Else.php',
    'PHP_Token_ELSEIF' => $vendorDir . '/phpunit/php-token-stream/src/Elseif.php',
    'PHP_Token_EMPTY' => $vendorDir . '/phpunit/php-token-stream/src/Empty.php',
    'PHP_Token_ENCAPSED_AND_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/EncapsedAndWhitespace.php',
    'PHP_Token_ENDDECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Enddeclare.php',
    'PHP_Token_ENDFOR' => $vendorDir . '/phpunit/php-token-stream/src/Endfor.php',
    'PHP_Token_ENDFOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Endforeach.php',
    'PHP_Token_ENDIF' => $vendorDir . '/phpunit/php-token-stream/src/Endif.php',
    'PHP_Token_ENDSWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Endswitch.php',
    'PHP_Token_ENDWHILE' => $vendorDir . '/phpunit/php-token-stream/src/Endwhile.php',
    'PHP_Token_END_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/EndHeredoc.php',
    'PHP_Token_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Equal.php',
    'PHP_Token_EVAL' => $vendorDir . '/phpunit/php-token-stream/src/Eval.php',
    'PHP_Token_EXCLAMATION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/ExclamationMark.php',
    'PHP_Token_EXIT' => $vendorDir . '/phpunit/php-token-stream/src/Exit.php',
    'PHP_Token_EXTENDS' => $vendorDir . '/phpunit/php-token-stream/src/Extends.php',
    'PHP_Token_FILE' => $vendorDir . '/phpunit/php-token-stream/src/File.php',
    'PHP_Token_FINAL' => $vendorDir . '/phpunit/php-token-stream/src/Final.php',
    'PHP_Token_FINALLY' => $vendorDir . '/phpunit/php-token-stream/src/Finally.php',
    'PHP_Token_FN' => $vendorDir . '/phpunit/php-token-stream/src/Fn.php',
    'PHP_Token_FOR' => $vendorDir . '/phpunit/php-token-stream/src/For.php',
    'PHP_Token_FOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Foreach.php',
    'PHP_Token_FUNCTION' => $vendorDir . '/phpunit/php-token-stream/src/Function.php',
    'PHP_Token_FUNC_C' => $vendorDir . '/phpunit/php-token-stream/src/FuncC.php',
    'PHP_Token_GLOBAL' => $vendorDir . '/phpunit/php-token-stream/src/Global.php',
    'PHP_Token_GOTO' => $vendorDir . '/phpunit/php-token-stream/src/Goto.php',
    'PHP_Token_GT' => $vendorDir . '/phpunit/php-token-stream/src/Gt.php',
    'PHP_Token_HALT_COMPILER' => $vendorDir . '/phpunit/php-token-stream/src/HaltCompiler.php',
    'PHP_Token_IF' => $vendorDir . '/phpunit/php-token-stream/src/If.php',
    'PHP_Token_IMPLEMENTS' => $vendorDir . '/phpunit/php-token-stream/src/Implements.php',
    'PHP_Token_INC' => $vendorDir . '/phpunit/php-token-stream/src/Inc.php',
    'PHP_Token_INCLUDE' => $vendorDir . '/phpunit/php-token-stream/src/Include.php',
    'PHP_Token_INCLUDE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/IncludeOnce.php',
    'PHP_Token_INLINE_HTML' => $vendorDir . '/phpunit/php-token-stream/src/InlineHtml.php',
    'PHP_Token_INSTANCEOF' => $vendorDir . '/phpunit/php-token-stream/src/Instanceof.php',
    'PHP_Token_INSTEADOF' => $vendorDir . '/phpunit/php-token-stream/src/Insteadof.php',
    'PHP_Token_INTERFACE' => $vendorDir . '/phpunit/php-token-stream/src/Interface.php',
    'PHP_Token_INT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/IntCast.php',
    'PHP_Token_ISSET' => $vendorDir . '/phpunit/php-token-stream/src/Isset.php',
    'PHP_Token_IS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/IsEqual.php',
    'PHP_Token_IS_GREATER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/IsGreaterOrEqual.php',
    'PHP_Token_IS_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/IsIdentical.php',
    'PHP_Token_IS_NOT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/IsNotEqual.php',
    'PHP_Token_IS_NOT_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/IsNotIdentical.php',
    'PHP_Token_IS_SMALLER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/IsSmallerOrEqual.php',
    'PHP_Token_Includes' => $vendorDir . '/phpunit/php-token-stream/src/Includes.php',
    'PHP_Token_LINE' => $vendorDir . '/phpunit/php-token-stream/src/Line.php',
    'PHP_Token_LIST' => $vendorDir . '/phpunit/php-token-stream/src/List.php',
    'PHP_Token_LNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Lnumber.php',
    'PHP_Token_LOGICAL_AND' => $vendorDir . '/phpunit/php-token-stream/src/LogicalAnd.php',
    'PHP_Token_LOGICAL_OR' => $vendorDir . '/phpunit/php-token-stream/src/LogicalOr.php',
    'PHP_Token_LOGICAL_XOR' => $vendorDir . '/phpunit/php-token-stream/src/LogicalXor.php',
    'PHP_Token_LT' => $vendorDir . '/phpunit/php-token-stream/src/Lt.php',
    'PHP_Token_METHOD_C' => $vendorDir . '/phpunit/php-token-stream/src/MethodC.php',
    'PHP_Token_MINUS' => $vendorDir . '/phpunit/php-token-stream/src/Minus.php',
    'PHP_Token_MINUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/MinusEqual.php',
    'PHP_Token_MOD_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/ModEqual.php',
    'PHP_Token_MULT' => $vendorDir . '/phpunit/php-token-stream/src/Mult.php',
    'PHP_Token_MUL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/MulEqual.php',
    'PHP_Token_NAMESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Namespace.php',
    'PHP_Token_NAME_FULLY_QUALIFIED' => $vendorDir . '/phpunit/php-token-stream/src/NameFullyQualified.php',
    'PHP_Token_NAME_QUALIFIED' => $vendorDir . '/phpunit/php-token-stream/src/NameQualified.php',
    'PHP_Token_NAME_RELATIVE' => $vendorDir . '/phpunit/php-token-stream/src/NameRelative.php',
    'PHP_Token_NEW' => $vendorDir . '/phpunit/php-token-stream/src/New.php',
    'PHP_Token_NS_C' => $vendorDir . '/phpunit/php-token-stream/src/NsC.php',
    'PHP_Token_NS_SEPARATOR' => $vendorDir . '/phpunit/php-token-stream/src/NsSeparator.php',
    'PHP_Token_NUM_STRING' => $vendorDir . '/phpunit/php-token-stream/src/NumString.php',
    'PHP_Token_OBJECT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/ObjectCast.php',
    'PHP_Token_OBJECT_OPERATOR' => $vendorDir . '/phpunit/php-token-stream/src/ObjectOperator.php',
    'PHP_Token_OPEN_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/OpenBracket.php',
    'PHP_Token_OPEN_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/OpenCurly.php',
    'PHP_Token_OPEN_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/OpenSquare.php',
    'PHP_Token_OPEN_TAG' => $vendorDir . '/phpunit/php-token-stream/src/OpenTag.php',
    'PHP_Token_OPEN_TAG_WITH_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/OpenTagWithEcho.php',
    'PHP_Token_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/OrEqual.php',
    'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => $vendorDir . '/phpunit/php-token-stream/src/PaamayimNekudotayim.php',
    'PHP_Token_PERCENT' => $vendorDir . '/phpunit/php-token-stream/src/Percent.php',
    'PHP_Token_PIPE' => $vendorDir . '/phpunit/php-token-stream/src/Pipe.php',
    'PHP_Token_PLUS' => $vendorDir . '/phpunit/php-token-stream/src/Plus.php',
    'PHP_Token_PLUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/PlusEqual.php',
    'PHP_Token_POW' => $vendorDir . '/phpunit/php-token-stream/src/Pow.php',
    'PHP_Token_POW_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/PowEqual.php',
    'PHP_Token_PRINT' => $vendorDir . '/phpunit/php-token-stream/src/Print.php',
    'PHP_Token_PRIVATE' => $vendorDir . '/phpunit/php-token-stream/src/Private.php',
    'PHP_Token_PROTECTED' => $vendorDir . '/phpunit/php-token-stream/src/Protected.php',
    'PHP_Token_PUBLIC' => $vendorDir . '/phpunit/php-token-stream/src/Public.php',
    'PHP_Token_QUESTION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/QuestionMark.php',
    'PHP_Token_REQUIRE' => $vendorDir . '/phpunit/php-token-stream/src/Require.php',
    'PHP_Token_REQUIRE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/RequireOnce.php',
    'PHP_Token_RETURN' => $vendorDir . '/phpunit/php-token-stream/src/Return.php',
    'PHP_Token_SEMICOLON' => $vendorDir . '/phpunit/php-token-stream/src/Semicolon.php',
    'PHP_Token_SL' => $vendorDir . '/phpunit/php-token-stream/src/Sl.php',
    'PHP_Token_SL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/SlEqual.php',
    'PHP_Token_SPACESHIP' => $vendorDir . '/phpunit/php-token-stream/src/Spaceship.php',
    'PHP_Token_SR' => $vendorDir . '/phpunit/php-token-stream/src/Sr.php',
    'PHP_Token_SR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/SrEqual.php',
    'PHP_Token_START_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/StartHeredoc.php',
    'PHP_Token_STATIC' => $vendorDir . '/phpunit/php-token-stream/src/Static.php',
    'PHP_Token_STRING' => $vendorDir . '/phpunit/php-token-stream/src/String.php',
    'PHP_Token_STRING_CAST' => $vendorDir . '/phpunit/php-token-stream/src/StringCast.php',
    'PHP_Token_STRING_VARNAME' => $vendorDir . '/phpunit/php-token-stream/src/StringVarname.php',
    'PHP_Token_SWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Switch.php',
    'PHP_Token_Stream' => $vendorDir . '/phpunit/php-token-stream/src/Stream.php',
    'PHP_Token_Stream_CachingFactory' => $vendorDir . '/phpunit/php-token-stream/src/CachingFactory.php',
    'PHP_Token_THROW' => $vendorDir . '/phpunit/php-token-stream/src/Throw.php',
    'PHP_Token_TILDE' => $vendorDir . '/phpunit/php-token-stream/src/Tilde.php',
    'PHP_Token_TRAIT' => $vendorDir . '/phpunit/php-token-stream/src/Trait.php',
    'PHP_Token_TRAIT_C' => $vendorDir . '/phpunit/php-token-stream/src/TraitC.php',
    'PHP_Token_TRY' => $vendorDir . '/phpunit/php-token-stream/src/Try.php',
    'PHP_Token_UNSET' => $vendorDir . '/phpunit/php-token-stream/src/Unset.php',
    'PHP_Token_UNSET_CAST' => $vendorDir . '/phpunit/php-token-stream/src/UnsetCast.php',
    'PHP_Token_USE' => $vendorDir . '/phpunit/php-token-stream/src/Use.php',
    'PHP_Token_USE_FUNCTION' => $vendorDir . '/phpunit/php-token-stream/src/UseFunction.php',
    'PHP_Token_Util' => $vendorDir . '/phpunit/php-token-stream/src/Util.php',
    'PHP_Token_VAR' => $vendorDir . '/phpunit/php-token-stream/src/Var.php',
    'PHP_Token_VARIABLE' => $vendorDir . '/phpunit/php-token-stream/src/Variable.php',
    'PHP_Token_WHILE' => $vendorDir . '/phpunit/php-token-stream/src/While.php',
    'PHP_Token_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Whitespace.php',
    'PHP_Token_XOR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/XorEqual.php',
    'PHP_Token_YIELD' => $vendorDir . '/phpunit/php-token-stream/src/Yield.php',
    'PHP_Token_YIELD_FROM' => $vendorDir . '/phpunit/php-token-stream/src/YieldFrom.php',
    'PharIo\\Manifest\\Application' => $vendorDir . '/phar-io/manifest/src/values/Application.php',
    'PharIo\\Manifest\\ApplicationName' => $vendorDir . '/phar-io/manifest/src/values/ApplicationName.php',
    'PharIo\\Manifest\\Author' => $vendorDir . '/phar-io/manifest/src/values/Author.php',
    'PharIo\\Manifest\\AuthorCollection' => $vendorDir . '/phar-io/manifest/src/values/AuthorCollection.php',
    'PharIo\\Manifest\\AuthorCollectionIterator' => $vendorDir . '/phar-io/manifest/src/values/AuthorCollectionIterator.php',
    'PharIo\\Manifest\\AuthorElement' => $vendorDir . '/phar-io/manifest/src/xml/AuthorElement.php',
    'PharIo\\Manifest\\AuthorElementCollection' => $vendorDir . '/phar-io/manifest/src/xml/AuthorElementCollection.php',
    'PharIo\\Manifest\\BundledComponent' => $vendorDir . '/phar-io/manifest/src/values/BundledComponent.php',
    'PharIo\\Manifest\\BundledComponentCollection' => $vendorDir . '/phar-io/manifest/src/values/BundledComponentCollection.php',
    'PharIo\\Manifest\\BundledComponentCollectionIterator' => $vendorDir . '/phar-io/manifest/src/values/BundledComponentCollectionIterator.php',
    'PharIo\\Manifest\\BundlesElement' => $vendorDir . '/phar-io/manifest/src/xml/BundlesElement.php',
    'PharIo\\Manifest\\ComponentElement' => $vendorDir . '/phar-io/manifest/src/xml/ComponentElement.php',
    'PharIo\\Manifest\\ComponentElementCollection' => $vendorDir . '/phar-io/manifest/src/xml/ComponentElementCollection.php',
    'PharIo\\Manifest\\ContainsElement' => $vendorDir . '/phar-io/manifest/src/xml/ContainsElement.php',
    'PharIo\\Manifest\\CopyrightElement' => $vendorDir . '/phar-io/manifest/src/xml/CopyrightElement.php',
    'PharIo\\Manifest\\CopyrightInformation' => $vendorDir . '/phar-io/manifest/src/values/CopyrightInformation.php',
    'PharIo\\Manifest\\ElementCollection' => $vendorDir . '/phar-io/manifest/src/xml/ElementCollection.php',
    'PharIo\\Manifest\\ElementCollectionException' => $vendorDir . '/phar-io/manifest/src/exceptions/ElementCollectionException.php',
    'PharIo\\Manifest\\Email' => $vendorDir . '/phar-io/manifest/src/values/Email.php',
    'PharIo\\Manifest\\Exception' => $vendorDir . '/phar-io/manifest/src/exceptions/Exception.php',
    'PharIo\\Manifest\\ExtElement' => $vendorDir . '/phar-io/manifest/src/xml/ExtElement.php',
    'PharIo\\Manifest\\ExtElementCollection' => $vendorDir . '/phar-io/manifest/src/xml/ExtElementCollection.php',
    'PharIo\\Manifest\\Extension' => $vendorDir . '/phar-io/manifest/src/values/Extension.php',
    'PharIo\\Manifest\\ExtensionElement' => $vendorDir . '/phar-io/manifest/src/xml/ExtensionElement.php',
    'PharIo\\Manifest\\InvalidApplicationNameException' => $vendorDir . '/phar-io/manifest/src/exceptions/InvalidApplicationNameException.php',
    'PharIo\\Manifest\\InvalidEmailException' => $vendorDir . '/phar-io/manifest/src/exceptions/InvalidEmailException.php',
    'PharIo\\Manifest\\InvalidUrlException' => $vendorDir . '/phar-io/manifest/src/exceptions/InvalidUrlException.php',
    'PharIo\\Manifest\\Library' => $vendorDir . '/phar-io/manifest/src/values/Library.php',
    'PharIo\\Manifest\\License' => $vendorDir . '/phar-io/manifest/src/values/License.php',
    'PharIo\\Manifest\\LicenseElement' => $vendorDir . '/phar-io/manifest/src/xml/LicenseElement.php',
    'PharIo\\Manifest\\Manifest' => $vendorDir . '/phar-io/manifest/src/values/Manifest.php',
    'PharIo\\Manifest\\ManifestDocument' => $vendorDir . '/phar-io/manifest/src/xml/ManifestDocument.php',
    'PharIo\\Manifest\\ManifestDocumentException' => $vendorDir . '/phar-io/manifest/src/exceptions/ManifestDocumentException.php',
    'PharIo\\Manifest\\ManifestDocumentLoadingException' => $vendorDir . '/phar-io/manifest/src/exceptions/ManifestDocumentLoadingException.php',
    'PharIo\\Manifest\\ManifestDocumentMapper' => $vendorDir . '/phar-io/manifest/src/ManifestDocumentMapper.php',
    'PharIo\\Manifest\\ManifestDocumentMapperException' => $vendorDir . '/phar-io/manifest/src/exceptions/ManifestDocumentMapperException.php',
    'PharIo\\Manifest\\ManifestElement' => $vendorDir . '/phar-io/manifest/src/xml/ManifestElement.php',
    'PharIo\\Manifest\\ManifestElementException' => $vendorDir . '/phar-io/manifest/src/exceptions/ManifestElementException.php',
    'PharIo\\Manifest\\ManifestLoader' => $vendorDir . '/phar-io/manifest/src/ManifestLoader.php',
    'PharIo\\Manifest\\ManifestLoaderException' => $vendorDir . '/phar-io/manifest/src/exceptions/ManifestLoaderException.php',
    'PharIo\\Manifest\\ManifestSerializer' => $vendorDir . '/phar-io/manifest/src/ManifestSerializer.php',
    'PharIo\\Manifest\\PhpElement' => $vendorDir . '/phar-io/manifest/src/xml/PhpElement.php',
    'PharIo\\Manifest\\PhpExtensionRequirement' => $vendorDir . '/phar-io/manifest/src/values/PhpExtensionRequirement.php',
    'PharIo\\Manifest\\PhpVersionRequirement' => $vendorDir . '/phar-io/manifest/src/values/PhpVersionRequirement.php',
    'PharIo\\Manifest\\Requirement' => $vendorDir . '/phar-io/manifest/src/values/Requirement.php',
    'PharIo\\Manifest\\RequirementCollection' => $vendorDir . '/phar-io/manifest/src/values/RequirementCollection.php',
    'PharIo\\Manifest\\RequirementCollectionIterator' => $vendorDir . '/phar-io/manifest/src/values/RequirementCollectionIterator.php',
    'PharIo\\Manifest\\RequiresElement' => $vendorDir . '/phar-io/manifest/src/xml/RequiresElement.php',
    'PharIo\\Manifest\\Type' => $vendorDir . '/phar-io/manifest/src/values/Type.php',
    'PharIo\\Manifest\\Url' => $vendorDir . '/phar-io/manifest/src/values/Url.php',
    'PharIo\\Version\\AbstractVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/AbstractVersionConstraint.php',
    'PharIo\\Version\\AndVersionConstraintGroup' => $vendorDir . '/phar-io/version/src/constraints/AndVersionConstraintGroup.php',
    'PharIo\\Version\\AnyVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/AnyVersionConstraint.php',
    'PharIo\\Version\\BuildMetaData' => $vendorDir . '/phar-io/version/src/BuildMetaData.php',
    'PharIo\\Version\\ExactVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/ExactVersionConstraint.php',
    'PharIo\\Version\\Exception' => $vendorDir . '/phar-io/version/src/exceptions/Exception.php',
    'PharIo\\Version\\GreaterThanOrEqualToVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/GreaterThanOrEqualToVersionConstraint.php',
    'PharIo\\Version\\InvalidPreReleaseSuffixException' => $vendorDir . '/phar-io/version/src/exceptions/InvalidPreReleaseSuffixException.php',
    'PharIo\\Version\\InvalidVersionException' => $vendorDir . '/phar-io/version/src/exceptions/InvalidVersionException.php',
    'PharIo\\Version\\NoBuildMetaDataException' => $vendorDir . '/phar-io/version/src/exceptions/NoBuildMetaDataException.php',
    'PharIo\\Version\\NoPreReleaseSuffixException' => $vendorDir . '/phar-io/version/src/exceptions/NoPreReleaseSuffixException.php',
    'PharIo\\Version\\OrVersionConstraintGroup' => $vendorDir . '/phar-io/version/src/constraints/OrVersionConstraintGroup.php',
    'PharIo\\Version\\PreReleaseSuffix' => $vendorDir . '/phar-io/version/src/PreReleaseSuffix.php',
    'PharIo\\Version\\SpecificMajorAndMinorVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/SpecificMajorAndMinorVersionConstraint.php',
    'PharIo\\Version\\SpecificMajorVersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/SpecificMajorVersionConstraint.php',
    'PharIo\\Version\\UnsupportedVersionConstraintException' => $vendorDir . '/phar-io/version/src/exceptions/UnsupportedVersionConstraintException.php',
    'PharIo\\Version\\Version' => $vendorDir . '/phar-io/version/src/Version.php',
    'PharIo\\Version\\VersionConstraint' => $vendorDir . '/phar-io/version/src/constraints/VersionConstraint.php',
    'PharIo\\Version\\VersionConstraintParser' => $vendorDir . '/phar-io/version/src/VersionConstraintParser.php',
    'PharIo\\Version\\VersionConstraintValue' => $vendorDir . '/phar-io/version/src/VersionConstraintValue.php',
    'PharIo\\Version\\VersionNumber' => $vendorDir . '/phar-io/version/src/VersionNumber.php',
    'SebastianBergmann\\CodeCoverage\\CodeCoverage' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage.php',
    'SebastianBergmann\\CodeCoverage\\CoveredCodeNotExecutedException' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/CoveredCodeNotExecutedException.php',
    'SebastianBergmann\\CodeCoverage\\Driver\\Driver' => $vendorDir . '/phpunit/php-code-coverage/src/Driver/Driver.php',
    'SebastianBergmann\\CodeCoverage\\Driver\\PCOV' => $vendorDir . '/phpunit/php-code-coverage/src/Driver/PCOV.php',
    'SebastianBergmann\\CodeCoverage\\Driver\\PHPDBG' => $vendorDir . '/phpunit/php-code-coverage/src/Driver/PHPDBG.php',
    'SebastianBergmann\\CodeCoverage\\Driver\\Xdebug' => $vendorDir . '/phpunit/php-code-coverage/src/Driver/Xdebug.php',
    'SebastianBergmann\\CodeCoverage\\Exception' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/Exception.php',
    'SebastianBergmann\\CodeCoverage\\Filter' => $vendorDir . '/phpunit/php-code-coverage/src/Filter.php',
    'SebastianBergmann\\CodeCoverage\\InvalidArgumentException' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/InvalidArgumentException.php',
    'SebastianBergmann\\CodeCoverage\\MissingCoversAnnotationException' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/MissingCoversAnnotationException.php',
    'SebastianBergmann\\CodeCoverage\\Node\\AbstractNode' => $vendorDir . '/phpunit/php-code-coverage/src/Node/AbstractNode.php',
    'SebastianBergmann\\CodeCoverage\\Node\\Builder' => $vendorDir . '/phpunit/php-code-coverage/src/Node/Builder.php',
    'SebastianBergmann\\CodeCoverage\\Node\\Directory' => $vendorDir . '/phpunit/php-code-coverage/src/Node/Directory.php',
    'SebastianBergmann\\CodeCoverage\\Node\\File' => $vendorDir . '/phpunit/php-code-coverage/src/Node/File.php',
    'SebastianBergmann\\CodeCoverage\\Node\\Iterator' => $vendorDir . '/phpunit/php-code-coverage/src/Node/Iterator.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Clover' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Clover.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Crap4j' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Crap4j.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Html\\Dashboard' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Dashboard.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Html\\Directory' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Directory.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Html\\Facade' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Html/Facade.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Html\\File' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Html/Renderer/File.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Html\\Renderer' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Html/Renderer.php',
    'SebastianBergmann\\CodeCoverage\\Report\\PHP' => $vendorDir . '/phpunit/php-code-coverage/src/Report/PHP.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Text' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Text.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\BuildInformation' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/BuildInformation.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Coverage' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Coverage.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Directory' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Directory.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Facade' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Facade.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\File' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/File.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Method' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Method.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Node' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Node.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Project' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Project.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Report' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Report.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Source' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Source.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Tests' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Tests.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Totals' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Totals.php',
    'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Unit' => $vendorDir . '/phpunit/php-code-coverage/src/Report/Xml/Unit.php',
    'SebastianBergmann\\CodeCoverage\\RuntimeException' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/RuntimeException.php',
    'SebastianBergmann\\CodeCoverage\\UnintentionallyCoveredCodeException' => $vendorDir . '/phpunit/php-code-coverage/src/Exception/UnintentionallyCoveredCodeException.php',
    'SebastianBergmann\\CodeCoverage\\Util' => $vendorDir . '/phpunit/php-code-coverage/src/Util.php',
    'SebastianBergmann\\CodeCoverage\\Version' => $vendorDir . '/phpunit/php-code-coverage/src/Version.php',
    'SebastianBergmann\\CodeUnitReverseLookup\\Wizard' => $vendorDir . '/sebastian/code-unit-reverse-lookup/src/Wizard.php',
    'SebastianBergmann\\Comparator\\ArrayComparator' => $vendorDir . '/sebastian/comparator/src/ArrayComparator.php',
    'SebastianBergmann\\Comparator\\Comparator' => $vendorDir . '/sebastian/comparator/src/Comparator.php',
    'SebastianBergmann\\Comparator\\ComparisonFailure' => $vendorDir . '/sebastian/comparator/src/ComparisonFailure.php',
    'SebastianBergmann\\Comparator\\DOMNodeComparator' => $vendorDir . '/sebastian/comparator/src/DOMNodeComparator.php',
    'SebastianBergmann\\Comparator\\DateTimeComparator' => $vendorDir . '/sebastian/comparator/src/DateTimeComparator.php',
    'SebastianBergmann\\Comparator\\DoubleComparator' => $vendorDir . '/sebastian/comparator/src/DoubleComparator.php',
    'SebastianBergmann\\Comparator\\ExceptionComparator' => $vendorDir . '/sebastian/comparator/src/ExceptionComparator.php',
    'SebastianBergmann\\Comparator\\Factory' => $vendorDir . '/sebastian/comparator/src/Factory.php',
    'SebastianBergmann\\Comparator\\MockObjectComparator' => $vendorDir . '/sebastian/comparator/src/MockObjectComparator.php',
    'SebastianBergmann\\Comparator\\NumericComparator' => $vendorDir . '/sebastian/comparator/src/NumericComparator.php',
    'SebastianBergmann\\Comparator\\ObjectComparator' => $vendorDir . '/sebastian/comparator/src/ObjectComparator.php',
    'SebastianBergmann\\Comparator\\ResourceComparator' => $vendorDir . '/sebastian/comparator/src/ResourceComparator.php',
    'SebastianBergmann\\Comparator\\ScalarComparator' => $vendorDir . '/sebastian/comparator/src/ScalarComparator.php',
    'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => $vendorDir . '/sebastian/comparator/src/SplObjectStorageComparator.php',
    'SebastianBergmann\\Comparator\\TypeComparator' => $vendorDir . '/sebastian/comparator/src/TypeComparator.php',
    'SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php',
    'SebastianBergmann\\Diff\\ConfigurationException' => $vendorDir . '/sebastian/diff/src/Exception/ConfigurationException.php',
    'SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php',
    'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php',
    'SebastianBergmann\\Diff\\Exception' => $vendorDir . '/sebastian/diff/src/Exception/Exception.php',
    'SebastianBergmann\\Diff\\InvalidArgumentException' => $vendorDir . '/sebastian/diff/src/Exception/InvalidArgumentException.php',
    'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php',
    'SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php',
    'SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php',
    'SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php',
    'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php',
    'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php',
    'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php',
    'SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php',
    'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php',
    'SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php',
    'SebastianBergmann\\Environment\\Console' => $vendorDir . '/sebastian/environment/src/Console.php',
    'SebastianBergmann\\Environment\\OperatingSystem' => $vendorDir . '/sebastian/environment/src/OperatingSystem.php',
    'SebastianBergmann\\Environment\\Runtime' => $vendorDir . '/sebastian/environment/src/Runtime.php',
    'SebastianBergmann\\Exporter\\Exporter' => $vendorDir . '/sebastian/exporter/src/Exporter.php',
    'SebastianBergmann\\FileIterator\\Facade' => $vendorDir . '/phpunit/php-file-iterator/src/Facade.php',
    'SebastianBergmann\\FileIterator\\Factory' => $vendorDir . '/phpunit/php-file-iterator/src/Factory.php',
    'SebastianBergmann\\FileIterator\\Iterator' => $vendorDir . '/phpunit/php-file-iterator/src/Iterator.php',
    'SebastianBergmann\\GlobalState\\Blacklist' => $vendorDir . '/sebastian/global-state/src/Blacklist.php',
    'SebastianBergmann\\GlobalState\\CodeExporter' => $vendorDir . '/sebastian/global-state/src/CodeExporter.php',
    'SebastianBergmann\\GlobalState\\Exception' => $vendorDir . '/sebastian/global-state/src/exceptions/Exception.php',
    'SebastianBergmann\\GlobalState\\Restorer' => $vendorDir . '/sebastian/global-state/src/Restorer.php',
    'SebastianBergmann\\GlobalState\\RuntimeException' => $vendorDir . '/sebastian/global-state/src/exceptions/RuntimeException.php',
    'SebastianBergmann\\GlobalState\\Snapshot' => $vendorDir . '/sebastian/global-state/src/Snapshot.php',
    'SebastianBergmann\\ObjectEnumerator\\Enumerator' => $vendorDir . '/sebastian/object-enumerator/src/Enumerator.php',
    'SebastianBergmann\\ObjectEnumerator\\Exception' => $vendorDir . '/sebastian/object-enumerator/src/Exception.php',
    'SebastianBergmann\\ObjectEnumerator\\InvalidArgumentException' => $vendorDir . '/sebastian/object-enumerator/src/InvalidArgumentException.php',
    'SebastianBergmann\\ObjectReflector\\Exception' => $vendorDir . '/sebastian/object-reflector/src/Exception.php',
    'SebastianBergmann\\ObjectReflector\\InvalidArgumentException' => $vendorDir . '/sebastian/object-reflector/src/InvalidArgumentException.php',
    'SebastianBergmann\\ObjectReflector\\ObjectReflector' => $vendorDir . '/sebastian/object-reflector/src/ObjectReflector.php',
    'SebastianBergmann\\RecursionContext\\Context' => $vendorDir . '/sebastian/recursion-context/src/Context.php',
    'SebastianBergmann\\RecursionContext\\Exception' => $vendorDir . '/sebastian/recursion-context/src/Exception.php',
    'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => $vendorDir . '/sebastian/recursion-context/src/InvalidArgumentException.php',
    'SebastianBergmann\\ResourceOperations\\ResourceOperations' => $vendorDir . '/sebastian/resource-operations/src/ResourceOperations.php',
    'SebastianBergmann\\Timer\\Exception' => $vendorDir . '/phpunit/php-timer/src/Exception.php',
    'SebastianBergmann\\Timer\\RuntimeException' => $vendorDir . '/phpunit/php-timer/src/RuntimeException.php',
    'SebastianBergmann\\Timer\\Timer' => $vendorDir . '/phpunit/php-timer/src/Timer.php',
    'SebastianBergmann\\Type\\CallableType' => $vendorDir . '/sebastian/type/src/CallableType.php',
    'SebastianBergmann\\Type\\Exception' => $vendorDir . '/sebastian/type/src/exception/Exception.php',
    'SebastianBergmann\\Type\\GenericObjectType' => $vendorDir . '/sebastian/type/src/GenericObjectType.php',
    'SebastianBergmann\\Type\\IterableType' => $vendorDir . '/sebastian/type/src/IterableType.php',
    'SebastianBergmann\\Type\\NullType' => $vendorDir . '/sebastian/type/src/NullType.php',
    'SebastianBergmann\\Type\\ObjectType' => $vendorDir . '/sebastian/type/src/ObjectType.php',
    'SebastianBergmann\\Type\\RuntimeException' => $vendorDir . '/sebastian/type/src/exception/RuntimeException.php',
    'SebastianBergmann\\Type\\SimpleType' => $vendorDir . '/sebastian/type/src/SimpleType.php',
    'SebastianBergmann\\Type\\Type' => $vendorDir . '/sebastian/type/src/Type.php',
    'SebastianBergmann\\Type\\TypeName' => $vendorDir . '/sebastian/type/src/TypeName.php',
    'SebastianBergmann\\Type\\UnknownType' => $vendorDir . '/sebastian/type/src/UnknownType.php',
    'SebastianBergmann\\Type\\VoidType' => $vendorDir . '/sebastian/type/src/VoidType.php',
    'SebastianBergmann\\Version' => $vendorDir . '/sebastian/version/src/Version.php',
    'Text_Template' => $vendorDir . '/phpunit/php-text-template/src/Template.php',
    'TheSeer\\Tokenizer\\Exception' => $vendorDir . '/theseer/tokenizer/src/Exception.php',
    'TheSeer\\Tokenizer\\NamespaceUri' => $vendorDir . '/theseer/tokenizer/src/NamespaceUri.php',
    'TheSeer\\Tokenizer\\NamespaceUriException' => $vendorDir . '/theseer/tokenizer/src/NamespaceUriException.php',
    'TheSeer\\Tokenizer\\Token' => $vendorDir . '/theseer/tokenizer/src/Token.php',
    'TheSeer\\Tokenizer\\TokenCollection' => $vendorDir . '/theseer/tokenizer/src/TokenCollection.php',
    'TheSeer\\Tokenizer\\TokenCollectionException' => $vendorDir . '/theseer/tokenizer/src/TokenCollectionException.php',
    'TheSeer\\Tokenizer\\Tokenizer' => $vendorDir . '/theseer/tokenizer/src/Tokenizer.php',
    'TheSeer\\Tokenizer\\XMLSerializer' => $vendorDir . '/theseer/tokenizer/src/XMLSerializer.php',
);
<?php

// platform_check.php @generated by Composer

$issues = array();

if (!(PHP_VERSION_ID >= 70300)) {
    $issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.0". You are running ' . PHP_VERSION . '.';
}

if ($issues) {
    if (!headers_sent()) {
        header('HTTP/1.1 500 Internal Server Error');
    }
    if (!ini_get('display_errors')) {
        if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
            fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
        } elseif (!headers_sent()) {
            echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
        }
    }
    trigger_error(
        'Composer detected issues in your platform: ' . implode(' ', $issues),
        E_USER_ERROR
    );
}
<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit5d90551c137e56c44ad81de477daaa67
{
    public static $files = array (
        '6124b4c8570aa390c21fafd04a26c69f' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
    );

    public static $prefixLengthsPsr4 = array (
        'S' => 
        array (
            'Symfony\\Component\\EventDispatcher\\' => 34,
        ),
        'P' => 
        array (
            'Psr\\Log\\' => 8,
        ),
        'M' => 
        array (
            'Monolog\\' => 8,
        ),
        'D' => 
        array (
            'Doctrine\\Instantiator\\' => 22,
            'DeepCopy\\' => 9,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'Symfony\\Component\\EventDispatcher\\' => 
        array (
            0 => __DIR__ . '/..' . '/symfony/event-dispatcher',
        ),
        'Psr\\Log\\' => 
        array (
            0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
        ),
        'Monolog\\' => 
        array (
            0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
        ),
        'Doctrine\\Instantiator\\' => 
        array (
            0 => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator',
        ),
        'DeepCopy\\' => 
        array (
            0 => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy',
        ),
    );

    public static $prefixesPsr0 = array (
        'G' => 
        array (
            'Guzzle\\Tests' => 
            array (
                0 => __DIR__ . '/..' . '/guzzle/guzzle/tests',
            ),
            'Guzzle' => 
            array (
                0 => __DIR__ . '/..' . '/guzzle/guzzle/src',
            ),
        ),
        'B' => 
        array (
            'BaiduBce' => 
            array (
                0 => __DIR__ . '/../..' . '/src',
            ),
        ),
    );

    public static $classMap = array (
        'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
        'PHPUnit\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Exception.php',
        'PHPUnit\\Framework\\Assert' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Assert.php',
        'PHPUnit\\Framework\\AssertionFailedError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/AssertionFailedError.php',
        'PHPUnit\\Framework\\CodeCoverageException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/CodeCoverageException.php',
        'PHPUnit\\Framework\\Constraint\\ArrayHasKey' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.php',
        'PHPUnit\\Framework\\Constraint\\ArraySubset' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php',
        'PHPUnit\\Framework\\Constraint\\Attribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Attribute.php',
        'PHPUnit\\Framework\\Constraint\\Callback' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Callback.php',
        'PHPUnit\\Framework\\Constraint\\ClassHasAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php',
        'PHPUnit\\Framework\\Constraint\\ClassHasStaticAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.php',
        'PHPUnit\\Framework\\Constraint\\Composite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Composite.php',
        'PHPUnit\\Framework\\Constraint\\Constraint' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Constraint.php',
        'PHPUnit\\Framework\\Constraint\\Count' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Count.php',
        'PHPUnit\\Framework\\Constraint\\DirectoryExists' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/DirectoryExists.php',
        'PHPUnit\\Framework\\Constraint\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/Exception.php',
        'PHPUnit\\Framework\\Constraint\\ExceptionCode' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.php',
        'PHPUnit\\Framework\\Constraint\\ExceptionMessage' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.php',
        'PHPUnit\\Framework\\Constraint\\ExceptionMessageRegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegularExpression.php',
        'PHPUnit\\Framework\\Constraint\\FileExists' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/FileExists.php',
        'PHPUnit\\Framework\\Constraint\\GreaterThan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php',
        'PHPUnit\\Framework\\Constraint\\IsAnything' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsAnything.php',
        'PHPUnit\\Framework\\Constraint\\IsEmpty' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsEmpty.php',
        'PHPUnit\\Framework\\Constraint\\IsEqual' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsEqual.php',
        'PHPUnit\\Framework\\Constraint\\IsFalse' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsFalse.php',
        'PHPUnit\\Framework\\Constraint\\IsFinite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsFinite.php',
        'PHPUnit\\Framework\\Constraint\\IsIdentical' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php',
        'PHPUnit\\Framework\\Constraint\\IsInfinite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsInfinite.php',
        'PHPUnit\\Framework\\Constraint\\IsInstanceOf' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.php',
        'PHPUnit\\Framework\\Constraint\\IsJson' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsJson.php',
        'PHPUnit\\Framework\\Constraint\\IsNan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsNan.php',
        'PHPUnit\\Framework\\Constraint\\IsNull' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsNull.php',
        'PHPUnit\\Framework\\Constraint\\IsReadable' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsReadable.php',
        'PHPUnit\\Framework\\Constraint\\IsTrue' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
        'PHPUnit\\Framework\\Constraint\\IsType' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
        'PHPUnit\\Framework\\Constraint\\IsWritable' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/IsWritable.php',
        'PHPUnit\\Framework\\Constraint\\JsonMatches' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
        'PHPUnit\\Framework\\Constraint\\JsonMatchesErrorMessageProvider' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php',
        'PHPUnit\\Framework\\Constraint\\LessThan' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
        'PHPUnit\\Framework\\Constraint\\LogicalAnd' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalAnd.php',
        'PHPUnit\\Framework\\Constraint\\LogicalNot' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalNot.php',
        'PHPUnit\\Framework\\Constraint\\LogicalOr' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalOr.php',
        'PHPUnit\\Framework\\Constraint\\LogicalXor' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/LogicalXor.php',
        'PHPUnit\\Framework\\Constraint\\ObjectHasAttribute' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
        'PHPUnit\\Framework\\Constraint\\RegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/RegularExpression.php',
        'PHPUnit\\Framework\\Constraint\\SameSize' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/SameSize.php',
        'PHPUnit\\Framework\\Constraint\\StringContains' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringContains.php',
        'PHPUnit\\Framework\\Constraint\\StringEndsWith' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php',
        'PHPUnit\\Framework\\Constraint\\StringMatchesFormatDescription' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringMatchesFormatDescription.php',
        'PHPUnit\\Framework\\Constraint\\StringStartsWith' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php',
        'PHPUnit\\Framework\\Constraint\\TraversableContains' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContains.php',
        'PHPUnit\\Framework\\Constraint\\TraversableContainsEqual' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsEqual.php',
        'PHPUnit\\Framework\\Constraint\\TraversableContainsIdentical' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsIdentical.php',
        'PHPUnit\\Framework\\Constraint\\TraversableContainsOnly' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
        'PHPUnit\\Framework\\CoveredCodeNotExecutedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/CoveredCodeNotExecutedException.php',
        'PHPUnit\\Framework\\DataProviderTestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/DataProviderTestSuite.php',
        'PHPUnit\\Framework\\Error\\Deprecated' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Deprecated.php',
        'PHPUnit\\Framework\\Error\\Error' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Error.php',
        'PHPUnit\\Framework\\Error\\Notice' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Notice.php',
        'PHPUnit\\Framework\\Error\\Warning' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Error/Warning.php',
        'PHPUnit\\Framework\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/Exception.php',
        'PHPUnit\\Framework\\ExceptionWrapper' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
        'PHPUnit\\Framework\\ExpectationFailedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/ExpectationFailedException.php',
        'PHPUnit\\Framework\\IncompleteTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/IncompleteTest.php',
        'PHPUnit\\Framework\\IncompleteTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/IncompleteTestCase.php',
        'PHPUnit\\Framework\\IncompleteTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/IncompleteTestError.php',
        'PHPUnit\\Framework\\InvalidArgumentException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/InvalidArgumentException.php',
        'PHPUnit\\Framework\\InvalidCoversTargetException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/InvalidCoversTargetException.php',
        'PHPUnit\\Framework\\InvalidDataProviderException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/InvalidDataProviderException.php',
        'PHPUnit\\Framework\\InvalidParameterGroupException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/InvalidParameterGroupException.php',
        'PHPUnit\\Framework\\MissingCoversAnnotationException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/MissingCoversAnnotationException.php',
        'PHPUnit\\Framework\\MockObject\\Api' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Api/Api.php',
        'PHPUnit\\Framework\\MockObject\\BadMethodCallException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Exception/BadMethodCallException.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\Identity' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/Identity.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\InvocationMocker' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationMocker.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\InvocationStubber' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/InvocationStubber.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\Match_' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/Match_.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\MethodNameMatch' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/MethodNameMatch.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\ParametersMatch' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/ParametersMatch.php',
        'PHPUnit\\Framework\\MockObject\\Builder\\Stub' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Builder/Stub.php',
        'PHPUnit\\Framework\\MockObject\\ConfigurableMethod' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/ConfigurableMethod.php',
        'PHPUnit\\Framework\\MockObject\\ConfigurableMethodsAlreadyInitializedException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Exception/ConfigurableMethodsAlreadyInitializedException.php',
        'PHPUnit\\Framework\\MockObject\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Exception/Exception.php',
        'PHPUnit\\Framework\\MockObject\\Generator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Generator.php',
        'PHPUnit\\Framework\\MockObject\\IncompatibleReturnValueException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Exception/IncompatibleReturnValueException.php',
        'PHPUnit\\Framework\\MockObject\\Invocation' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Invocation.php',
        'PHPUnit\\Framework\\MockObject\\InvocationHandler' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/InvocationHandler.php',
        'PHPUnit\\Framework\\MockObject\\Matcher' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Matcher.php',
        'PHPUnit\\Framework\\MockObject\\Method' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Api/Method.php',
        'PHPUnit\\Framework\\MockObject\\MethodNameConstraint' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MethodNameConstraint.php',
        'PHPUnit\\Framework\\MockObject\\MockBuilder' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockBuilder.php',
        'PHPUnit\\Framework\\MockObject\\MockClass' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockClass.php',
        'PHPUnit\\Framework\\MockObject\\MockMethod' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockMethod.php',
        'PHPUnit\\Framework\\MockObject\\MockMethodSet' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockMethodSet.php',
        'PHPUnit\\Framework\\MockObject\\MockObject' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockObject.php',
        'PHPUnit\\Framework\\MockObject\\MockTrait' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockTrait.php',
        'PHPUnit\\Framework\\MockObject\\MockType' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/MockType.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\AnyInvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/AnyInvokedCount.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\AnyParameters' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/AnyParameters.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\ConsecutiveParameters' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/ConsecutiveParameters.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvocationOrder' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvocationOrder.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtIndex' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtIndex.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtLeastCount' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastCount.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtLeastOnce' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtLeastOnce.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvokedAtMostCount' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedAtMostCount.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\InvokedCount' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/InvokedCount.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\MethodName' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/MethodName.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\Parameters' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/Parameters.php',
        'PHPUnit\\Framework\\MockObject\\Rule\\ParametersRule' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Rule/ParametersRule.php',
        'PHPUnit\\Framework\\MockObject\\RuntimeException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Exception/RuntimeException.php',
        'PHPUnit\\Framework\\MockObject\\Stub' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ConsecutiveCalls' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ConsecutiveCalls.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/Exception.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnArgument' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnArgument.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnCallback' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnCallback.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnReference' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnReference.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnSelf' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnSelf.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnStub' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnStub.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\ReturnValueMap' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/ReturnValueMap.php',
        'PHPUnit\\Framework\\MockObject\\Stub\\Stub' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Stub/Stub.php',
        'PHPUnit\\Framework\\MockObject\\Verifiable' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/MockObject/Verifiable.php',
        'PHPUnit\\Framework\\NoChildTestSuiteException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/NoChildTestSuiteException.php',
        'PHPUnit\\Framework\\OutputError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/OutputError.php',
        'PHPUnit\\Framework\\PHPTAssertionFailedError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/PHPTAssertionFailedError.php',
        'PHPUnit\\Framework\\RiskyTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/RiskyTestError.php',
        'PHPUnit\\Framework\\SelfDescribing' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SelfDescribing.php',
        'PHPUnit\\Framework\\SkippedTest' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTest.php',
        'PHPUnit\\Framework\\SkippedTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/SkippedTestCase.php',
        'PHPUnit\\Framework\\SkippedTestError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/SkippedTestError.php',
        'PHPUnit\\Framework\\SkippedTestSuiteError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/SkippedTestSuiteError.php',
        'PHPUnit\\Framework\\SyntheticError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/SyntheticError.php',
        'PHPUnit\\Framework\\SyntheticSkippedError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/SyntheticSkippedError.php',
        'PHPUnit\\Framework\\Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Test.php',
        'PHPUnit\\Framework\\TestBuilder' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestBuilder.php',
        'PHPUnit\\Framework\\TestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestCase.php',
        'PHPUnit\\Framework\\TestFailure' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestFailure.php',
        'PHPUnit\\Framework\\TestListener' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestListener.php',
        'PHPUnit\\Framework\\TestListenerDefaultImplementation' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestListenerDefaultImplementation.php',
        'PHPUnit\\Framework\\TestResult' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestResult.php',
        'PHPUnit\\Framework\\TestSuite' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuite.php',
        'PHPUnit\\Framework\\TestSuiteIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/TestSuiteIterator.php',
        'PHPUnit\\Framework\\UnintentionallyCoveredCodeError' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/UnintentionallyCoveredCodeError.php',
        'PHPUnit\\Framework\\Warning' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/Exception/Warning.php',
        'PHPUnit\\Framework\\WarningTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Framework/WarningTestCase.php',
        'PHPUnit\\Runner\\AfterIncompleteTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterIncompleteTestHook.php',
        'PHPUnit\\Runner\\AfterLastTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterLastTestHook.php',
        'PHPUnit\\Runner\\AfterRiskyTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterRiskyTestHook.php',
        'PHPUnit\\Runner\\AfterSkippedTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterSkippedTestHook.php',
        'PHPUnit\\Runner\\AfterSuccessfulTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterSuccessfulTestHook.php',
        'PHPUnit\\Runner\\AfterTestErrorHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterTestErrorHook.php',
        'PHPUnit\\Runner\\AfterTestFailureHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterTestFailureHook.php',
        'PHPUnit\\Runner\\AfterTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterTestHook.php',
        'PHPUnit\\Runner\\AfterTestWarningHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/AfterTestWarningHook.php',
        'PHPUnit\\Runner\\BaseTestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
        'PHPUnit\\Runner\\BeforeFirstTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/BeforeFirstTestHook.php',
        'PHPUnit\\Runner\\BeforeTestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/BeforeTestHook.php',
        'PHPUnit\\Runner\\DefaultTestResultCache' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/DefaultTestResultCache.php',
        'PHPUnit\\Runner\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Exception.php',
        'PHPUnit\\Runner\\Filter\\ExcludeGroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/ExcludeGroupFilterIterator.php',
        'PHPUnit\\Runner\\Filter\\Factory' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
        'PHPUnit\\Runner\\Filter\\GroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/GroupFilterIterator.php',
        'PHPUnit\\Runner\\Filter\\IncludeGroupFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/IncludeGroupFilterIterator.php',
        'PHPUnit\\Runner\\Filter\\NameFilterIterator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Filter/NameFilterIterator.php',
        'PHPUnit\\Runner\\Hook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/Hook.php',
        'PHPUnit\\Runner\\NullTestResultCache' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/NullTestResultCache.php',
        'PHPUnit\\Runner\\PhptTestCase' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/PhptTestCase.php',
        'PHPUnit\\Runner\\ResultCacheExtension' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/ResultCacheExtension.php',
        'PHPUnit\\Runner\\StandardTestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
        'PHPUnit\\Runner\\TestHook' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/TestHook.php',
        'PHPUnit\\Runner\\TestListenerAdapter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Hook/TestListenerAdapter.php',
        'PHPUnit\\Runner\\TestResultCache' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/TestResultCache.php',
        'PHPUnit\\Runner\\TestSuiteLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
        'PHPUnit\\Runner\\TestSuiteSorter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/TestSuiteSorter.php',
        'PHPUnit\\Runner\\Version' => __DIR__ . '/..' . '/phpunit/phpunit/src/Runner/Version.php',
        'PHPUnit\\TextUI\\Command' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/Command.php',
        'PHPUnit\\TextUI\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/Exception.php',
        'PHPUnit\\TextUI\\Help' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/Help.php',
        'PHPUnit\\TextUI\\ResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
        'PHPUnit\\TextUI\\TestRunner' => __DIR__ . '/..' . '/phpunit/phpunit/src/TextUI/TestRunner.php',
        'PHPUnit\\Util\\Annotation\\DocBlock' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Annotation/DocBlock.php',
        'PHPUnit\\Util\\Annotation\\Registry' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Annotation/Registry.php',
        'PHPUnit\\Util\\Blacklist' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Blacklist.php',
        'PHPUnit\\Util\\Color' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Color.php',
        'PHPUnit\\Util\\Configuration' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Configuration.php',
        'PHPUnit\\Util\\ConfigurationGenerator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/ConfigurationGenerator.php',
        'PHPUnit\\Util\\ErrorHandler' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/ErrorHandler.php',
        'PHPUnit\\Util\\Exception' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Exception.php',
        'PHPUnit\\Util\\FileLoader' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/FileLoader.php',
        'PHPUnit\\Util\\Filesystem' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Filesystem.php',
        'PHPUnit\\Util\\Filter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Filter.php',
        'PHPUnit\\Util\\Getopt' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Getopt.php',
        'PHPUnit\\Util\\GlobalState' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/GlobalState.php',
        'PHPUnit\\Util\\InvalidDataSetException' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/InvalidDataSetException.php',
        'PHPUnit\\Util\\Json' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Json.php',
        'PHPUnit\\Util\\Log\\JUnit' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/JUnit.php',
        'PHPUnit\\Util\\Log\\TeamCity' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Log/TeamCity.php',
        'PHPUnit\\Util\\PHP\\AbstractPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/AbstractPhpProcess.php',
        'PHPUnit\\Util\\PHP\\DefaultPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/DefaultPhpProcess.php',
        'PHPUnit\\Util\\PHP\\WindowsPhpProcess' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/PHP/WindowsPhpProcess.php',
        'PHPUnit\\Util\\Printer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Printer.php',
        'PHPUnit\\Util\\Reflection' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Reflection.php',
        'PHPUnit\\Util\\RegularExpression' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/RegularExpression.php',
        'PHPUnit\\Util\\Test' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Test.php',
        'PHPUnit\\Util\\TestDox\\CliTestDoxPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/CliTestDoxPrinter.php',
        'PHPUnit\\Util\\TestDox\\HtmlResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/HtmlResultPrinter.php',
        'PHPUnit\\Util\\TestDox\\NamePrettifier' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php',
        'PHPUnit\\Util\\TestDox\\ResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php',
        'PHPUnit\\Util\\TestDox\\TestDoxPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/TestDoxPrinter.php',
        'PHPUnit\\Util\\TestDox\\TextResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/TextResultPrinter.php',
        'PHPUnit\\Util\\TestDox\\XmlResultPrinter' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TestDox/XmlResultPrinter.php',
        'PHPUnit\\Util\\TextTestListRenderer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/TextTestListRenderer.php',
        'PHPUnit\\Util\\Type' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Type.php',
        'PHPUnit\\Util\\VersionComparisonOperator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/VersionComparisonOperator.php',
        'PHPUnit\\Util\\XdebugFilterScriptGenerator' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/XdebugFilterScriptGenerator.php',
        'PHPUnit\\Util\\Xml' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/Xml.php',
        'PHPUnit\\Util\\XmlTestListRenderer' => __DIR__ . '/..' . '/phpunit/phpunit/src/Util/XmlTestListRenderer.php',
        'PHP_Token' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Token.php',
        'PHP_TokenWithScope' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/TokenWithScope.php',
        'PHP_TokenWithScopeAndVisibility' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/TokenWithScopeAndVisibility.php',
        'PHP_Token_ABSTRACT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Abstract.php',
        'PHP_Token_AMPERSAND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Ampersand.php',
        'PHP_Token_AND_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/AndEqual.php',
        'PHP_Token_ARRAY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Array.php',
        'PHP_Token_ARRAY_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ArrayCast.php',
        'PHP_Token_AS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/As.php',
        'PHP_Token_AT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/At.php',
        'PHP_Token_BACKTICK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Backtick.php',
        'PHP_Token_BAD_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/BadCharacter.php',
        'PHP_Token_BOOLEAN_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/BooleanAnd.php',
        'PHP_Token_BOOLEAN_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/BooleanOr.php',
        'PHP_Token_BOOL_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/BoolCast.php',
        'PHP_Token_BREAK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/break.php',
        'PHP_Token_CALLABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Callable.php',
        'PHP_Token_CARET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Caret.php',
        'PHP_Token_CASE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Case.php',
        'PHP_Token_CATCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Catch.php',
        'PHP_Token_CHARACTER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Character.php',
        'PHP_Token_CLASS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Class.php',
        'PHP_Token_CLASS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ClassC.php',
        'PHP_Token_CLASS_NAME_CONSTANT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ClassNameConstant.php',
        'PHP_Token_CLONE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Clone.php',
        'PHP_Token_CLOSE_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CloseBracket.php',
        'PHP_Token_CLOSE_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CloseCurly.php',
        'PHP_Token_CLOSE_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CloseSquare.php',
        'PHP_Token_CLOSE_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CloseTag.php',
        'PHP_Token_COALESCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Coalesce.php',
        'PHP_Token_COALESCE_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CoalesceEqual.php',
        'PHP_Token_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Colon.php',
        'PHP_Token_COMMA' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Comma.php',
        'PHP_Token_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Comment.php',
        'PHP_Token_CONCAT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ConcatEqual.php',
        'PHP_Token_CONST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Const.php',
        'PHP_Token_CONSTANT_ENCAPSED_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ConstantEncapsedString.php',
        'PHP_Token_CONTINUE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Continue.php',
        'PHP_Token_CURLY_OPEN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CurlyOpen.php',
        'PHP_Token_DEC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Dec.php',
        'PHP_Token_DECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Declare.php',
        'PHP_Token_DEFAULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Default.php',
        'PHP_Token_DIR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Dir.php',
        'PHP_Token_DIV' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Div.php',
        'PHP_Token_DIV_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DivEqual.php',
        'PHP_Token_DNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DNumber.php',
        'PHP_Token_DO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Do.php',
        'PHP_Token_DOC_COMMENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DocComment.php',
        'PHP_Token_DOLLAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Dollar.php',
        'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DollarOpenCurlyBraces.php',
        'PHP_Token_DOT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Dot.php',
        'PHP_Token_DOUBLE_ARROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DoubleArrow.php',
        'PHP_Token_DOUBLE_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DoubleCast.php',
        'PHP_Token_DOUBLE_COLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DoubleColon.php',
        'PHP_Token_DOUBLE_QUOTES' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/DoubleQuotes.php',
        'PHP_Token_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Echo.php',
        'PHP_Token_ELLIPSIS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Ellipsis.php',
        'PHP_Token_ELSE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Else.php',
        'PHP_Token_ELSEIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Elseif.php',
        'PHP_Token_EMPTY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Empty.php',
        'PHP_Token_ENCAPSED_AND_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/EncapsedAndWhitespace.php',
        'PHP_Token_ENDDECLARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Enddeclare.php',
        'PHP_Token_ENDFOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Endfor.php',
        'PHP_Token_ENDFOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Endforeach.php',
        'PHP_Token_ENDIF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Endif.php',
        'PHP_Token_ENDSWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Endswitch.php',
        'PHP_Token_ENDWHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Endwhile.php',
        'PHP_Token_END_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/EndHeredoc.php',
        'PHP_Token_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Equal.php',
        'PHP_Token_EVAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Eval.php',
        'PHP_Token_EXCLAMATION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ExclamationMark.php',
        'PHP_Token_EXIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Exit.php',
        'PHP_Token_EXTENDS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Extends.php',
        'PHP_Token_FILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/File.php',
        'PHP_Token_FINAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Final.php',
        'PHP_Token_FINALLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Finally.php',
        'PHP_Token_FN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Fn.php',
        'PHP_Token_FOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/For.php',
        'PHP_Token_FOREACH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Foreach.php',
        'PHP_Token_FUNCTION' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Function.php',
        'PHP_Token_FUNC_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/FuncC.php',
        'PHP_Token_GLOBAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Global.php',
        'PHP_Token_GOTO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Goto.php',
        'PHP_Token_GT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Gt.php',
        'PHP_Token_HALT_COMPILER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/HaltCompiler.php',
        'PHP_Token_IF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/If.php',
        'PHP_Token_IMPLEMENTS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Implements.php',
        'PHP_Token_INC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Inc.php',
        'PHP_Token_INCLUDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Include.php',
        'PHP_Token_INCLUDE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IncludeOnce.php',
        'PHP_Token_INLINE_HTML' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/InlineHtml.php',
        'PHP_Token_INSTANCEOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Instanceof.php',
        'PHP_Token_INSTEADOF' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Insteadof.php',
        'PHP_Token_INTERFACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Interface.php',
        'PHP_Token_INT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IntCast.php',
        'PHP_Token_ISSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Isset.php',
        'PHP_Token_IS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsEqual.php',
        'PHP_Token_IS_GREATER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsGreaterOrEqual.php',
        'PHP_Token_IS_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsIdentical.php',
        'PHP_Token_IS_NOT_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsNotEqual.php',
        'PHP_Token_IS_NOT_IDENTICAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsNotIdentical.php',
        'PHP_Token_IS_SMALLER_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/IsSmallerOrEqual.php',
        'PHP_Token_Includes' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Includes.php',
        'PHP_Token_LINE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Line.php',
        'PHP_Token_LIST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/List.php',
        'PHP_Token_LNUMBER' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Lnumber.php',
        'PHP_Token_LOGICAL_AND' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/LogicalAnd.php',
        'PHP_Token_LOGICAL_OR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/LogicalOr.php',
        'PHP_Token_LOGICAL_XOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/LogicalXor.php',
        'PHP_Token_LT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Lt.php',
        'PHP_Token_METHOD_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/MethodC.php',
        'PHP_Token_MINUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Minus.php',
        'PHP_Token_MINUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/MinusEqual.php',
        'PHP_Token_MOD_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ModEqual.php',
        'PHP_Token_MULT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Mult.php',
        'PHP_Token_MUL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/MulEqual.php',
        'PHP_Token_NAMESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Namespace.php',
        'PHP_Token_NAME_FULLY_QUALIFIED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NameFullyQualified.php',
        'PHP_Token_NAME_QUALIFIED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NameQualified.php',
        'PHP_Token_NAME_RELATIVE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NameRelative.php',
        'PHP_Token_NEW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/New.php',
        'PHP_Token_NS_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NsC.php',
        'PHP_Token_NS_SEPARATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NsSeparator.php',
        'PHP_Token_NUM_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/NumString.php',
        'PHP_Token_OBJECT_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ObjectCast.php',
        'PHP_Token_OBJECT_OPERATOR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/ObjectOperator.php',
        'PHP_Token_OPEN_BRACKET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OpenBracket.php',
        'PHP_Token_OPEN_CURLY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OpenCurly.php',
        'PHP_Token_OPEN_SQUARE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OpenSquare.php',
        'PHP_Token_OPEN_TAG' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OpenTag.php',
        'PHP_Token_OPEN_TAG_WITH_ECHO' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OpenTagWithEcho.php',
        'PHP_Token_OR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/OrEqual.php',
        'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/PaamayimNekudotayim.php',
        'PHP_Token_PERCENT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Percent.php',
        'PHP_Token_PIPE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Pipe.php',
        'PHP_Token_PLUS' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Plus.php',
        'PHP_Token_PLUS_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/PlusEqual.php',
        'PHP_Token_POW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Pow.php',
        'PHP_Token_POW_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/PowEqual.php',
        'PHP_Token_PRINT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Print.php',
        'PHP_Token_PRIVATE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Private.php',
        'PHP_Token_PROTECTED' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Protected.php',
        'PHP_Token_PUBLIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Public.php',
        'PHP_Token_QUESTION_MARK' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/QuestionMark.php',
        'PHP_Token_REQUIRE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Require.php',
        'PHP_Token_REQUIRE_ONCE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/RequireOnce.php',
        'PHP_Token_RETURN' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Return.php',
        'PHP_Token_SEMICOLON' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Semicolon.php',
        'PHP_Token_SL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Sl.php',
        'PHP_Token_SL_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/SlEqual.php',
        'PHP_Token_SPACESHIP' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Spaceship.php',
        'PHP_Token_SR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Sr.php',
        'PHP_Token_SR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/SrEqual.php',
        'PHP_Token_START_HEREDOC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/StartHeredoc.php',
        'PHP_Token_STATIC' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Static.php',
        'PHP_Token_STRING' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/String.php',
        'PHP_Token_STRING_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/StringCast.php',
        'PHP_Token_STRING_VARNAME' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/StringVarname.php',
        'PHP_Token_SWITCH' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Switch.php',
        'PHP_Token_Stream' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Stream.php',
        'PHP_Token_Stream_CachingFactory' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/CachingFactory.php',
        'PHP_Token_THROW' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Throw.php',
        'PHP_Token_TILDE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Tilde.php',
        'PHP_Token_TRAIT' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Trait.php',
        'PHP_Token_TRAIT_C' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/TraitC.php',
        'PHP_Token_TRY' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Try.php',
        'PHP_Token_UNSET' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Unset.php',
        'PHP_Token_UNSET_CAST' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/UnsetCast.php',
        'PHP_Token_USE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Use.php',
        'PHP_Token_USE_FUNCTION' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/UseFunction.php',
        'PHP_Token_Util' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Util.php',
        'PHP_Token_VAR' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Var.php',
        'PHP_Token_VARIABLE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Variable.php',
        'PHP_Token_WHILE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/While.php',
        'PHP_Token_WHITESPACE' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Whitespace.php',
        'PHP_Token_XOR_EQUAL' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/XorEqual.php',
        'PHP_Token_YIELD' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/Yield.php',
        'PHP_Token_YIELD_FROM' => __DIR__ . '/..' . '/phpunit/php-token-stream/src/YieldFrom.php',
        'PharIo\\Manifest\\Application' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Application.php',
        'PharIo\\Manifest\\ApplicationName' => __DIR__ . '/..' . '/phar-io/manifest/src/values/ApplicationName.php',
        'PharIo\\Manifest\\Author' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Author.php',
        'PharIo\\Manifest\\AuthorCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/AuthorCollection.php',
        'PharIo\\Manifest\\AuthorCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/AuthorCollectionIterator.php',
        'PharIo\\Manifest\\AuthorElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/AuthorElement.php',
        'PharIo\\Manifest\\AuthorElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/AuthorElementCollection.php',
        'PharIo\\Manifest\\BundledComponent' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponent.php',
        'PharIo\\Manifest\\BundledComponentCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponentCollection.php',
        'PharIo\\Manifest\\BundledComponentCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/BundledComponentCollectionIterator.php',
        'PharIo\\Manifest\\BundlesElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/BundlesElement.php',
        'PharIo\\Manifest\\ComponentElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ComponentElement.php',
        'PharIo\\Manifest\\ComponentElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ComponentElementCollection.php',
        'PharIo\\Manifest\\ContainsElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ContainsElement.php',
        'PharIo\\Manifest\\CopyrightElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/CopyrightElement.php',
        'PharIo\\Manifest\\CopyrightInformation' => __DIR__ . '/..' . '/phar-io/manifest/src/values/CopyrightInformation.php',
        'PharIo\\Manifest\\ElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ElementCollection.php',
        'PharIo\\Manifest\\ElementCollectionException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ElementCollectionException.php',
        'PharIo\\Manifest\\Email' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Email.php',
        'PharIo\\Manifest\\Exception' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/Exception.php',
        'PharIo\\Manifest\\ExtElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtElement.php',
        'PharIo\\Manifest\\ExtElementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtElementCollection.php',
        'PharIo\\Manifest\\Extension' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Extension.php',
        'PharIo\\Manifest\\ExtensionElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ExtensionElement.php',
        'PharIo\\Manifest\\InvalidApplicationNameException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidApplicationNameException.php',
        'PharIo\\Manifest\\InvalidEmailException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidEmailException.php',
        'PharIo\\Manifest\\InvalidUrlException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/InvalidUrlException.php',
        'PharIo\\Manifest\\Library' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Library.php',
        'PharIo\\Manifest\\License' => __DIR__ . '/..' . '/phar-io/manifest/src/values/License.php',
        'PharIo\\Manifest\\LicenseElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/LicenseElement.php',
        'PharIo\\Manifest\\Manifest' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Manifest.php',
        'PharIo\\Manifest\\ManifestDocument' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ManifestDocument.php',
        'PharIo\\Manifest\\ManifestDocumentException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestDocumentException.php',
        'PharIo\\Manifest\\ManifestDocumentLoadingException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestDocumentLoadingException.php',
        'PharIo\\Manifest\\ManifestDocumentMapper' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestDocumentMapper.php',
        'PharIo\\Manifest\\ManifestDocumentMapperException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestDocumentMapperException.php',
        'PharIo\\Manifest\\ManifestElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/ManifestElement.php',
        'PharIo\\Manifest\\ManifestElementException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestElementException.php',
        'PharIo\\Manifest\\ManifestLoader' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestLoader.php',
        'PharIo\\Manifest\\ManifestLoaderException' => __DIR__ . '/..' . '/phar-io/manifest/src/exceptions/ManifestLoaderException.php',
        'PharIo\\Manifest\\ManifestSerializer' => __DIR__ . '/..' . '/phar-io/manifest/src/ManifestSerializer.php',
        'PharIo\\Manifest\\PhpElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/PhpElement.php',
        'PharIo\\Manifest\\PhpExtensionRequirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/PhpExtensionRequirement.php',
        'PharIo\\Manifest\\PhpVersionRequirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/PhpVersionRequirement.php',
        'PharIo\\Manifest\\Requirement' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Requirement.php',
        'PharIo\\Manifest\\RequirementCollection' => __DIR__ . '/..' . '/phar-io/manifest/src/values/RequirementCollection.php',
        'PharIo\\Manifest\\RequirementCollectionIterator' => __DIR__ . '/..' . '/phar-io/manifest/src/values/RequirementCollectionIterator.php',
        'PharIo\\Manifest\\RequiresElement' => __DIR__ . '/..' . '/phar-io/manifest/src/xml/RequiresElement.php',
        'PharIo\\Manifest\\Type' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Type.php',
        'PharIo\\Manifest\\Url' => __DIR__ . '/..' . '/phar-io/manifest/src/values/Url.php',
        'PharIo\\Version\\AbstractVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/AbstractVersionConstraint.php',
        'PharIo\\Version\\AndVersionConstraintGroup' => __DIR__ . '/..' . '/phar-io/version/src/constraints/AndVersionConstraintGroup.php',
        'PharIo\\Version\\AnyVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/AnyVersionConstraint.php',
        'PharIo\\Version\\BuildMetaData' => __DIR__ . '/..' . '/phar-io/version/src/BuildMetaData.php',
        'PharIo\\Version\\ExactVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/ExactVersionConstraint.php',
        'PharIo\\Version\\Exception' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/Exception.php',
        'PharIo\\Version\\GreaterThanOrEqualToVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/GreaterThanOrEqualToVersionConstraint.php',
        'PharIo\\Version\\InvalidPreReleaseSuffixException' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/InvalidPreReleaseSuffixException.php',
        'PharIo\\Version\\InvalidVersionException' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/InvalidVersionException.php',
        'PharIo\\Version\\NoBuildMetaDataException' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/NoBuildMetaDataException.php',
        'PharIo\\Version\\NoPreReleaseSuffixException' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/NoPreReleaseSuffixException.php',
        'PharIo\\Version\\OrVersionConstraintGroup' => __DIR__ . '/..' . '/phar-io/version/src/constraints/OrVersionConstraintGroup.php',
        'PharIo\\Version\\PreReleaseSuffix' => __DIR__ . '/..' . '/phar-io/version/src/PreReleaseSuffix.php',
        'PharIo\\Version\\SpecificMajorAndMinorVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/SpecificMajorAndMinorVersionConstraint.php',
        'PharIo\\Version\\SpecificMajorVersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/SpecificMajorVersionConstraint.php',
        'PharIo\\Version\\UnsupportedVersionConstraintException' => __DIR__ . '/..' . '/phar-io/version/src/exceptions/UnsupportedVersionConstraintException.php',
        'PharIo\\Version\\Version' => __DIR__ . '/..' . '/phar-io/version/src/Version.php',
        'PharIo\\Version\\VersionConstraint' => __DIR__ . '/..' . '/phar-io/version/src/constraints/VersionConstraint.php',
        'PharIo\\Version\\VersionConstraintParser' => __DIR__ . '/..' . '/phar-io/version/src/VersionConstraintParser.php',
        'PharIo\\Version\\VersionConstraintValue' => __DIR__ . '/..' . '/phar-io/version/src/VersionConstraintValue.php',
        'PharIo\\Version\\VersionNumber' => __DIR__ . '/..' . '/phar-io/version/src/VersionNumber.php',
        'SebastianBergmann\\CodeCoverage\\CodeCoverage' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/CodeCoverage.php',
        'SebastianBergmann\\CodeCoverage\\CoveredCodeNotExecutedException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/CoveredCodeNotExecutedException.php',
        'SebastianBergmann\\CodeCoverage\\Driver\\Driver' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/Driver.php',
        'SebastianBergmann\\CodeCoverage\\Driver\\PCOV' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/PCOV.php',
        'SebastianBergmann\\CodeCoverage\\Driver\\PHPDBG' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/PHPDBG.php',
        'SebastianBergmann\\CodeCoverage\\Driver\\Xdebug' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Driver/Xdebug.php',
        'SebastianBergmann\\CodeCoverage\\Exception' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/Exception.php',
        'SebastianBergmann\\CodeCoverage\\Filter' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Filter.php',
        'SebastianBergmann\\CodeCoverage\\InvalidArgumentException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/InvalidArgumentException.php',
        'SebastianBergmann\\CodeCoverage\\MissingCoversAnnotationException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/MissingCoversAnnotationException.php',
        'SebastianBergmann\\CodeCoverage\\Node\\AbstractNode' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/AbstractNode.php',
        'SebastianBergmann\\CodeCoverage\\Node\\Builder' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Builder.php',
        'SebastianBergmann\\CodeCoverage\\Node\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Directory.php',
        'SebastianBergmann\\CodeCoverage\\Node\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/File.php',
        'SebastianBergmann\\CodeCoverage\\Node\\Iterator' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Node/Iterator.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Clover' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Clover.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Crap4j' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Crap4j.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Html\\Dashboard' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Dashboard.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Html\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/Directory.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Html\\Facade' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Facade.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Html\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer/File.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Html\\Renderer' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Html/Renderer.php',
        'SebastianBergmann\\CodeCoverage\\Report\\PHP' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/PHP.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Text' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Text.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\BuildInformation' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/BuildInformation.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Coverage' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Coverage.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Directory' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Directory.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Facade' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Facade.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\File' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/File.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Method' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Method.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Node' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Node.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Project' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Project.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Report' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Report.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Source' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Source.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Tests' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Tests.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Totals' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Totals.php',
        'SebastianBergmann\\CodeCoverage\\Report\\Xml\\Unit' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Report/Xml/Unit.php',
        'SebastianBergmann\\CodeCoverage\\RuntimeException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/RuntimeException.php',
        'SebastianBergmann\\CodeCoverage\\UnintentionallyCoveredCodeException' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Exception/UnintentionallyCoveredCodeException.php',
        'SebastianBergmann\\CodeCoverage\\Util' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Util.php',
        'SebastianBergmann\\CodeCoverage\\Version' => __DIR__ . '/..' . '/phpunit/php-code-coverage/src/Version.php',
        'SebastianBergmann\\CodeUnitReverseLookup\\Wizard' => __DIR__ . '/..' . '/sebastian/code-unit-reverse-lookup/src/Wizard.php',
        'SebastianBergmann\\Comparator\\ArrayComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ArrayComparator.php',
        'SebastianBergmann\\Comparator\\Comparator' => __DIR__ . '/..' . '/sebastian/comparator/src/Comparator.php',
        'SebastianBergmann\\Comparator\\ComparisonFailure' => __DIR__ . '/..' . '/sebastian/comparator/src/ComparisonFailure.php',
        'SebastianBergmann\\Comparator\\DOMNodeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DOMNodeComparator.php',
        'SebastianBergmann\\Comparator\\DateTimeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DateTimeComparator.php',
        'SebastianBergmann\\Comparator\\DoubleComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/DoubleComparator.php',
        'SebastianBergmann\\Comparator\\ExceptionComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ExceptionComparator.php',
        'SebastianBergmann\\Comparator\\Factory' => __DIR__ . '/..' . '/sebastian/comparator/src/Factory.php',
        'SebastianBergmann\\Comparator\\MockObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/MockObjectComparator.php',
        'SebastianBergmann\\Comparator\\NumericComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/NumericComparator.php',
        'SebastianBergmann\\Comparator\\ObjectComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ObjectComparator.php',
        'SebastianBergmann\\Comparator\\ResourceComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ResourceComparator.php',
        'SebastianBergmann\\Comparator\\ScalarComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/ScalarComparator.php',
        'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/SplObjectStorageComparator.php',
        'SebastianBergmann\\Comparator\\TypeComparator' => __DIR__ . '/..' . '/sebastian/comparator/src/TypeComparator.php',
        'SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php',
        'SebastianBergmann\\Diff\\ConfigurationException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/ConfigurationException.php',
        'SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php',
        'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php',
        'SebastianBergmann\\Diff\\Exception' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/Exception.php',
        'SebastianBergmann\\Diff\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/InvalidArgumentException.php',
        'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php',
        'SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php',
        'SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php',
        'SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php',
        'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php',
        'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php',
        'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php',
        'SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php',
        'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php',
        'SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php',
        'SebastianBergmann\\Environment\\Console' => __DIR__ . '/..' . '/sebastian/environment/src/Console.php',
        'SebastianBergmann\\Environment\\OperatingSystem' => __DIR__ . '/..' . '/sebastian/environment/src/OperatingSystem.php',
        'SebastianBergmann\\Environment\\Runtime' => __DIR__ . '/..' . '/sebastian/environment/src/Runtime.php',
        'SebastianBergmann\\Exporter\\Exporter' => __DIR__ . '/..' . '/sebastian/exporter/src/Exporter.php',
        'SebastianBergmann\\FileIterator\\Facade' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Facade.php',
        'SebastianBergmann\\FileIterator\\Factory' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Factory.php',
        'SebastianBergmann\\FileIterator\\Iterator' => __DIR__ . '/..' . '/phpunit/php-file-iterator/src/Iterator.php',
        'SebastianBergmann\\GlobalState\\Blacklist' => __DIR__ . '/..' . '/sebastian/global-state/src/Blacklist.php',
        'SebastianBergmann\\GlobalState\\CodeExporter' => __DIR__ . '/..' . '/sebastian/global-state/src/CodeExporter.php',
        'SebastianBergmann\\GlobalState\\Exception' => __DIR__ . '/..' . '/sebastian/global-state/src/exceptions/Exception.php',
        'SebastianBergmann\\GlobalState\\Restorer' => __DIR__ . '/..' . '/sebastian/global-state/src/Restorer.php',
        'SebastianBergmann\\GlobalState\\RuntimeException' => __DIR__ . '/..' . '/sebastian/global-state/src/exceptions/RuntimeException.php',
        'SebastianBergmann\\GlobalState\\Snapshot' => __DIR__ . '/..' . '/sebastian/global-state/src/Snapshot.php',
        'SebastianBergmann\\ObjectEnumerator\\Enumerator' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/Enumerator.php',
        'SebastianBergmann\\ObjectEnumerator\\Exception' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/Exception.php',
        'SebastianBergmann\\ObjectEnumerator\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/object-enumerator/src/InvalidArgumentException.php',
        'SebastianBergmann\\ObjectReflector\\Exception' => __DIR__ . '/..' . '/sebastian/object-reflector/src/Exception.php',
        'SebastianBergmann\\ObjectReflector\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/object-reflector/src/InvalidArgumentException.php',
        'SebastianBergmann\\ObjectReflector\\ObjectReflector' => __DIR__ . '/..' . '/sebastian/object-reflector/src/ObjectReflector.php',
        'SebastianBergmann\\RecursionContext\\Context' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Context.php',
        'SebastianBergmann\\RecursionContext\\Exception' => __DIR__ . '/..' . '/sebastian/recursion-context/src/Exception.php',
        'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/recursion-context/src/InvalidArgumentException.php',
        'SebastianBergmann\\ResourceOperations\\ResourceOperations' => __DIR__ . '/..' . '/sebastian/resource-operations/src/ResourceOperations.php',
        'SebastianBergmann\\Timer\\Exception' => __DIR__ . '/..' . '/phpunit/php-timer/src/Exception.php',
        'SebastianBergmann\\Timer\\RuntimeException' => __DIR__ . '/..' . '/phpunit/php-timer/src/RuntimeException.php',
        'SebastianBergmann\\Timer\\Timer' => __DIR__ . '/..' . '/phpunit/php-timer/src/Timer.php',
        'SebastianBergmann\\Type\\CallableType' => __DIR__ . '/..' . '/sebastian/type/src/CallableType.php',
        'SebastianBergmann\\Type\\Exception' => __DIR__ . '/..' . '/sebastian/type/src/exception/Exception.php',
        'SebastianBergmann\\Type\\GenericObjectType' => __DIR__ . '/..' . '/sebastian/type/src/GenericObjectType.php',
        'SebastianBergmann\\Type\\IterableType' => __DIR__ . '/..' . '/sebastian/type/src/IterableType.php',
        'SebastianBergmann\\Type\\NullType' => __DIR__ . '/..' . '/sebastian/type/src/NullType.php',
        'SebastianBergmann\\Type\\ObjectType' => __DIR__ . '/..' . '/sebastian/type/src/ObjectType.php',
        'SebastianBergmann\\Type\\RuntimeException' => __DIR__ . '/..' . '/sebastian/type/src/exception/RuntimeException.php',
        'SebastianBergmann\\Type\\SimpleType' => __DIR__ . '/..' . '/sebastian/type/src/SimpleType.php',
        'SebastianBergmann\\Type\\Type' => __DIR__ . '/..' . '/sebastian/type/src/Type.php',
        'SebastianBergmann\\Type\\TypeName' => __DIR__ . '/..' . '/sebastian/type/src/TypeName.php',
        'SebastianBergmann\\Type\\UnknownType' => __DIR__ . '/..' . '/sebastian/type/src/UnknownType.php',
        'SebastianBergmann\\Type\\VoidType' => __DIR__ . '/..' . '/sebastian/type/src/VoidType.php',
        'SebastianBergmann\\Version' => __DIR__ . '/..' . '/sebastian/version/src/Version.php',
        'Text_Template' => __DIR__ . '/..' . '/phpunit/php-text-template/src/Template.php',
        'TheSeer\\Tokenizer\\Exception' => __DIR__ . '/..' . '/theseer/tokenizer/src/Exception.php',
        'TheSeer\\Tokenizer\\NamespaceUri' => __DIR__ . '/..' . '/theseer/tokenizer/src/NamespaceUri.php',
        'TheSeer\\Tokenizer\\NamespaceUriException' => __DIR__ . '/..' . '/theseer/tokenizer/src/NamespaceUriException.php',
        'TheSeer\\Tokenizer\\Token' => __DIR__ . '/..' . '/theseer/tokenizer/src/Token.php',
        'TheSeer\\Tokenizer\\TokenCollection' => __DIR__ . '/..' . '/theseer/tokenizer/src/TokenCollection.php',
        'TheSeer\\Tokenizer\\TokenCollectionException' => __DIR__ . '/..' . '/theseer/tokenizer/src/TokenCollectionException.php',
        'TheSeer\\Tokenizer\\Tokenizer' => __DIR__ . '/..' . '/theseer/tokenizer/src/Tokenizer.php',
        'TheSeer\\Tokenizer\\XMLSerializer' => __DIR__ . '/..' . '/theseer/tokenizer/src/XMLSerializer.php',
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit5d90551c137e56c44ad81de477daaa67::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit5d90551c137e56c44ad81de477daaa67::$prefixDirsPsr4;
            $loader->prefixesPsr0 = ComposerStaticInit5d90551c137e56c44ad81de477daaa67::$prefixesPsr0;
            $loader->classMap = ComposerStaticInit5d90551c137e56c44ad81de477daaa67::$classMap;

        }, null, ClassLoader::class);
    }
}
<?php

// autoload_real.php @generated by Composer

class ComposerAutoloaderInit5d90551c137e56c44ad81de477daaa67
{
    private static $loader;

    public static function loadClassLoader($class)
    {
        if ('Composer\Autoload\ClassLoader' === $class) {
            require __DIR__ . '/ClassLoader.php';
        }
    }

    /**
     * @return \Composer\Autoload\ClassLoader
     */
    public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

        require __DIR__ . '/platform_check.php';

        spl_autoload_register(array('ComposerAutoloaderInit5d90551c137e56c44ad81de477daaa67', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
        spl_autoload_unregister(array('ComposerAutoloaderInit5d90551c137e56c44ad81de477daaa67', 'loadClassLoader'));

        require __DIR__ . '/autoload_static.php';
        call_user_func(\Composer\Autoload\ComposerStaticInit5d90551c137e56c44ad81de477daaa67::getInitializer($loader));

        $loader->register(true);

        $filesToLoad = \Composer\Autoload\ComposerStaticInit5d90551c137e56c44ad81de477daaa67::$files;
        $requireFile = static function ($fileIdentifier, $file) {
            if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
                $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;

                require $file;
            }
        };
        foreach ($filesToLoad as $fileIdentifier => $file) {
            ($requireFile)($fileIdentifier, $file);
        }

        return $loader;
    }
}
{
    "packages": [
        {
            "name": "doctrine/instantiator",
            "version": "1.5.0",
            "version_normalized": "1.5.0.0",
            "source": {
                "type": "git",
                "url": "https://github.com/doctrine/instantiator.git",
                "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/doctrine/instantiator/zipball/0a0fa9780f5d4e507415a065172d26a98d02047b",
                "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b",
                "shasum": ""
            },
            "require": {
                "php": "^7.1 || ^8.0"
            },
            "require-dev": {
                "doctrine/coding-standard": "^9 || ^11",
                "ext-pdo": "*",
                "ext-phar": "*",
                "phpbench/phpbench": "^0.16 || ^1",
                "phpstan/phpstan": "^1.4",
                "phpstan/phpstan-phpunit": "^1",
                "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
                "vimeo/psalm": "^4.30 || ^5.4"
            },
            "time": "2022-12-30T00:15:36+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "psr-4": {
                    "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Marco Pivetta",
                    "email": "ocramius@gmail.com",
                    "homepage": "https://ocramius.github.io/"
                }
            ],
            "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
            "homepage": "https://www.doctrine-project.org/projects/instantiator.html",
            "keywords": [
                "constructor",
                "instantiate"
            ],
            "support": {
                "issues": "https://github.com/doctrine/instantiator/issues",
                "source": "https://github.com/doctrine/instantiator/tree/1.5.0"
            },
            "funding": [
                {
                    "url": "https://www.doctrine-project.org/sponsorship.html",
                    "type": "custom"
                },
                {
                    "url": "https://www.patreon.com/phpdoctrine",
                    "type": "patreon"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finstantiator",
                    "type": "tidelift"
                }
            ],
            "install-path": "../doctrine/instantiator"
        },
        {
            "name": "guzzle/guzzle",
            "version": "v3.9.3",
            "version_normalized": "3.9.3.0",
            "source": {
                "type": "git",
                "url": "https://github.com/guzzle/guzzle3.git",
                "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/0645b70d953bc1c067bbc8d5bc53194706b628d9",
                "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9",
                "shasum": ""
            },
            "require": {
                "ext-curl": "*",
                "php": ">=5.3.3",
                "symfony/event-dispatcher": "~2.1"
            },
            "replace": {
                "guzzle/batch": "self.version",
                "guzzle/cache": "self.version",
                "guzzle/common": "self.version",
                "guzzle/http": "self.version",
                "guzzle/inflection": "self.version",
                "guzzle/iterator": "self.version",
                "guzzle/log": "self.version",
                "guzzle/parser": "self.version",
                "guzzle/plugin": "self.version",
                "guzzle/plugin-async": "self.version",
                "guzzle/plugin-backoff": "self.version",
                "guzzle/plugin-cache": "self.version",
                "guzzle/plugin-cookie": "self.version",
                "guzzle/plugin-curlauth": "self.version",
                "guzzle/plugin-error-response": "self.version",
                "guzzle/plugin-history": "self.version",
                "guzzle/plugin-log": "self.version",
                "guzzle/plugin-md5": "self.version",
                "guzzle/plugin-mock": "self.version",
                "guzzle/plugin-oauth": "self.version",
                "guzzle/service": "self.version",
                "guzzle/stream": "self.version"
            },
            "require-dev": {
                "doctrine/cache": "~1.3",
                "monolog/monolog": "~1.0",
                "phpunit/phpunit": "3.7.*",
                "psr/log": "~1.0",
                "symfony/class-loader": "~2.1",
                "zendframework/zend-cache": "2.*,<2.3",
                "zendframework/zend-log": "2.*,<2.3"
            },
            "suggest": {
                "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated."
            },
            "time": "2015-03-18T18:23:50+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.9-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "psr-0": {
                    "Guzzle": "src/",
                    "Guzzle\\Tests": "tests/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Michael Dowling",
                    "email": "mtdowling@gmail.com",
                    "homepage": "https://github.com/mtdowling"
                },
                {
                    "name": "Guzzle Community",
                    "homepage": "https://github.com/guzzle/guzzle/contributors"
                }
            ],
            "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle",
            "homepage": "http://guzzlephp.org/",
            "keywords": [
                "client",
                "curl",
                "framework",
                "http",
                "http client",
                "rest",
                "web service"
            ],
            "install-path": "../guzzle/guzzle"
        },
        {
            "name": "monolog/monolog",
            "version": "1.27.1",
            "version_normalized": "1.27.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/Seldaek/monolog.git",
                "reference": "904713c5929655dc9b97288b69cfeedad610c9a1"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/Seldaek/monolog/zipball/904713c5929655dc9b97288b69cfeedad610c9a1",
                "reference": "904713c5929655dc9b97288b69cfeedad610c9a1",
                "shasum": ""
            },
            "require": {
                "php": ">=5.3.0",
                "psr/log": "~1.0"
            },
            "provide": {
                "psr/log-implementation": "1.0.0"
            },
            "require-dev": {
                "aws/aws-sdk-php": "^2.4.9 || ^3.0",
                "doctrine/couchdb": "~1.0@dev",
                "graylog2/gelf-php": "~1.0",
                "php-amqplib/php-amqplib": "~2.4",
                "php-console/php-console": "^3.1.3",
                "phpstan/phpstan": "^0.12.59",
                "phpunit/phpunit": "~4.5",
                "ruflin/elastica": ">=0.90 <3.0",
                "sentry/sentry": "^0.13",
                "swiftmailer/swiftmailer": "^5.3|^6.0"
            },
            "suggest": {
                "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
                "doctrine/couchdb": "Allow sending log messages to a CouchDB server",
                "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
                "ext-mongo": "Allow sending log messages to a MongoDB server",
                "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
                "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver",
                "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
                "php-console/php-console": "Allow sending log messages to Google Chrome",
                "rollbar/rollbar": "Allow sending log messages to Rollbar",
                "ruflin/elastica": "Allow sending log messages to an Elastic Search server",
                "sentry/sentry": "Allow sending log messages to a Sentry server"
            },
            "time": "2022-06-09T08:53:42+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "psr-4": {
                    "Monolog\\": "src/Monolog"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Jordi Boggiano",
                    "email": "j.boggiano@seld.be",
                    "homepage": "http://seld.be"
                }
            ],
            "description": "Sends your logs to files, sockets, inboxes, databases and various web services",
            "homepage": "http://github.com/Seldaek/monolog",
            "keywords": [
                "log",
                "logging",
                "psr-3"
            ],
            "support": {
                "issues": "https://github.com/Seldaek/monolog/issues",
                "source": "https://github.com/Seldaek/monolog/tree/1.27.1"
            },
            "funding": [
                {
                    "url": "https://github.com/Seldaek",
                    "type": "github"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/monolog/monolog",
                    "type": "tidelift"
                }
            ],
            "install-path": "../monolog/monolog"
        },
        {
            "name": "myclabs/deep-copy",
            "version": "1.11.0",
            "version_normalized": "1.11.0.0",
            "source": {
                "type": "git",
                "url": "https://github.com/myclabs/DeepCopy.git",
                "reference": "14daed4296fae74d9e3201d2c4925d1acb7aa614"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/14daed4296fae74d9e3201d2c4925d1acb7aa614",
                "reference": "14daed4296fae74d9e3201d2c4925d1acb7aa614",
                "shasum": ""
            },
            "require": {
                "php": "^7.1 || ^8.0"
            },
            "conflict": {
                "doctrine/collections": "<1.6.8",
                "doctrine/common": "<2.13.3 || >=3,<3.2.2"
            },
            "require-dev": {
                "doctrine/collections": "^1.6.8",
                "doctrine/common": "^2.13.3 || ^3.2.2",
                "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
            },
            "time": "2022-03-03T13:19:32+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "files": [
                    "src/DeepCopy/deep_copy.php"
                ],
                "psr-4": {
                    "DeepCopy\\": "src/DeepCopy/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "description": "Create deep copies (clones) of your objects",
            "keywords": [
                "clone",
                "copy",
                "duplicate",
                "object",
                "object graph"
            ],
            "support": {
                "issues": "https://github.com/myclabs/DeepCopy/issues",
                "source": "https://github.com/myclabs/DeepCopy/tree/1.11.0"
            },
            "funding": [
                {
                    "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",
                    "type": "tidelift"
                }
            ],
            "install-path": "../myclabs/deep-copy"
        },
        {
            "name": "phar-io/manifest",
            "version": "2.0.3",
            "version_normalized": "2.0.3.0",
            "source": {
                "type": "git",
                "url": "https://github.com/phar-io/manifest.git",
                "reference": "97803eca37d319dfa7826cc2437fc020857acb53"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/phar-io/manifest/zipball/97803eca37d319dfa7826cc2437fc020857acb53",
                "reference": "97803eca37d319dfa7826cc2437fc020857acb53",
                "shasum": ""
            },
            "require": {
                "ext-dom": "*",
                "ext-phar": "*",
                "ext-xmlwriter": "*",
                "phar-io/version": "^3.0.1",
                "php": "^7.2 || ^8.0"
            },
            "time": "2021-07-20T11:28:43+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Arne Blankerts",
                    "email": "arne@blankerts.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Heuer",
                    "email": "sebastian@phpeople.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "Developer"
                }
            ],
            "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
            "support": {
                "issues": "https://github.com/phar-io/manifest/issues",
                "source": "https://github.com/phar-io/manifest/tree/2.0.3"
            },
            "install-path": "../phar-io/manifest"
        },
        {
            "name": "phar-io/version",
            "version": "3.2.1",
            "version_normalized": "3.2.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/phar-io/version.git",
                "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74",
                "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74",
                "shasum": ""
            },
            "require": {
                "php": "^7.2 || ^8.0"
            },
            "time": "2022-02-21T01:04:05+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Arne Blankerts",
                    "email": "arne@blankerts.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Heuer",
                    "email": "sebastian@phpeople.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "Developer"
                }
            ],
            "description": "Library for handling version information and constraints",
            "support": {
                "issues": "https://github.com/phar-io/version/issues",
                "source": "https://github.com/phar-io/version/tree/3.2.1"
            },
            "install-path": "../phar-io/version"
        },
        {
            "name": "phpunit/php-code-coverage",
            "version": "7.0.15",
            "version_normalized": "7.0.15.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/php-code-coverage.git",
                "reference": "819f92bba8b001d4363065928088de22f25a3a48"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/819f92bba8b001d4363065928088de22f25a3a48",
                "reference": "819f92bba8b001d4363065928088de22f25a3a48",
                "shasum": ""
            },
            "require": {
                "ext-dom": "*",
                "ext-xmlwriter": "*",
                "php": ">=7.2",
                "phpunit/php-file-iterator": "^2.0.2",
                "phpunit/php-text-template": "^1.2.1",
                "phpunit/php-token-stream": "^3.1.3 || ^4.0",
                "sebastian/code-unit-reverse-lookup": "^1.0.1",
                "sebastian/environment": "^4.2.2",
                "sebastian/version": "^2.0.1",
                "theseer/tokenizer": "^1.1.3"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.2.2"
            },
            "suggest": {
                "ext-xdebug": "^2.7.2"
            },
            "time": "2021-07-26T12:20:09+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "7.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
            "homepage": "https://github.com/sebastianbergmann/php-code-coverage",
            "keywords": [
                "coverage",
                "testing",
                "xunit"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
                "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/7.0.15"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../phpunit/php-code-coverage"
        },
        {
            "name": "phpunit/php-file-iterator",
            "version": "2.0.5",
            "version_normalized": "2.0.5.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/php-file-iterator.git",
                "reference": "42c5ba5220e6904cbfe8b1a1bda7c0cfdc8c12f5"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/42c5ba5220e6904cbfe8b1a1bda7c0cfdc8c12f5",
                "reference": "42c5ba5220e6904cbfe8b1a1bda7c0cfdc8c12f5",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.5"
            },
            "time": "2021-12-02T12:42:26+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "FilterIterator implementation that filters files based on a list of suffixes.",
            "homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
            "keywords": [
                "filesystem",
                "iterator"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",
                "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/2.0.5"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../phpunit/php-file-iterator"
        },
        {
            "name": "phpunit/php-text-template",
            "version": "1.2.1",
            "version_normalized": "1.2.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/php-text-template.git",
                "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
                "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686",
                "shasum": ""
            },
            "require": {
                "php": ">=5.3.3"
            },
            "time": "2015-06-21T13:50:34+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "Simple template engine.",
            "homepage": "https://github.com/sebastianbergmann/php-text-template/",
            "keywords": [
                "template"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/php-text-template/issues",
                "source": "https://github.com/sebastianbergmann/php-text-template/tree/1.2.1"
            },
            "install-path": "../phpunit/php-text-template"
        },
        {
            "name": "phpunit/php-timer",
            "version": "2.1.3",
            "version_normalized": "2.1.3.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/php-timer.git",
                "reference": "2454ae1765516d20c4ffe103d85a58a9a3bd5662"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/2454ae1765516d20c4ffe103d85a58a9a3bd5662",
                "reference": "2454ae1765516d20c4ffe103d85a58a9a3bd5662",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.5"
            },
            "time": "2020-11-30T08:20:02+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.1-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "Utility class for timing",
            "homepage": "https://github.com/sebastianbergmann/php-timer/",
            "keywords": [
                "timer"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/php-timer/issues",
                "source": "https://github.com/sebastianbergmann/php-timer/tree/2.1.3"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../phpunit/php-timer"
        },
        {
            "name": "phpunit/php-token-stream",
            "version": "4.0.4",
            "version_normalized": "4.0.4.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/php-token-stream.git",
                "reference": "a853a0e183b9db7eed023d7933a858fa1c8d25a3"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/a853a0e183b9db7eed023d7933a858fa1c8d25a3",
                "reference": "a853a0e183b9db7eed023d7933a858fa1c8d25a3",
                "shasum": ""
            },
            "require": {
                "ext-tokenizer": "*",
                "php": "^7.3 || ^8.0"
            },
            "require-dev": {
                "phpunit/phpunit": "^9.0"
            },
            "time": "2020-08-04T08:28:15+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "4.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Wrapper around PHP's tokenizer extension.",
            "homepage": "https://github.com/sebastianbergmann/php-token-stream/",
            "keywords": [
                "tokenizer"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/php-token-stream/issues",
                "source": "https://github.com/sebastianbergmann/php-token-stream/tree/master"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "abandoned": true,
            "install-path": "../phpunit/php-token-stream"
        },
        {
            "name": "phpunit/phpunit",
            "version": "8.5.32",
            "version_normalized": "8.5.32.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/phpunit.git",
                "reference": "375686930d05c9fd7d20f6e5fc38121e8d7a9d55"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/375686930d05c9fd7d20f6e5fc38121e8d7a9d55",
                "reference": "375686930d05c9fd7d20f6e5fc38121e8d7a9d55",
                "shasum": ""
            },
            "require": {
                "doctrine/instantiator": "^1.3.1",
                "ext-dom": "*",
                "ext-json": "*",
                "ext-libxml": "*",
                "ext-mbstring": "*",
                "ext-xml": "*",
                "ext-xmlwriter": "*",
                "myclabs/deep-copy": "^1.10.0",
                "phar-io/manifest": "^2.0.3",
                "phar-io/version": "^3.0.2",
                "php": ">=7.2",
                "phpunit/php-code-coverage": "^7.0.12",
                "phpunit/php-file-iterator": "^2.0.4",
                "phpunit/php-text-template": "^1.2.1",
                "phpunit/php-timer": "^2.1.2",
                "sebastian/comparator": "^3.0.5",
                "sebastian/diff": "^3.0.2",
                "sebastian/environment": "^4.2.3",
                "sebastian/exporter": "^3.1.5",
                "sebastian/global-state": "^3.0.0",
                "sebastian/object-enumerator": "^3.0.3",
                "sebastian/resource-operations": "^2.0.1",
                "sebastian/type": "^1.1.3",
                "sebastian/version": "^2.0.1"
            },
            "suggest": {
                "ext-soap": "*",
                "ext-xdebug": "*",
                "phpunit/php-invoker": "^2.0.0"
            },
            "time": "2023-01-26T08:30:25+00:00",
            "bin": [
                "phpunit"
            ],
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "8.5-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "The PHP Unit Testing framework.",
            "homepage": "https://phpunit.de/",
            "keywords": [
                "phpunit",
                "testing",
                "xunit"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/phpunit/issues",
                "source": "https://github.com/sebastianbergmann/phpunit/tree/8.5.32"
            },
            "funding": [
                {
                    "url": "https://phpunit.de/sponsors.html",
                    "type": "custom"
                },
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                },
                {
                    "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit",
                    "type": "tidelift"
                }
            ],
            "install-path": "../phpunit/phpunit"
        },
        {
            "name": "psr/log",
            "version": "1.1.4",
            "version_normalized": "1.1.4.0",
            "source": {
                "type": "git",
                "url": "https://github.com/php-fig/log.git",
                "reference": "d49695b909c3b7628b6289db5479a1c204601f11"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11",
                "reference": "d49695b909c3b7628b6289db5479a1c204601f11",
                "shasum": ""
            },
            "require": {
                "php": ">=5.3.0"
            },
            "time": "2021-05-03T11:20:27+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "1.1.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "psr-4": {
                    "Psr\\Log\\": "Psr/Log/"
                }
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "PHP-FIG",
                    "homepage": "https://www.php-fig.org/"
                }
            ],
            "description": "Common interface for logging libraries",
            "homepage": "https://github.com/php-fig/log",
            "keywords": [
                "log",
                "psr",
                "psr-3"
            ],
            "support": {
                "source": "https://github.com/php-fig/log/tree/1.1.4"
            },
            "install-path": "../psr/log"
        },
        {
            "name": "sebastian/code-unit-reverse-lookup",
            "version": "1.0.2",
            "version_normalized": "1.0.2.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",
                "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/1de8cd5c010cb153fcd68b8d0f64606f523f7619",
                "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619",
                "shasum": ""
            },
            "require": {
                "php": ">=5.6"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.5"
            },
            "time": "2020-11-30T08:15:22+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "1.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Looks up which function or method a line of code belongs to",
            "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
            "support": {
                "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",
                "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/1.0.2"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/code-unit-reverse-lookup"
        },
        {
            "name": "sebastian/comparator",
            "version": "3.0.5",
            "version_normalized": "3.0.5.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/comparator.git",
                "reference": "1dc7ceb4a24aede938c7af2a9ed1de09609ca770"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/1dc7ceb4a24aede938c7af2a9ed1de09609ca770",
                "reference": "1dc7ceb4a24aede938c7af2a9ed1de09609ca770",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1",
                "sebastian/diff": "^3.0",
                "sebastian/exporter": "^3.1"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.5"
            },
            "time": "2022-09-14T12:31:48+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                },
                {
                    "name": "Jeff Welch",
                    "email": "whatthejeff@gmail.com"
                },
                {
                    "name": "Volker Dusch",
                    "email": "github@wallbash.com"
                },
                {
                    "name": "Bernhard Schussek",
                    "email": "bschussek@2bepublished.at"
                }
            ],
            "description": "Provides the functionality to compare PHP values for equality",
            "homepage": "https://github.com/sebastianbergmann/comparator",
            "keywords": [
                "comparator",
                "compare",
                "equality"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/comparator/issues",
                "source": "https://github.com/sebastianbergmann/comparator/tree/3.0.5"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/comparator"
        },
        {
            "name": "sebastian/diff",
            "version": "3.0.3",
            "version_normalized": "3.0.3.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/diff.git",
                "reference": "14f72dd46eaf2f2293cbe79c93cc0bc43161a211"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/14f72dd46eaf2f2293cbe79c93cc0bc43161a211",
                "reference": "14f72dd46eaf2f2293cbe79c93cc0bc43161a211",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1"
            },
            "require-dev": {
                "phpunit/phpunit": "^7.5 || ^8.0",
                "symfony/process": "^2 || ^3.3 || ^4"
            },
            "time": "2020-11-30T07:59:04+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                },
                {
                    "name": "Kore Nordmann",
                    "email": "mail@kore-nordmann.de"
                }
            ],
            "description": "Diff implementation",
            "homepage": "https://github.com/sebastianbergmann/diff",
            "keywords": [
                "diff",
                "udiff",
                "unidiff",
                "unified diff"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/diff/issues",
                "source": "https://github.com/sebastianbergmann/diff/tree/3.0.3"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/diff"
        },
        {
            "name": "sebastian/environment",
            "version": "4.2.4",
            "version_normalized": "4.2.4.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/environment.git",
                "reference": "d47bbbad83711771f167c72d4e3f25f7fcc1f8b0"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/d47bbbad83711771f167c72d4e3f25f7fcc1f8b0",
                "reference": "d47bbbad83711771f167c72d4e3f25f7fcc1f8b0",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1"
            },
            "require-dev": {
                "phpunit/phpunit": "^7.5"
            },
            "suggest": {
                "ext-posix": "*"
            },
            "time": "2020-11-30T07:53:42+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "4.2-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Provides functionality to handle HHVM/PHP environments",
            "homepage": "http://www.github.com/sebastianbergmann/environment",
            "keywords": [
                "Xdebug",
                "environment",
                "hhvm"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/environment/issues",
                "source": "https://github.com/sebastianbergmann/environment/tree/4.2.4"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/environment"
        },
        {
            "name": "sebastian/exporter",
            "version": "3.1.5",
            "version_normalized": "3.1.5.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/exporter.git",
                "reference": "73a9676f2833b9a7c36968f9d882589cd75511e6"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/73a9676f2833b9a7c36968f9d882589cd75511e6",
                "reference": "73a9676f2833b9a7c36968f9d882589cd75511e6",
                "shasum": ""
            },
            "require": {
                "php": ">=7.0",
                "sebastian/recursion-context": "^3.0"
            },
            "require-dev": {
                "ext-mbstring": "*",
                "phpunit/phpunit": "^8.5"
            },
            "time": "2022-09-14T06:00:17+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.1.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                },
                {
                    "name": "Jeff Welch",
                    "email": "whatthejeff@gmail.com"
                },
                {
                    "name": "Volker Dusch",
                    "email": "github@wallbash.com"
                },
                {
                    "name": "Adam Harvey",
                    "email": "aharvey@php.net"
                },
                {
                    "name": "Bernhard Schussek",
                    "email": "bschussek@gmail.com"
                }
            ],
            "description": "Provides the functionality to export PHP variables for visualization",
            "homepage": "http://www.github.com/sebastianbergmann/exporter",
            "keywords": [
                "export",
                "exporter"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/exporter/issues",
                "source": "https://github.com/sebastianbergmann/exporter/tree/3.1.5"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/exporter"
        },
        {
            "name": "sebastian/global-state",
            "version": "3.0.2",
            "version_normalized": "3.0.2.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/global-state.git",
                "reference": "de036ec91d55d2a9e0db2ba975b512cdb1c23921"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/de036ec91d55d2a9e0db2ba975b512cdb1c23921",
                "reference": "de036ec91d55d2a9e0db2ba975b512cdb1c23921",
                "shasum": ""
            },
            "require": {
                "php": ">=7.2",
                "sebastian/object-reflector": "^1.1.1",
                "sebastian/recursion-context": "^3.0"
            },
            "require-dev": {
                "ext-dom": "*",
                "phpunit/phpunit": "^8.0"
            },
            "suggest": {
                "ext-uopz": "*"
            },
            "time": "2022-02-10T06:55:38+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Snapshotting of global state",
            "homepage": "http://www.github.com/sebastianbergmann/global-state",
            "keywords": [
                "global state"
            ],
            "support": {
                "issues": "https://github.com/sebastianbergmann/global-state/issues",
                "source": "https://github.com/sebastianbergmann/global-state/tree/3.0.2"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/global-state"
        },
        {
            "name": "sebastian/object-enumerator",
            "version": "3.0.4",
            "version_normalized": "3.0.4.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/object-enumerator.git",
                "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2",
                "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2",
                "shasum": ""
            },
            "require": {
                "php": ">=7.0",
                "sebastian/object-reflector": "^1.1.1",
                "sebastian/recursion-context": "^3.0"
            },
            "require-dev": {
                "phpunit/phpunit": "^6.0"
            },
            "time": "2020-11-30T07:40:27+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Traverses array structures and object graphs to enumerate all referenced objects",
            "homepage": "https://github.com/sebastianbergmann/object-enumerator/",
            "support": {
                "issues": "https://github.com/sebastianbergmann/object-enumerator/issues",
                "source": "https://github.com/sebastianbergmann/object-enumerator/tree/3.0.4"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/object-enumerator"
        },
        {
            "name": "sebastian/object-reflector",
            "version": "1.1.2",
            "version_normalized": "1.1.2.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/object-reflector.git",
                "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/9b8772b9cbd456ab45d4a598d2dd1a1bced6363d",
                "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d",
                "shasum": ""
            },
            "require": {
                "php": ">=7.0"
            },
            "require-dev": {
                "phpunit/phpunit": "^6.0"
            },
            "time": "2020-11-30T07:37:18+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "1.1-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Allows reflection of object attributes, including inherited and non-public ones",
            "homepage": "https://github.com/sebastianbergmann/object-reflector/",
            "support": {
                "issues": "https://github.com/sebastianbergmann/object-reflector/issues",
                "source": "https://github.com/sebastianbergmann/object-reflector/tree/1.1.2"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/object-reflector"
        },
        {
            "name": "sebastian/recursion-context",
            "version": "3.0.1",
            "version_normalized": "3.0.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/recursion-context.git",
                "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/367dcba38d6e1977be014dc4b22f47a484dac7fb",
                "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb",
                "shasum": ""
            },
            "require": {
                "php": ">=7.0"
            },
            "require-dev": {
                "phpunit/phpunit": "^6.0"
            },
            "time": "2020-11-30T07:34:24+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "3.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                },
                {
                    "name": "Jeff Welch",
                    "email": "whatthejeff@gmail.com"
                },
                {
                    "name": "Adam Harvey",
                    "email": "aharvey@php.net"
                }
            ],
            "description": "Provides functionality to recursively process PHP variables",
            "homepage": "http://www.github.com/sebastianbergmann/recursion-context",
            "support": {
                "issues": "https://github.com/sebastianbergmann/recursion-context/issues",
                "source": "https://github.com/sebastianbergmann/recursion-context/tree/3.0.1"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/recursion-context"
        },
        {
            "name": "sebastian/resource-operations",
            "version": "2.0.2",
            "version_normalized": "2.0.2.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/resource-operations.git",
                "reference": "31d35ca87926450c44eae7e2611d45a7a65ea8b3"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/31d35ca87926450c44eae7e2611d45a7a65ea8b3",
                "reference": "31d35ca87926450c44eae7e2611d45a7a65ea8b3",
                "shasum": ""
            },
            "require": {
                "php": ">=7.1"
            },
            "time": "2020-11-30T07:30:19+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.0-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de"
                }
            ],
            "description": "Provides a list of PHP built-in functions that operate on resources",
            "homepage": "https://www.github.com/sebastianbergmann/resource-operations",
            "support": {
                "issues": "https://github.com/sebastianbergmann/resource-operations/issues",
                "source": "https://github.com/sebastianbergmann/resource-operations/tree/2.0.2"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/resource-operations"
        },
        {
            "name": "sebastian/type",
            "version": "1.1.4",
            "version_normalized": "1.1.4.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/type.git",
                "reference": "0150cfbc4495ed2df3872fb31b26781e4e077eb4"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/0150cfbc4495ed2df3872fb31b26781e4e077eb4",
                "reference": "0150cfbc4495ed2df3872fb31b26781e4e077eb4",
                "shasum": ""
            },
            "require": {
                "php": ">=7.2"
            },
            "require-dev": {
                "phpunit/phpunit": "^8.2"
            },
            "time": "2020-11-30T07:25:11+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "1.1-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "Collection of value objects that represent the types of the PHP type system",
            "homepage": "https://github.com/sebastianbergmann/type",
            "support": {
                "issues": "https://github.com/sebastianbergmann/type/issues",
                "source": "https://github.com/sebastianbergmann/type/tree/1.1.4"
            },
            "funding": [
                {
                    "url": "https://github.com/sebastianbergmann",
                    "type": "github"
                }
            ],
            "install-path": "../sebastian/type"
        },
        {
            "name": "sebastian/version",
            "version": "2.0.1",
            "version_normalized": "2.0.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/sebastianbergmann/version.git",
                "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/99732be0ddb3361e16ad77b68ba41efc8e979019",
                "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019",
                "shasum": ""
            },
            "require": {
                "php": ">=5.6"
            },
            "time": "2016-10-03T07:35:21+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.0.x-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "lead"
                }
            ],
            "description": "Library that helps with managing the version number of Git-hosted PHP projects",
            "homepage": "https://github.com/sebastianbergmann/version",
            "support": {
                "issues": "https://github.com/sebastianbergmann/version/issues",
                "source": "https://github.com/sebastianbergmann/version/tree/master"
            },
            "install-path": "../sebastian/version"
        },
        {
            "name": "symfony/event-dispatcher",
            "version": "v2.8.52",
            "version_normalized": "2.8.52.0",
            "source": {
                "type": "git",
                "url": "https://github.com/symfony/event-dispatcher.git",
                "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/a77e974a5fecb4398833b0709210e3d5e334ffb0",
                "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0",
                "shasum": ""
            },
            "require": {
                "php": ">=5.3.9"
            },
            "require-dev": {
                "psr/log": "~1.0",
                "symfony/config": "^2.0.5|~3.0.0",
                "symfony/dependency-injection": "~2.6|~3.0.0",
                "symfony/expression-language": "~2.6|~3.0.0",
                "symfony/stopwatch": "~2.3|~3.0.0"
            },
            "suggest": {
                "symfony/dependency-injection": "",
                "symfony/http-kernel": ""
            },
            "time": "2018-11-21T14:20:20+00:00",
            "type": "library",
            "extra": {
                "branch-alias": {
                    "dev-master": "2.8-dev"
                }
            },
            "installation-source": "dist",
            "autoload": {
                "psr-4": {
                    "Symfony\\Component\\EventDispatcher\\": ""
                },
                "exclude-from-classmap": [
                    "/Tests/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "MIT"
            ],
            "authors": [
                {
                    "name": "Fabien Potencier",
                    "email": "fabien@symfony.com"
                },
                {
                    "name": "Symfony Community",
                    "homepage": "https://symfony.com/contributors"
                }
            ],
            "description": "Symfony EventDispatcher Component",
            "homepage": "https://symfony.com",
            "support": {
                "source": "https://github.com/symfony/event-dispatcher/tree/v2.8.50"
            },
            "install-path": "../symfony/event-dispatcher"
        },
        {
            "name": "theseer/tokenizer",
            "version": "1.2.1",
            "version_normalized": "1.2.1.0",
            "source": {
                "type": "git",
                "url": "https://github.com/theseer/tokenizer.git",
                "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/theseer/tokenizer/zipball/34a41e998c2183e22995f158c581e7b5e755ab9e",
                "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e",
                "shasum": ""
            },
            "require": {
                "ext-dom": "*",
                "ext-tokenizer": "*",
                "ext-xmlwriter": "*",
                "php": "^7.2 || ^8.0"
            },
            "time": "2021-07-28T10:34:58+00:00",
            "type": "library",
            "installation-source": "dist",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Arne Blankerts",
                    "email": "arne@blankerts.de",
                    "role": "Developer"
                }
            ],
            "description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
            "support": {
                "issues": "https://github.com/theseer/tokenizer/issues",
                "source": "https://github.com/theseer/tokenizer/tree/1.2.1"
            },
            "funding": [
                {
                    "url": "https://github.com/theseer",
                    "type": "github"
                }
            ],
            "install-path": "../theseer/tokenizer"
        }
    ],
    "dev": true,
    "dev-package-names": [
        "monolog/monolog"
    ]
}
<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    '6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
);
<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer;

use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;

/**
 * This class is copied in every Composer installed project and available to all
 *
 * See also https://getcomposer.org/doc/07-runtime.md#installed-versions
 *
 * To require its presence, you can require `composer-runtime-api ^2.0`
 *
 * @final
 */
class InstalledVersions
{
    /**
     * @var mixed[]|null
     * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
     */
    private static $installed;

    /**
     * @var bool|null
     */
    private static $canGetVendors;

    /**
     * @var array[]
     * @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
     */
    private static $installedByVendor = array();

    /**
     * Returns a list of all package names which are present, either by being installed, replaced or provided
     *
     * @return string[]
     * @psalm-return list<string>
     */
    public static function getInstalledPackages()
    {
        $packages = array();
        foreach (self::getInstalled() as $installed) {
            $packages[] = array_keys($installed['versions']);
        }

        if (1 === \count($packages)) {
            return $packages[0];
        }

        return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
    }

    /**
     * Returns a list of all package names with a specific type e.g. 'library'
     *
     * @param  string   $type
     * @return string[]
     * @psalm-return list<string>
     */
    public static function getInstalledPackagesByType($type)
    {
        $packagesByType = array();

        foreach (self::getInstalled() as $installed) {
            foreach ($installed['versions'] as $name => $package) {
                if (isset($package['type']) && $package['type'] === $type) {
                    $packagesByType[] = $name;
                }
            }
        }

        return $packagesByType;
    }

    /**
     * Checks whether the given package is installed
     *
     * This also returns true if the package name is provided or replaced by another package
     *
     * @param  string $packageName
     * @param  bool   $includeDevRequirements
     * @return bool
     */
    public static function isInstalled($packageName, $includeDevRequirements = true)
    {
        foreach (self::getInstalled() as $installed) {
            if (isset($installed['versions'][$packageName])) {
                return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
            }
        }

        return false;
    }

    /**
     * Checks whether the given package satisfies a version constraint
     *
     * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
     *
     *   Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
     *
     * @param  VersionParser $parser      Install composer/semver to have access to this class and functionality
     * @param  string        $packageName
     * @param  string|null   $constraint  A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
     * @return bool
     */
    public static function satisfies(VersionParser $parser, $packageName, $constraint)
    {
        $constraint = $parser->parseConstraints($constraint);
        $provided = $parser->parseConstraints(self::getVersionRanges($packageName));

        return $provided->matches($constraint);
    }

    /**
     * Returns a version constraint representing all the range(s) which are installed for a given package
     *
     * It is easier to use this via isInstalled() with the $constraint argument if you need to check
     * whether a given version of a package is installed, and not just whether it exists
     *
     * @param  string $packageName
     * @return string Version constraint usable with composer/semver
     */
    public static function getVersionRanges($packageName)
    {
        foreach (self::getInstalled() as $installed) {
            if (!isset($installed['versions'][$packageName])) {
                continue;
            }

            $ranges = array();
            if (isset($installed['versions'][$packageName]['pretty_version'])) {
                $ranges[] = $installed['versions'][$packageName]['pretty_version'];
            }
            if (array_key_exists('aliases', $installed['versions'][$packageName])) {
                $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
            }
            if (array_key_exists('replaced', $installed['versions'][$packageName])) {
                $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
            }
            if (array_key_exists('provided', $installed['versions'][$packageName])) {
                $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
            }

            return implode(' || ', $ranges);
        }

        throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
    }

    /**
     * @param  string      $packageName
     * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
     */
    public static function getVersion($packageName)
    {
        foreach (self::getInstalled() as $installed) {
            if (!isset($installed['versions'][$packageName])) {
                continue;
            }

            if (!isset($installed['versions'][$packageName]['version'])) {
                return null;
            }

            return $installed['versions'][$packageName]['version'];
        }

        throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
    }

    /**
     * @param  string      $packageName
     * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
     */
    public static function getPrettyVersion($packageName)
    {
        foreach (self::getInstalled() as $installed) {
            if (!isset($installed['versions'][$packageName])) {
                continue;
            }

            if (!isset($installed['versions'][$packageName]['pretty_version'])) {
                return null;
            }

            return $installed['versions'][$packageName]['pretty_version'];
        }

        throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
    }

    /**
     * @param  string      $packageName
     * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
     */
    public static function getReference($packageName)
    {
        foreach (self::getInstalled() as $installed) {
            if (!isset($installed['versions'][$packageName])) {
                continue;
            }

            if (!isset($installed['versions'][$packageName]['reference'])) {
                return null;
            }

            return $installed['versions'][$packageName]['reference'];
        }

        throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
    }

    /**
     * @param  string      $packageName
     * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
     */
    public static function getInstallPath($packageName)
    {
        foreach (self::getInstalled() as $installed) {
            if (!isset($installed['versions'][$packageName])) {
                continue;
            }

            return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
        }

        throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
    }

    /**
     * @return array
     * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
     */
    public static function getRootPackage()
    {
        $installed = self::getInstalled();

        return $installed[0]['root'];
    }

    /**
     * Returns the raw installed.php data for custom implementations
     *
     * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
     * @return array[]
     * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
     */
    public static function getRawData()
    {
        @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);

        if (null === self::$installed) {
            // only require the installed.php file if this file is loaded from its dumped location,
            // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
            if (substr(__DIR__, -8, 1) !== 'C') {
                self::$installed = include __DIR__ . '/installed.php';
            } else {
                self::$installed = array();
            }
        }

        return self::$installed;
    }

    /**
     * Returns the raw data of all installed.php which are currently loaded for custom implementations
     *
     * @return array[]
     * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
     */
    public static function getAllRawData()
    {
        return self::getInstalled();
    }

    /**
     * Lets you reload the static array from another file
     *
     * This is only useful for complex integrations in which a project needs to use
     * this class but then also needs to execute another project's autoloader in process,
     * and wants to ensure both projects have access to their version of installed.php.
     *
     * A typical case would be PHPUnit, where it would need to make sure it reads all
     * the data it needs from this class, then call reload() with
     * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
     * the project in which it runs can then also use this class safely, without
     * interference between PHPUnit's dependencies and the project's dependencies.
     *
     * @param  array[] $data A vendor/composer/installed.php data set
     * @return void
     *
     * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
     */
    public static function reload($data)
    {
        self::$installed = $data;
        self::$installedByVendor = array();
    }

    /**
     * @return array[]
     * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
     */
    private static function getInstalled()
    {
        if (null === self::$canGetVendors) {
            self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
        }

        $installed = array();

        if (self::$canGetVendors) {
            foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
                if (isset(self::$installedByVendor[$vendorDir])) {
                    $installed[] = self::$installedByVendor[$vendorDir];
                } elseif (is_file($vendorDir.'/composer/installed.php')) {
                    $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
                    if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
                        self::$installed = $installed[count($installed) - 1];
                    }
                }
            }
        }

        if (null === self::$installed) {
            // only require the installed.php file if this file is loaded from its dumped location,
            // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
            if (substr(__DIR__, -8, 1) !== 'C') {
                self::$installed = require __DIR__ . '/installed.php';
            } else {
                self::$installed = array();
            }
        }
        $installed[] = self::$installed;

        return $installed;
    }
}
<?php return array(
    'root' => array(
        'name' => 'baidubce/bce-sdk-php',
        'pretty_version' => 'dev-master',
        'version' => 'dev-master',
        'reference' => 'f4073a5419dc17455ce55b4b2e3e70ecbcef22b0',
        'type' => 'library',
        'install_path' => __DIR__ . '/../../',
        'aliases' => array(
            0 => '0.8.25.x-dev',
        ),
        'dev' => true,
    ),
    'versions' => array(
        'baidubce/bce-sdk-php' => array(
            'pretty_version' => 'dev-master',
            'version' => 'dev-master',
            'reference' => 'f4073a5419dc17455ce55b4b2e3e70ecbcef22b0',
            'type' => 'library',
            'install_path' => __DIR__ . '/../../',
            'aliases' => array(
                0 => '0.8.25.x-dev',
            ),
            'dev_requirement' => false,
        ),
        'doctrine/instantiator' => array(
            'pretty_version' => '1.5.0',
            'version' => '1.5.0.0',
            'reference' => '0a0fa9780f5d4e507415a065172d26a98d02047b',
            'type' => 'library',
            'install_path' => __DIR__ . '/../doctrine/instantiator',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'guzzle/batch' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/cache' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/common' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/guzzle' => array(
            'pretty_version' => 'v3.9.3',
            'version' => '3.9.3.0',
            'reference' => '0645b70d953bc1c067bbc8d5bc53194706b628d9',
            'type' => 'library',
            'install_path' => __DIR__ . '/../guzzle/guzzle',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'guzzle/http' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/inflection' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/iterator' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/log' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/parser' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-async' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-backoff' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-cache' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-cookie' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-curlauth' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-error-response' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-history' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-log' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-md5' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-mock' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/plugin-oauth' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/service' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'guzzle/stream' => array(
            'dev_requirement' => false,
            'replaced' => array(
                0 => 'v3.9.3',
            ),
        ),
        'monolog/monolog' => array(
            'pretty_version' => '1.27.1',
            'version' => '1.27.1.0',
            'reference' => '904713c5929655dc9b97288b69cfeedad610c9a1',
            'type' => 'library',
            'install_path' => __DIR__ . '/../monolog/monolog',
            'aliases' => array(),
            'dev_requirement' => true,
        ),
        'myclabs/deep-copy' => array(
            'pretty_version' => '1.11.0',
            'version' => '1.11.0.0',
            'reference' => '14daed4296fae74d9e3201d2c4925d1acb7aa614',
            'type' => 'library',
            'install_path' => __DIR__ . '/../myclabs/deep-copy',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phar-io/manifest' => array(
            'pretty_version' => '2.0.3',
            'version' => '2.0.3.0',
            'reference' => '97803eca37d319dfa7826cc2437fc020857acb53',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phar-io/manifest',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phar-io/version' => array(
            'pretty_version' => '3.2.1',
            'version' => '3.2.1.0',
            'reference' => '4f7fd7836c6f332bb2933569e566a0d6c4cbed74',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phar-io/version',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/php-code-coverage' => array(
            'pretty_version' => '7.0.15',
            'version' => '7.0.15.0',
            'reference' => '819f92bba8b001d4363065928088de22f25a3a48',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/php-code-coverage',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/php-file-iterator' => array(
            'pretty_version' => '2.0.5',
            'version' => '2.0.5.0',
            'reference' => '42c5ba5220e6904cbfe8b1a1bda7c0cfdc8c12f5',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/php-file-iterator',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/php-text-template' => array(
            'pretty_version' => '1.2.1',
            'version' => '1.2.1.0',
            'reference' => '31f8b717e51d9a2afca6c9f046f5d69fc27c8686',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/php-text-template',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/php-timer' => array(
            'pretty_version' => '2.1.3',
            'version' => '2.1.3.0',
            'reference' => '2454ae1765516d20c4ffe103d85a58a9a3bd5662',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/php-timer',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/php-token-stream' => array(
            'pretty_version' => '4.0.4',
            'version' => '4.0.4.0',
            'reference' => 'a853a0e183b9db7eed023d7933a858fa1c8d25a3',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/php-token-stream',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'phpunit/phpunit' => array(
            'pretty_version' => '8.5.32',
            'version' => '8.5.32.0',
            'reference' => '375686930d05c9fd7d20f6e5fc38121e8d7a9d55',
            'type' => 'library',
            'install_path' => __DIR__ . '/../phpunit/phpunit',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'psr/log' => array(
            'pretty_version' => '1.1.4',
            'version' => '1.1.4.0',
            'reference' => 'd49695b909c3b7628b6289db5479a1c204601f11',
            'type' => 'library',
            'install_path' => __DIR__ . '/../psr/log',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'psr/log-implementation' => array(
            'dev_requirement' => true,
            'provided' => array(
                0 => '1.0.0',
            ),
        ),
        'sebastian/code-unit-reverse-lookup' => array(
            'pretty_version' => '1.0.2',
            'version' => '1.0.2.0',
            'reference' => '1de8cd5c010cb153fcd68b8d0f64606f523f7619',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/code-unit-reverse-lookup',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/comparator' => array(
            'pretty_version' => '3.0.5',
            'version' => '3.0.5.0',
            'reference' => '1dc7ceb4a24aede938c7af2a9ed1de09609ca770',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/comparator',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/diff' => array(
            'pretty_version' => '3.0.3',
            'version' => '3.0.3.0',
            'reference' => '14f72dd46eaf2f2293cbe79c93cc0bc43161a211',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/diff',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/environment' => array(
            'pretty_version' => '4.2.4',
            'version' => '4.2.4.0',
            'reference' => 'd47bbbad83711771f167c72d4e3f25f7fcc1f8b0',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/environment',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/exporter' => array(
            'pretty_version' => '3.1.5',
            'version' => '3.1.5.0',
            'reference' => '73a9676f2833b9a7c36968f9d882589cd75511e6',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/exporter',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/global-state' => array(
            'pretty_version' => '3.0.2',
            'version' => '3.0.2.0',
            'reference' => 'de036ec91d55d2a9e0db2ba975b512cdb1c23921',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/global-state',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/object-enumerator' => array(
            'pretty_version' => '3.0.4',
            'version' => '3.0.4.0',
            'reference' => 'e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/object-enumerator',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/object-reflector' => array(
            'pretty_version' => '1.1.2',
            'version' => '1.1.2.0',
            'reference' => '9b8772b9cbd456ab45d4a598d2dd1a1bced6363d',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/object-reflector',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/recursion-context' => array(
            'pretty_version' => '3.0.1',
            'version' => '3.0.1.0',
            'reference' => '367dcba38d6e1977be014dc4b22f47a484dac7fb',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/recursion-context',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/resource-operations' => array(
            'pretty_version' => '2.0.2',
            'version' => '2.0.2.0',
            'reference' => '31d35ca87926450c44eae7e2611d45a7a65ea8b3',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/resource-operations',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/type' => array(
            'pretty_version' => '1.1.4',
            'version' => '1.1.4.0',
            'reference' => '0150cfbc4495ed2df3872fb31b26781e4e077eb4',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/type',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'sebastian/version' => array(
            'pretty_version' => '2.0.1',
            'version' => '2.0.1.0',
            'reference' => '99732be0ddb3361e16ad77b68ba41efc8e979019',
            'type' => 'library',
            'install_path' => __DIR__ . '/../sebastian/version',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'symfony/event-dispatcher' => array(
            'pretty_version' => 'v2.8.52',
            'version' => '2.8.52.0',
            'reference' => 'a77e974a5fecb4398833b0709210e3d5e334ffb0',
            'type' => 'library',
            'install_path' => __DIR__ . '/../symfony/event-dispatcher',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
        'theseer/tokenizer' => array(
            'pretty_version' => '1.2.1',
            'version' => '1.2.1.0',
            'reference' => '34a41e998c2183e22995f158c581e7b5e755ab9e',
            'type' => 'library',
            'install_path' => __DIR__ . '/../theseer/tokenizer',
            'aliases' => array(),
            'dev_requirement' => false,
        ),
    ),
);
Copyright (c) 2014 Doctrine Project

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Introduction
============

This library provides a way of avoiding usage of constructors when instantiating PHP classes.

Installation
============

The suggested installation method is via `composer`_:

.. code-block:: console

   $ composer require doctrine/instantiator

Usage
=====

The instantiator is able to create new instances of any class without
using the constructor or any API of the class itself:

.. code-block:: php

    <?php

    use Doctrine\Instantiator\Instantiator;
    use App\Entities\User;

    $instantiator = new Instantiator();

    $user = $instantiator->instantiate(User::class);

Contributing
============

-  Follow the `Doctrine Coding Standard`_
-  The project will follow strict `object calisthenics`_
-  Any contribution must provide tests for additional introduced
   conditions
-  Any un-confirmed issue needs a failing test case before being
   accepted
-  Pull requests must be sent from a new hotfix/feature branch, not from
   ``master``.

Testing
=======

The PHPUnit version to be used is the one installed as a dev- dependency
via composer:

.. code-block:: console

   $ ./vendor/bin/phpunit

Accepted coverage for new contributions is 80%. Any contribution not
satisfying this requirement won’t be merged.

Credits
=======

This library was migrated from `ocramius/instantiator`_, which has been
donated to the doctrine organization, and which is now deprecated in
favour of this package.

.. _composer: https://getcomposer.org/
.. _CONTRIBUTING.md: CONTRIBUTING.md
.. _ocramius/instantiator: https://github.com/Ocramius/Instantiator
.. _Doctrine Coding Standard: https://github.com/doctrine/coding-standard
.. _object calisthenics: http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php
.. toctree::
    :depth: 3

    index
# Instantiator

This library provides a way of avoiding usage of constructors when instantiating PHP classes.

[![Build Status](https://travis-ci.org/doctrine/instantiator.svg?branch=master)](https://travis-ci.org/doctrine/instantiator)
[![Code Coverage](https://codecov.io/gh/doctrine/instantiator/branch/master/graph/badge.svg)](https://codecov.io/gh/doctrine/instantiator/branch/master)
[![Dependency Status](https://www.versioneye.com/package/php--doctrine--instantiator/badge.svg)](https://www.versioneye.com/package/php--doctrine--instantiator)

[![Latest Stable Version](https://poser.pugx.org/doctrine/instantiator/v/stable.png)](https://packagist.org/packages/doctrine/instantiator)
[![Latest Unstable Version](https://poser.pugx.org/doctrine/instantiator/v/unstable.png)](https://packagist.org/packages/doctrine/instantiator)

## Installation

The suggested installation method is via [composer](https://getcomposer.org/):

```sh
composer require doctrine/instantiator
```

## Usage

The instantiator is able to create new instances of any class without using the constructor or any API of the class
itself:

```php
$instantiator = new \Doctrine\Instantiator\Instantiator();

$instance = $instantiator->instantiate(\My\ClassName\Here::class);
```

## Contributing

Please read the [CONTRIBUTING.md](CONTRIBUTING.md) contents if you wish to help out!

## Credits

This library was migrated from [ocramius/instantiator](https://github.com/Ocramius/Instantiator), which
has been donated to the doctrine organization, and which is now deprecated in favour of this package.
# Contributing

 * Follow the [Doctrine Coding Standard](https://github.com/doctrine/coding-standard)
 * The project will follow strict [object calisthenics](http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php)
 * Any contribution must provide tests for additional introduced conditions
 * Any un-confirmed issue needs a failing test case before being accepted
 * Pull requests must be sent from a new hotfix/feature branch, not from `master`.

## Installation

To install the project and run the tests, you need to clone it first:

```sh
$ git clone git://github.com/doctrine/instantiator.git
```

You will then need to run a composer installation:

```sh
$ cd Instantiator
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar update
```

## Testing

The PHPUnit version to be used is the one installed as a dev- dependency via composer:

```sh
$ ./vendor/bin/phpunit
```

Accepted coverage for new contributions is 80%. Any contribution not satisfying this requirement 
won't be merged.

{
    "active": true,
    "name": "Instantiator",
    "slug": "instantiator",
    "docsSlug": "doctrine-instantiator",
    "codePath": "/src",
    "versions": [
        {
            "name": "1.5",
            "branchName": "1.5.x",
            "slug": "latest",
            "upcoming": true
        },
        {
            "name": "1.4",
            "branchName": "1.4.x",
            "slug": "1.4",
            "aliases": [
                "current",
                "stable"
            ],
            "maintained": true,
            "current": true
        },
        {
            "name": "1.3",
            "branchName": "1.3.x",
            "slug": "1.3",
            "maintained": false
        },
        {
            "name": "1.2",
            "branchName": "1.2.x",
            "slug": "1.2"
        },
        {
            "name": "1.1",
            "branchName": "1.1.x",
            "slug": "1.1"
        },
        {
            "name": "1.0",
            "branchName": "1.0.x",
            "slug": "1.0"
        }
    ]
}
{
    "name":              "doctrine/instantiator",
    "description":       "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
    "type":              "library",
    "license":           "MIT",
    "homepage":          "https://www.doctrine-project.org/projects/instantiator.html",
    "keywords":          [
        "instantiate",
        "constructor"
    ],
    "authors": [
        {
            "name":     "Marco Pivetta",
            "email":    "ocramius@gmail.com",
            "homepage": "https://ocramius.github.io/"
        }
    ],
    "require": {
        "php": "^7.1 || ^8.0"
    },
    "require-dev": {
        "ext-phar":                  "*",
        "ext-pdo":                   "*",
        "doctrine/coding-standard":  "^9 || ^11",
        "phpbench/phpbench":         "^0.16 || ^1",
        "phpstan/phpstan":           "^1.4",
        "phpstan/phpstan-phpunit":   "^1",
        "phpunit/phpunit":           "^7.5 || ^8.5 || ^9.5",
        "vimeo/psalm": "^4.30 || ^5.4"
    },
    "autoload": {
        "psr-4": {
            "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
        }
    },
    "autoload-dev": {
        "psr-0": {
            "DoctrineTest\\InstantiatorPerformance\\": "tests",
            "DoctrineTest\\InstantiatorTest\\": "tests",
            "DoctrineTest\\InstantiatorTestAsset\\": "tests"
        }
    },
    "config": {
        "allow-plugins": {
            "dealerdirect/phpcodesniffer-composer-installer": true
        }
    }
}
<?xml version="1.0"?>
<psalm
    errorLevel="7"
    phpVersion="8.2"
    resolveFromConfigFile="true"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://getpsalm.org/schema/config"
    xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
    <projectFiles>
        <directory name="src" />
        <ignoreFiles>
            <directory name="vendor" />
        </ignoreFiles>
    </projectFiles>
</psalm>
<?php

namespace Doctrine\Instantiator;

use ArrayIterator;
use Doctrine\Instantiator\Exception\ExceptionInterface;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Exception;
use ReflectionClass;
use ReflectionException;
use Serializable;

use function class_exists;
use function enum_exists;
use function is_subclass_of;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use function strlen;
use function unserialize;

use const PHP_VERSION_ID;

final class Instantiator implements InstantiatorInterface
{
    /**
     * Markers used internally by PHP to define whether {@see \unserialize} should invoke
     * the method {@see \Serializable::unserialize()} when dealing with classes implementing
     * the {@see \Serializable} interface.
     *
     * @deprecated This constant will be private in 2.0
     */
    public const SERIALIZATION_FORMAT_USE_UNSERIALIZER = 'C';

    /** @deprecated This constant will be private in 2.0 */
    public const SERIALIZATION_FORMAT_AVOID_UNSERIALIZER = 'O';

    /**
     * Used to instantiate specific classes, indexed by class name.
     *
     * @var callable[]
     */
    private static $cachedInstantiators = [];

    /**
     * Array of objects that can directly be cloned, indexed by class name.
     *
     * @var object[]
     */
    private static $cachedCloneables = [];

    /**
     * @param string $className
     * @phpstan-param class-string<T> $className
     *
     * @return object
     * @phpstan-return T
     *
     * @throws ExceptionInterface
     *
     * @template T of object
     */
    public function instantiate($className)
    {
        if (isset(self::$cachedCloneables[$className])) {
            /** @phpstan-var T */
            $cachedCloneable = self::$cachedCloneables[$className];

            return clone $cachedCloneable;
        }

        if (isset(self::$cachedInstantiators[$className])) {
            $factory = self::$cachedInstantiators[$className];

            return $factory();
        }

        return $this->buildAndCacheFromFactory($className);
    }

    /**
     * Builds the requested object and caches it in static properties for performance
     *
     * @phpstan-param class-string<T> $className
     *
     * @return object
     * @phpstan-return T
     *
     * @template T of object
     */
    private function buildAndCacheFromFactory(string $className)
    {
        $factory  = self::$cachedInstantiators[$className] = $this->buildFactory($className);
        $instance = $factory();

        if ($this->isSafeToClone(new ReflectionClass($instance))) {
            self::$cachedCloneables[$className] = clone $instance;
        }

        return $instance;
    }

    /**
     * Builds a callable capable of instantiating the given $className without
     * invoking its constructor.
     *
     * @phpstan-param class-string<T> $className
     *
     * @phpstan-return callable(): T
     *
     * @throws InvalidArgumentException
     * @throws UnexpectedValueException
     * @throws ReflectionException
     *
     * @template T of object
     */
    private function buildFactory(string $className): callable
    {
        $reflectionClass = $this->getReflectionClass($className);

        if ($this->isInstantiableViaReflection($reflectionClass)) {
            return [$reflectionClass, 'newInstanceWithoutConstructor'];
        }

        $serializedString = sprintf(
            '%s:%d:"%s":0:{}',
            is_subclass_of($className, Serializable::class) ? self::SERIALIZATION_FORMAT_USE_UNSERIALIZER : self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER,
            strlen($className),
            $className
        );

        $this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);

        return static function () use ($serializedString) {
            return unserialize($serializedString);
        };
    }

    /**
     * @phpstan-param class-string<T> $className
     *
     * @phpstan-return ReflectionClass<T>
     *
     * @throws InvalidArgumentException
     * @throws ReflectionException
     *
     * @template T of object
     */
    private function getReflectionClass(string $className): ReflectionClass
    {
        if (! class_exists($className)) {
            throw InvalidArgumentException::fromNonExistingClass($className);
        }

        if (PHP_VERSION_ID >= 80100 && enum_exists($className, false)) {
            throw InvalidArgumentException::fromEnum($className);
        }

        $reflection = new ReflectionClass($className);

        if ($reflection->isAbstract()) {
            throw InvalidArgumentException::fromAbstractClass($reflection);
        }

        return $reflection;
    }

    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @throws UnexpectedValueException
     *
     * @template T of object
     */
    private function checkIfUnSerializationIsSupported(ReflectionClass $reflectionClass, string $serializedString): void
    {
        set_error_handler(static function (int $code, string $message, string $file, int $line) use ($reflectionClass, &$error): bool {
            $error = UnexpectedValueException::fromUncleanUnSerialization(
                $reflectionClass,
                $message,
                $code,
                $file,
                $line
            );

            return true;
        });

        try {
            $this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
        } finally {
            restore_error_handler();
        }

        if ($error) {
            throw $error;
        }
    }

    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @throws UnexpectedValueException
     *
     * @template T of object
     */
    private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, string $serializedString): void
    {
        try {
            unserialize($serializedString);
        } catch (Exception $exception) {
            throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception);
        }
    }

    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    private function isInstantiableViaReflection(ReflectionClass $reflectionClass): bool
    {
        return ! ($this->hasInternalAncestors($reflectionClass) && $reflectionClass->isFinal());
    }

    /**
     * Verifies whether the given class is to be considered internal
     *
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    private function hasInternalAncestors(ReflectionClass $reflectionClass): bool
    {
        do {
            if ($reflectionClass->isInternal()) {
                return true;
            }

            $reflectionClass = $reflectionClass->getParentClass();
        } while ($reflectionClass);

        return false;
    }

    /**
     * Checks if a class is cloneable
     *
     * Classes implementing `__clone` cannot be safely cloned, as that may cause side-effects.
     *
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    private function isSafeToClone(ReflectionClass $reflectionClass): bool
    {
        return $reflectionClass->isCloneable()
            && ! $reflectionClass->hasMethod('__clone')
            && ! $reflectionClass->isSubclassOf(ArrayIterator::class);
    }
}
<?php

namespace Doctrine\Instantiator;

use Doctrine\Instantiator\Exception\ExceptionInterface;

/**
 * Instantiator provides utility methods to build objects without invoking their constructors
 */
interface InstantiatorInterface
{
    /**
     * @param string $className
     * @phpstan-param class-string<T> $className
     *
     * @return object
     * @phpstan-return T
     *
     * @throws ExceptionInterface
     *
     * @template T of object
     */
    public function instantiate($className);
}
<?php

namespace Doctrine\Instantiator\Exception;

use Throwable;

/**
 * Base exception marker interface for the instantiator component
 */
interface ExceptionInterface extends Throwable
{
}
<?php

namespace Doctrine\Instantiator\Exception;

use Exception;
use ReflectionClass;
use UnexpectedValueException as BaseUnexpectedValueException;

use function sprintf;

/**
 * Exception for given parameters causing invalid/unexpected state on instantiation
 */
class UnexpectedValueException extends BaseUnexpectedValueException implements ExceptionInterface
{
    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    public static function fromSerializationTriggeredException(
        ReflectionClass $reflectionClass,
        Exception $exception
    ): self {
        return new self(
            sprintf(
                'An exception was raised while trying to instantiate an instance of "%s" via un-serialization',
                $reflectionClass->getName()
            ),
            0,
            $exception
        );
    }

    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    public static function fromUncleanUnSerialization(
        ReflectionClass $reflectionClass,
        string $errorString,
        int $errorCode,
        string $errorFile,
        int $errorLine
    ): self {
        return new self(
            sprintf(
                'Could not produce an instance of "%s" via un-serialization, since an error was triggered '
                . 'in file "%s" at line "%d"',
                $reflectionClass->getName(),
                $errorFile,
                $errorLine
            ),
            0,
            new Exception($errorString, $errorCode)
        );
    }
}
<?php

namespace Doctrine\Instantiator\Exception;

use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;

use function interface_exists;
use function sprintf;
use function trait_exists;

/**
 * Exception for invalid arguments provided to the instantiator
 */
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
    public static function fromNonExistingClass(string $className): self
    {
        if (interface_exists($className)) {
            return new self(sprintf('The provided type "%s" is an interface, and cannot be instantiated', $className));
        }

        if (trait_exists($className)) {
            return new self(sprintf('The provided type "%s" is a trait, and cannot be instantiated', $className));
        }

        return new self(sprintf('The provided class "%s" does not exist', $className));
    }

    /**
     * @phpstan-param ReflectionClass<T> $reflectionClass
     *
     * @template T of object
     */
    public static function fromAbstractClass(ReflectionClass $reflectionClass): self
    {
        return new self(sprintf(
            'The provided class "%s" is abstract, and cannot be instantiated',
            $reflectionClass->getName()
        ));
    }

    public static function fromEnum(string $className): self
    {
        return new self(sprintf(
            'The provided class "%s" is an enum, and cannot be instantiated',
            $className
        ));
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.0/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuite name="default">
        <directory suffix="Test.php">tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
phpunit/php-timer

Copyright (c) 2010-2019, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [2.1.3] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [2.1.2] - 2019-06-07

### Fixed

* Fixed [#21](https://github.com/sebastianbergmann/php-timer/pull/3352): Formatting of memory consumption does not work on 32bit systems

## [2.1.1] - 2019-02-20

### Changed

* Improved formatting of memory consumption for `resourceUsage()`

## [2.1.0] - 2019-02-20

### Changed

* Improved formatting of memory consumption for `resourceUsage()`

## [2.0.0] - 2018-02-01

### Changed

* This component now uses namespaces

### Removed

* This component is no longer supported on PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6, and PHP 7.0

[2.1.3]: https://github.com/sebastianbergmann/diff/compare/2.1.2...2.1.3
[2.1.2]: https://github.com/sebastianbergmann/diff/compare/2.1.1...2.1.2
[2.1.1]: https://github.com/sebastianbergmann/diff/compare/2.1.0...2.1.1
[2.1.0]: https://github.com/sebastianbergmann/diff/compare/2.0.0...2.1.0
[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.0.9...2.0.0
<?xml version="1.0" encoding="UTF-8"?>
<project name="php-timer" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>
</project>

<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-timer.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Timer;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Timer\Timer
 */
final class TimerTest extends TestCase
{
    public function testCanBeStartedAndStopped(): void
    {
        $this->assertIsFloat(Timer::stop());
    }

    public function testCanFormatTimeSinceStartOfRequest(): void
    {
        $this->assertStringMatchesFormat('%f %s', Timer::timeSinceStartOfRequest());
    }

    /**
     * @backupGlobals enabled
     */
    public function testCanFormatSinceStartOfRequestWhenRequestTimeIsNotAvailableAsFloat(): void
    {
        if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
            unset($_SERVER['REQUEST_TIME_FLOAT']);
        }

        $this->assertStringMatchesFormat('%f %s', Timer::timeSinceStartOfRequest());
    }

    /**
     * @backupGlobals enabled
     */
    public function testCannotFormatTimeSinceStartOfRequestWhenRequestTimeIsNotAvailable(): void
    {
        if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
            unset($_SERVER['REQUEST_TIME_FLOAT']);
        }

        if (isset($_SERVER['REQUEST_TIME'])) {
            unset($_SERVER['REQUEST_TIME']);
        }

        $this->expectException(RuntimeException::class);

        Timer::timeSinceStartOfRequest();
    }

    public function testCanFormatResourceUsage(): void
    {
        $this->assertStringMatchesFormat('Time: %s, Memory: %f %s', Timer::resourceUsage());
    }

    /**
     * @dataProvider secondsProvider
     */
    public function testCanFormatSecondsAsString(string $string, float $seconds): void
    {
        $this->assertEquals($string, Timer::secondsToTimeString($seconds));
    }

    public function secondsProvider(): array
    {
        return [
            ['0 ms', 0],
            ['1 ms', .001],
            ['10 ms', .01],
            ['100 ms', .1],
            ['999 ms', .999],
            ['1 second', .9999],
            ['1 second', 1],
            ['2 seconds', 2],
            ['59.9 seconds', 59.9],
            ['59.99 seconds', 59.99],
            ['59.99 seconds', 59.999],
            ['1 minute', 59.9999],
            ['59 seconds', 59.001],
            ['59.01 seconds', 59.01],
            ['1 minute', 60],
            ['1.01 minutes', 61],
            ['2 minutes', 120],
            ['2.01 minutes', 121],
            ['59.99 minutes', 3599.9],
            ['59.99 minutes', 3599.99],
            ['59.99 minutes', 3599.999],
            ['1 hour', 3599.9999],
            ['59.98 minutes', 3599.001],
            ['59.98 minutes', 3599.01],
            ['1 hour', 3600],
            ['1 hour', 3601],
            ['1 hour', 3601.9],
            ['1 hour', 3601.99],
            ['1 hour', 3601.999],
            ['1 hour', 3601.9999],
            ['1.01 hours', 3659.9999],
            ['1.01 hours', 3659.001],
            ['1.01 hours', 3659.01],
            ['2 hours', 7199.9999],
        ];
    }

    /**
     * @dataProvider bytesProvider
     */
    public function testCanFormatBytesAsString(string $string, float $bytes): void
    {
        $this->assertEquals($string, Timer::bytesToString($bytes));
    }

    public function bytesProvider(): array
    {
        return [
            ['0 bytes', 0],
            ['1 byte', 1],
            ['1023 bytes', 1023],
            ['1.00 KB', 1024],
            ['1.50 KB', 1.5 * 1024],
            ['2.00 MB', 2 * 1048576],
            ['2.50 MB', 2.5 * 1048576],
            ['3.00 GB', 3 * 1073741824],
            ['3.50 GB', 3.5 * 1073741824],
        ];
    }
}
[![Build Status](https://travis-ci.org/sebastianbergmann/php-timer.svg?branch=master)](https://travis-ci.org/sebastianbergmann/php-timer)

# phpunit/php-timer

Utility class for timing things, factored out of PHPUnit into a stand-alone component.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require phpunit/php-timer

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev phpunit/php-timer

## Usage

### Basic Timing

```php
use SebastianBergmann\Timer\Timer;

Timer::start();

// ...

$time = Timer::stop();
var_dump($time);

print Timer::secondsToTimeString($time);
```

The code above yields the output below:

    double(1.0967254638672E-5)
    0 ms

### Resource Consumption Since PHP Startup

```php
use SebastianBergmann\Timer\Timer;

print Timer::resourceUsage();
```

The code above yields the output below:

    Time: 0 ms, Memory: 0.50MB
/.idea
/.php_cs.cache
/vendor
/composer.lock

patreon: s_bergmann
# Configuration for probot-stale - https://github.com/probot/stale

# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale Issue or Pull Request is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 7

# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
  - enhancement

# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false

# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false

# Label to use when marking as stale
staleLabel: stale

# Comment to post when marking as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.

# Comment to post when removing the stale label.
# unmarkComment: >
#   Your comment here.

# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
  This issue has been automatically closed because it has not had activity since it was marked as stale. Thank you for your contributions.

# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

# Limit to only `issues` or `pulls`
only: issues

*.php diff=php
language: php

php:
  - 7.1
  - 7.2
  - 7.3
  - 7.4snapshot

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "phpunit/php-timer",
    "description": "Utility class for timing",
    "type": "library",
    "keywords": [
        "timer"
    ],
    "homepage": "https://github.com/sebastianbergmann/php-timer/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/php-timer/issues"
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.5"
    },
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "2.1-dev"
        }
    }
}

<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of phpunit/php-timer.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => ['groups' => ['simple', 'meta']],
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-timer.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Timer;

final class RuntimeException extends \RuntimeException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-timer.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Timer;

final class Timer
{
    /**
     * @var int[]
     */
    private static $sizes = [
        'GB' => 1073741824,
        'MB' => 1048576,
        'KB' => 1024,
    ];

    /**
     * @var int[]
     */
    private static $times = [
        'hour'   => 3600000,
        'minute' => 60000,
        'second' => 1000,
    ];

    /**
     * @var float[]
     */
    private static $startTimes = [];

    public static function start(): void
    {
        self::$startTimes[] = \microtime(true);
    }

    public static function stop(): float
    {
        return \microtime(true) - \array_pop(self::$startTimes);
    }

    public static function bytesToString(float $bytes): string
    {
        foreach (self::$sizes as $unit => $value) {
            if ($bytes >= $value) {
                return \sprintf('%.2f %s', $bytes >= 1024 ? $bytes / $value : $bytes, $unit);
            }
        }

        return $bytes . ' byte' . ((int) $bytes !== 1 ? 's' : '');
    }

    public static function secondsToTimeString(float $time): string
    {
        $ms = \round($time * 1000);

        foreach (self::$times as $unit => $value) {
            if ($ms >= $value) {
                $time = \floor($ms / $value * 100.0) / 100.0;

                return $time . ' ' . ($time == 1 ? $unit : $unit . 's');
            }
        }

        return $ms . ' ms';
    }

    /**
     * @throws RuntimeException
     */
    public static function timeSinceStartOfRequest(): string
    {
        if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
            $startOfRequest = $_SERVER['REQUEST_TIME_FLOAT'];
        } elseif (isset($_SERVER['REQUEST_TIME'])) {
            $startOfRequest = $_SERVER['REQUEST_TIME'];
        } else {
            throw new RuntimeException('Cannot determine time at which the request started');
        }

        return self::secondsToTimeString(\microtime(true) - $startOfRequest);
    }

    /**
     * @throws RuntimeException
     */
    public static function resourceUsage(): string
    {
        return \sprintf(
            'Time: %s, Memory: %s',
            self::timeSinceStartOfRequest(),
            self::bytesToString(\memory_get_peak_usage(true))
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-timer.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Timer;

interface Exception
{
}
php-token-stream

Copyright (c) 2009-2020, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Change Log

All notable changes to `sebastianbergmann/php-token-stream` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [4.0.4] - 2020-08-04

### Added

* Support for `NAME_FULLY_QUALIFIED`, `NAME_QUALIFIED`, and `NAME_RELATIVE` tokens

## [4.0.3] - 2020-06-27

### Added

* This component is now supported on PHP 8

## [4.0.2] - 2020-06-16

### Fixed

* Fixed backward compatibility breaks introduced in version 4.0.1

## [4.0.1] - 2020-05-06

### Fixed

* [#93](https://github.com/sebastianbergmann/php-token-stream/issues/93): Class with method that uses anonymous class is not processed correctly

## [4.0.0] - 2020-02-07

### Removed

* This component is no longer supported PHP 7.1 and PHP 7.2

## [3.1.1] - 2019-09-17

### Fixed

* [#84](https://github.com/sebastianbergmann/php-token-stream/issues/84): Methods named `class` are not handled correctly

## [3.1.0] - 2019-07-25

### Added

* Added support for `FN` and `COALESCE_EQUAL` tokens introduced in PHP 7.4

## [3.0.2] - 2019-07-08

### Changed

* [#82](https://github.com/sebastianbergmann/php-token-stream/issues/82): Make sure this component works when its classes are prefixed using php-scoper

## [3.0.1] - 2018-10-30

### Fixed

* [#78](https://github.com/sebastianbergmann/php-token-stream/pull/78): `getEndTokenId()` does not handle string-dollar (`"${var}"`) interpolation

## [3.0.0] - 2018-02-01

### Removed

* [#71](https://github.com/sebastianbergmann/php-token-stream/issues/71): Remove code specific to Hack language constructs
* [#72](https://github.com/sebastianbergmann/php-token-stream/issues/72): Drop support for PHP 7.0

## [2.0.2] - 2017-11-27

### Fixed

* [#69](https://github.com/sebastianbergmann/php-token-stream/issues/69): `PHP_Token_USE_FUNCTION` does not serialize correctly

## [2.0.1] - 2017-08-20

### Fixed

* [#68](https://github.com/sebastianbergmann/php-token-stream/issues/68): Method with name `empty` wrongly recognized as anonymous function

## [2.0.0] - 2017-08-03

[4.0.4]: https://github.com/sebastianbergmann/php-token-stream/compare/4.0.3...4.0.4
[4.0.3]: https://github.com/sebastianbergmann/php-token-stream/compare/4.0.2...4.0.3
[4.0.2]: https://github.com/sebastianbergmann/php-token-stream/compare/4.0.1...4.0.2
[4.0.1]: https://github.com/sebastianbergmann/php-token-stream/compare/4.0.0...4.0.1
[4.0.0]: https://github.com/sebastianbergmann/php-token-stream/compare/3.1.1...4.0.0
[3.1.1]: https://github.com/sebastianbergmann/php-token-stream/compare/3.1.0...3.1.1
[3.1.0]: https://github.com/sebastianbergmann/php-token-stream/compare/3.0.2...3.1.0
[3.0.2]: https://github.com/sebastianbergmann/php-token-stream/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/php-token-stream/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/php-token-stream/compare/2.0...3.0.0
[2.0.2]: https://github.com/sebastianbergmann/php-token-stream/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/sebastianbergmann/php-token-stream/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/php-token-stream/compare/1.4.11...2.0.0
# phpunit/php-token-stream

[![CI Status](https://github.com/sebastianbergmann/php-token-stream/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/php-token-stream/actions)
[![Type Coverage](https://shepherd.dev/github/sebastianbergmann/php-token-stream/coverage.svg)](https://shepherd.dev/github/sebastianbergmann/php-token-stream)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

```
composer require phpunit/php-token-stream
```

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

```
composer require --dev phpunit/php-token-stream
```
/.idea
/.php_cs
/.php_cs.cache
/.phpunit.result.cache
/.psalm/cache
/composer.lock
/vendor
/.github        export-ignore
/.phive         export-ignore
/.php_cs.dist   export-ignore
/.psalm         export-ignore
/bin            export-ignore
/build.xml      export-ignore
/phpunit.xml    export-ignore
/tests          export-ignore
/tools          export-ignore
/tools/*        binary

*.php diff=php
{
    "name": "phpunit/php-token-stream",
    "description": "Wrapper around PHP's tokenizer extension.",
    "type": "library",
    "keywords": ["tokenizer"],
    "homepage": "https://github.com/sebastianbergmann/php-token-stream/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/php-token-stream/issues"
    },
    "prefer-stable": true,
    "require": {
        "php": "^7.3 || ^8.0",
        "ext-tokenizer": "*"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.0"
    },
    "config": {
        "platform": {
            "php": "7.3.0"
        },
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "4.0-dev"
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_COALESCE_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_GOTO extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FINAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SR_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_AMPERSAND extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_COMMA extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOUBLE_ARROW extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FOR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INSTEADOF extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLOSE_TAG extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PLUS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_STATIC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_AND_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDWHILE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NUM_STRING extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_GLOBAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDDECLARE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
abstract class PHP_TokenWithScope extends PHP_Token
{
    /**
     * @var int
     */
    protected $endTokenId;

    /**
     * Get the docblock for this token.
     *
     * This method will fetch the docblock belonging to the current token. The
     * docblock must be placed on the line directly above the token to be
     * recognized.
     *
     * @return null|string Returns the docblock as a string if found
     */
    public function getDocblock()
    {
        $tokens            = $this->tokenStream->tokens();
        $currentLineNumber = $tokens[$this->id]->getLine();
        $prevLineNumber    = $currentLineNumber - 1;

        for ($i = $this->id - 1; $i; $i--) {
            if (!isset($tokens[$i])) {
                return;
            }

            if ($tokens[$i] instanceof PHP_Token_FUNCTION ||
                $tokens[$i] instanceof PHP_Token_CLASS ||
                $tokens[$i] instanceof PHP_Token_TRAIT) {
                // Some other trait, class or function, no docblock can be
                // used for the current token
                break;
            }

            $line = $tokens[$i]->getLine();

            if ($line == $currentLineNumber ||
                ($line == $prevLineNumber &&
                    $tokens[$i] instanceof PHP_Token_WHITESPACE)) {
                continue;
            }

            if ($line < $currentLineNumber &&
                !$tokens[$i] instanceof PHP_Token_DOC_COMMENT) {
                break;
            }

            return (string) $tokens[$i];
        }
    }

    /**
     * @return int
     */
    public function getEndTokenId()
    {
        $block  = 0;
        $i      = $this->id;
        $tokens = $this->tokenStream->tokens();

        while ($this->endTokenId === null && isset($tokens[$i])) {
            if ($tokens[$i] instanceof PHP_Token_OPEN_CURLY ||
                $tokens[$i] instanceof PHP_Token_DOLLAR_OPEN_CURLY_BRACES ||
                $tokens[$i] instanceof PHP_Token_CURLY_OPEN) {
                $block++;
            } elseif ($tokens[$i] instanceof PHP_Token_CLOSE_CURLY) {
                $block--;

                if ($block === 0) {
                    $this->endTokenId = $i;
                }
            } elseif (($this instanceof PHP_Token_FUNCTION ||
                    $this instanceof PHP_Token_NAMESPACE) &&
                $tokens[$i] instanceof PHP_Token_SEMICOLON) {
                if ($block === 0) {
                    $this->endTokenId = $i;
                }
            }

            $i++;
        }

        if ($this->endTokenId === null) {
            $this->endTokenId = $this->id;
        }

        return $this->endTokenId;
    }

    /**
     * @return int
     */
    public function getEndLine()
    {
        return $this->tokenStream[$this->getEndTokenId()]->getLine();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDIF extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PAAMAYIM_NEKUDOTAYIM extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLASS extends PHP_Token_INTERFACE
{
    /**
     * @var bool
     */
    private $anonymous = false;

    /**
     * @var string
     */
    private $name;

    /**
     * @return string
     */
    public function getName()
    {
        if ($this->name !== null) {
            return $this->name;
        }

        $next = $this->tokenStream[$this->id + 1];

        if ($next instanceof PHP_Token_WHITESPACE) {
            $next = $this->tokenStream[$this->id + 2];
        }

        if ($next instanceof PHP_Token_STRING) {
            $this->name =(string) $next;

            return $this->name;
        }

        if ($next instanceof PHP_Token_OPEN_CURLY ||
            $next instanceof PHP_Token_EXTENDS ||
            $next instanceof PHP_Token_IMPLEMENTS) {
            $this->name = \sprintf(
                'AnonymousClass:%s#%s',
                $this->getLine(),
                $this->getId()
            );

            $this->anonymous = true;

            return $this->name;
        }
    }

    public function isAnonymous()
    {
        return $this->anonymous;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CALLABLE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_AS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOUBLE_COLON extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DIV_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_VARIABLE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CONST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CONTINUE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LOGICAL_OR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_RETURN extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_YIELD extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLASS_NAME_CONSTANT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INSTANCEOF extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CONSTANT_ENCAPSED_STRING extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INCLUDE extends PHP_Token_Includes
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
abstract class PHP_Token
{
    /**
     * @var string
     */
    protected $text;

    /**
     * @var int
     */
    protected $line;

    /**
     * @var PHP_Token_Stream
     */
    protected $tokenStream;

    /**
     * @var int
     */
    protected $id;

    /**
     * @param string $text
     * @param int    $line
     * @param int    $id
     */
    public function __construct($text, $line, PHP_Token_Stream $tokenStream, $id)
    {
        $this->text        = $text;
        $this->line        = $line;
        $this->tokenStream = $tokenStream;
        $this->id          = $id;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->text;
    }

    /**
     * @return int
     */
    public function getLine()
    {
        return $this->line;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SPACESHIP extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOC_COMMENT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CASE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_UNSET extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DNUMBER extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CATCH extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EVAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_AT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOUBLE_QUOTES extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDFOR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SL_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IMPLEMENTS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_NOT_IDENTICAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_YIELD_FROM extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_START_HEREDOC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ABSTRACT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOUBLE_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EMPTY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OBJECT_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_REQUIRE_ONCE extends PHP_Token_Includes
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DIR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ARRAY_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NAME_FULLY_QUALIFIED extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLOSE_CURLY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDSWITCH extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FUNC_C extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FILE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OPEN_TAG extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PROTECTED extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OPEN_CURLY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BOOLEAN_OR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ARRAY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_SMALLER_OR_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LOGICAL_AND extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INTERFACE extends PHP_TokenWithScopeAndVisibility
{
    /**
     * @var array
     */
    protected $interfaces;

    /**
     * @return string
     */
    public function getName()
    {
        return (string) $this->tokenStream[$this->id + 2];
    }

    /**
     * @return bool
     */
    public function hasParent()
    {
        return $this->tokenStream[$this->id + 4] instanceof PHP_Token_EXTENDS;
    }

    /**
     * @return array
     */
    public function getPackage()
    {
        $result = [
            'namespace'   => '',
            'fullPackage' => '',
            'category'    => '',
            'package'     => '',
            'subpackage'  => '',
        ];

        $docComment = $this->getDocblock();
        $className  = $this->getName();

        for ($i = $this->id; $i; --$i) {
            if ($this->tokenStream[$i] instanceof PHP_Token_NAMESPACE) {
                $result['namespace'] = $this->tokenStream[$i]->getName();

                break;
            }
        }

        if ($docComment === null) {
            return $result;
        }

        if (\preg_match('/@category[\s]+([\.\w]+)/', $docComment, $matches)) {
            $result['category'] = $matches[1];
        }

        if (\preg_match('/@package[\s]+([\.\w]+)/', $docComment, $matches)) {
            $result['package']     = $matches[1];
            $result['fullPackage'] = $matches[1];
        }

        if (\preg_match('/@subpackage[\s]+([\.\w]+)/', $docComment, $matches)) {
            $result['subpackage']   = $matches[1];
            $result['fullPackage'] .= '.' . $matches[1];
        }

        if (empty($result['fullPackage'])) {
            $result['fullPackage'] = $this->arrayToName(
                \explode('_', \str_replace('\\', '_', $className)),
                '.'
            );
        }

        return $result;
    }

    /**
     * @return bool|string
     */
    public function getParent()
    {
        if (!$this->hasParent()) {
            return false;
        }

        $i         = $this->id + 6;
        $tokens    = $this->tokenStream->tokens();
        $className = (string) $tokens[$i];

        while (isset($tokens[$i + 1]) &&
            !$tokens[$i + 1] instanceof PHP_Token_WHITESPACE) {
            $className .= (string) $tokens[++$i];
        }

        return $className;
    }

    /**
     * @return bool
     */
    public function hasInterfaces()
    {
        return (isset($this->tokenStream[$this->id + 4]) &&
                $this->tokenStream[$this->id + 4] instanceof PHP_Token_IMPLEMENTS) ||
            (isset($this->tokenStream[$this->id + 8]) &&
                $this->tokenStream[$this->id + 8] instanceof PHP_Token_IMPLEMENTS);
    }

    /**
     * @return array|bool
     */
    public function getInterfaces()
    {
        if ($this->interfaces !== null) {
            return $this->interfaces;
        }

        if (!$this->hasInterfaces()) {
            return $this->interfaces = false;
        }

        if ($this->tokenStream[$this->id + 4] instanceof PHP_Token_IMPLEMENTS) {
            $i = $this->id + 3;
        } else {
            $i = $this->id + 7;
        }

        $tokens = $this->tokenStream->tokens();

        while (!$tokens[$i + 1] instanceof PHP_Token_OPEN_CURLY) {
            $i++;

            if ($tokens[$i] instanceof PHP_Token_STRING) {
                $this->interfaces[] = (string) $tokens[$i];
            }
        }

        return $this->interfaces;
    }

    /**
     * @param string $join
     *
     * @return string
     */
    protected function arrayToName(array $parts, $join = '\\')
    {
        $result = '';

        if (\count($parts) > 1) {
            \array_pop($parts);

            $result = \implode($join, $parts);
        }

        return $result;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_VAR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_POW_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CURLY_OPEN extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FUNCTION extends PHP_TokenWithScopeAndVisibility
{
    /**
     * @var array
     */
    protected $arguments;

    /**
     * @var int
     */
    protected $ccn;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $signature;

    /**
     * @var bool
     */
    private $anonymous = false;

    /**
     * @return array
     */
    public function getArguments()
    {
        if ($this->arguments !== null) {
            return $this->arguments;
        }

        $this->arguments = [];
        $tokens          = $this->tokenStream->tokens();
        $typeDeclaration = null;

        // Search for first token inside brackets
        $i = $this->id + 2;

        while (!$tokens[$i - 1] instanceof PHP_Token_OPEN_BRACKET) {
            $i++;
        }

        while (!$tokens[$i] instanceof PHP_Token_CLOSE_BRACKET) {
            if ($tokens[$i] instanceof PHP_Token_STRING) {
                $typeDeclaration = (string) $tokens[$i];
            } elseif ($tokens[$i] instanceof PHP_Token_VARIABLE) {
                $this->arguments[(string) $tokens[$i]] = $typeDeclaration;
                $typeDeclaration                       = null;
            }

            $i++;
        }

        return $this->arguments;
    }

    /**
     * @return string
     */
    public function getName()
    {
        if ($this->name !== null) {
            return $this->name;
        }

        $tokens = $this->tokenStream->tokens();

        $i = $this->id + 1;

        if ($tokens[$i] instanceof PHP_Token_WHITESPACE) {
            $i++;
        }

        if ($tokens[$i] instanceof PHP_Token_AMPERSAND) {
            $i++;
        }

        if ($tokens[$i + 1] instanceof PHP_Token_OPEN_BRACKET) {
            $this->name = (string) $tokens[$i];
        } elseif ($tokens[$i + 1] instanceof PHP_Token_WHITESPACE && $tokens[$i + 2] instanceof PHP_Token_OPEN_BRACKET) {
            $this->name = (string) $tokens[$i];
        } else {
            $this->anonymous = true;

            $this->name = \sprintf(
                'anonymousFunction:%s#%s',
                $this->getLine(),
                $this->getId()
            );
        }

        if (!$this->isAnonymous()) {
            for ($i = $this->id; $i; --$i) {
                if ($tokens[$i] instanceof PHP_Token_NAMESPACE) {
                    $this->name = $tokens[$i]->getName() . '\\' . $this->name;

                    break;
                }

                if ($tokens[$i] instanceof PHP_Token_INTERFACE) {
                    break;
                }
            }
        }

        return $this->name;
    }

    /**
     * @return int
     */
    public function getCCN()
    {
        if ($this->ccn !== null) {
            return $this->ccn;
        }

        $this->ccn = 1;
        $end       = $this->getEndTokenId();
        $tokens    = $this->tokenStream->tokens();

        for ($i = $this->id; $i <= $end; $i++) {
            switch (\get_class($tokens[$i])) {
                case PHP_Token_IF::class:
                case PHP_Token_ELSEIF::class:
                case PHP_Token_FOR::class:
                case PHP_Token_FOREACH::class:
                case PHP_Token_WHILE::class:
                case PHP_Token_CASE::class:
                case PHP_Token_CATCH::class:
                case PHP_Token_BOOLEAN_AND::class:
                case PHP_Token_LOGICAL_AND::class:
                case PHP_Token_BOOLEAN_OR::class:
                case PHP_Token_LOGICAL_OR::class:
                case PHP_Token_QUESTION_MARK::class:
                    $this->ccn++;

                    break;
            }
        }

        return $this->ccn;
    }

    /**
     * @return string
     */
    public function getSignature()
    {
        if ($this->signature !== null) {
            return $this->signature;
        }

        if ($this->isAnonymous()) {
            $this->signature = 'anonymousFunction';
            $i               = $this->id + 1;
        } else {
            $this->signature = '';
            $i               = $this->id + 2;
        }

        $tokens = $this->tokenStream->tokens();

        while (isset($tokens[$i]) &&
            !$tokens[$i] instanceof PHP_Token_OPEN_CURLY &&
            !$tokens[$i] instanceof PHP_Token_SEMICOLON) {
            $this->signature .= $tokens[$i++];
        }

        $this->signature = \trim($this->signature);

        return $this->signature;
    }

    /**
     * @return bool
     */
    public function isAnonymous()
    {
        return $this->anonymous;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_NOT_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_MINUS_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_THROW extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NS_C extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DECLARE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOLLAR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DO extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_GT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_TRAIT_C extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PUBLIC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_REQUIRE extends PHP_Token_Includes
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BOOLEAN_AND extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLOSE_BRACKET extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DIV extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ECHO extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLONE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LOGICAL_XOR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EXTENDS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DEC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_COLON extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_USE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LIST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_HALT_COMPILER extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_Stream implements ArrayAccess, Countable, SeekableIterator
{
    /**
     * @var array<string, class-string<PHP_Token>>
     */
    protected static $customTokens = [
        '(' => PHP_Token_OPEN_BRACKET::class,
        ')' => PHP_Token_CLOSE_BRACKET::class,
        '[' => PHP_Token_OPEN_SQUARE::class,
        ']' => PHP_Token_CLOSE_SQUARE::class,
        '{' => PHP_Token_OPEN_CURLY::class,
        '}' => PHP_Token_CLOSE_CURLY::class,
        ';' => PHP_Token_SEMICOLON::class,
        '.' => PHP_Token_DOT::class,
        ',' => PHP_Token_COMMA::class,
        '=' => PHP_Token_EQUAL::class,
        '<' => PHP_Token_LT::class,
        '>' => PHP_Token_GT::class,
        '+' => PHP_Token_PLUS::class,
        '-' => PHP_Token_MINUS::class,
        '*' => PHP_Token_MULT::class,
        '/' => PHP_Token_DIV::class,
        '?' => PHP_Token_QUESTION_MARK::class,
        '!' => PHP_Token_EXCLAMATION_MARK::class,
        ':' => PHP_Token_COLON::class,
        '"' => PHP_Token_DOUBLE_QUOTES::class,
        '@' => PHP_Token_AT::class,
        '&' => PHP_Token_AMPERSAND::class,
        '%' => PHP_Token_PERCENT::class,
        '|' => PHP_Token_PIPE::class,
        '$' => PHP_Token_DOLLAR::class,
        '^' => PHP_Token_CARET::class,
        '~' => PHP_Token_TILDE::class,
        '`' => PHP_Token_BACKTICK::class,
    ];

    /**
     * @var string
     */
    protected $filename;

    /**
     * @var array
     */
    protected $tokens = [];

    /**
     * @var array
     */
    protected $tokensByLine = [];

    /**
     * @var int
     */
    protected $position = 0;

    /**
     * @var array
     */
    protected $linesOfCode = ['loc' => 0, 'cloc' => 0, 'ncloc' => 0];

    /**
     * @var array
     */
    protected $classes;

    /**
     * @var array
     */
    protected $functions;

    /**
     * @var array
     */
    protected $includes;

    /**
     * @var array
     */
    protected $interfaces;

    /**
     * @var array
     */
    protected $traits;

    /**
     * @var array
     */
    protected $lineToFunctionMap = [];

    /**
     * Constructor.
     *
     * @param string $sourceCode
     */
    public function __construct($sourceCode)
    {
        if (\is_file($sourceCode)) {
            $this->filename = $sourceCode;
            $sourceCode     = \file_get_contents($sourceCode);
        }

        $this->scan($sourceCode);
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        $this->tokens       = [];
        $this->tokensByLine = [];
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $buffer = '';

        foreach ($this as $token) {
            $buffer .= $token;
        }

        return $buffer;
    }

    /**
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * @return int
     */
    public function count()
    {
        return \count($this->tokens);
    }

    /**
     * @return PHP_Token[]
     */
    public function tokens()
    {
        return $this->tokens;
    }

    /**
     * @return array
     */
    public function getClasses()
    {
        if ($this->classes !== null) {
            return $this->classes;
        }

        $this->parse();

        return $this->classes;
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        if ($this->functions !== null) {
            return $this->functions;
        }

        $this->parse();

        return $this->functions;
    }

    /**
     * @return array
     */
    public function getInterfaces()
    {
        if ($this->interfaces !== null) {
            return $this->interfaces;
        }

        $this->parse();

        return $this->interfaces;
    }

    /**
     * @return array
     */
    public function getTraits()
    {
        if ($this->traits !== null) {
            return $this->traits;
        }

        $this->parse();

        return $this->traits;
    }

    /**
     * Gets the names of all files that have been included
     * using include(), include_once(), require() or require_once().
     *
     * Parameter $categorize set to TRUE causing this function to return a
     * multi-dimensional array with categories in the keys of the first dimension
     * and constants and their values in the second dimension.
     *
     * Parameter $category allow to filter following specific inclusion type
     *
     * @param bool   $categorize OPTIONAL
     * @param string $category   OPTIONAL Either 'require_once', 'require',
     *                           'include_once', 'include'
     *
     * @return array
     */
    public function getIncludes($categorize = false, $category = null)
    {
        if ($this->includes === null) {
            $this->includes = [
                'require_once' => [],
                'require'      => [],
                'include_once' => [],
                'include'      => [],
            ];

            foreach ($this->tokens as $token) {
                switch (\get_class($token)) {
                    case PHP_Token_REQUIRE_ONCE::class:
                    case PHP_Token_REQUIRE::class:
                    case PHP_Token_INCLUDE_ONCE::class:
                    case PHP_Token_INCLUDE::class:
                        $this->includes[$token->getType()][] = $token->getName();

                        break;
                }
            }
        }

        if (isset($this->includes[$category])) {
            $includes = $this->includes[$category];
        } elseif ($categorize === false) {
            $includes = \array_merge(
                $this->includes['require_once'],
                $this->includes['require'],
                $this->includes['include_once'],
                $this->includes['include']
            );
        } else {
            $includes = $this->includes;
        }

        return $includes;
    }

    /**
     * Returns the name of the function or method a line belongs to.
     *
     * @return string or null if the line is not in a function or method
     */
    public function getFunctionForLine($line)
    {
        $this->parse();

        if (isset($this->lineToFunctionMap[$line])) {
            return $this->lineToFunctionMap[$line];
        }
    }

    /**
     * @return array
     */
    public function getLinesOfCode()
    {
        return $this->linesOfCode;
    }

    public function rewind()/*: void*/
    {
        $this->position = 0;
    }

    /**
     * @return bool
     */
    public function valid()
    {
        return isset($this->tokens[$this->position]);
    }

    /**
     * @return int
     */
    public function key()
    {
        return $this->position;
    }

    /**
     * @return PHP_Token
     */
    public function current()
    {
        return $this->tokens[$this->position];
    }

    public function next()/*: void*/
    {
        $this->position++;
    }

    /**
     * @param int $offset
     *
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->tokens[$offset]);
    }

    /**
     * @param int $offset
     *
     * @throws OutOfBoundsException
     */
    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset)) {
            throw new OutOfBoundsException(
                \sprintf(
                    'No token at position "%s"',
                    $offset
                )
            );
        }

        return $this->tokens[$offset];
    }

    /**
     * @param int $offset
     */
    public function offsetSet($offset, $value)/*: void*/
    {
        $this->tokens[$offset] = $value;
    }

    /**
     * @param int $offset
     *
     * @throws OutOfBoundsException
     */
    public function offsetUnset($offset)/*: void*/
    {
        if (!$this->offsetExists($offset)) {
            throw new OutOfBoundsException(
                \sprintf(
                    'No token at position "%s"',
                    $offset
                )
            );
        }

        unset($this->tokens[$offset]);
    }

    /**
     * Seek to an absolute position.
     *
     * @param int $position
     *
     * @throws OutOfBoundsException
     */
    public function seek($position)/*: void*/
    {
        $this->position = $position;

        if (!$this->valid()) {
            throw new OutOfBoundsException(
                \sprintf(
                    'No token at position "%s"',
                    $this->position
                )
            );
        }
    }

    /**
     * Scans the source for sequences of characters and converts them into a
     * stream of tokens.
     *
     * @param string $sourceCode
     */
    protected function scan($sourceCode)/*: void*/
    {
        $id        = 0;
        $line      = 1;
        $tokens    = \token_get_all($sourceCode);
        $numTokens = \count($tokens);

        $lastNonWhitespaceTokenWasDoubleColon = false;

        $name = null;

        for ($i = 0; $i < $numTokens; ++$i) {
            $token = $tokens[$i];
            $skip  = 0;

            if (\is_array($token)) {
                $name = \substr(\token_name($token[0]), 2);
                $text = $token[1];

                if ($lastNonWhitespaceTokenWasDoubleColon && $name == 'CLASS') {
                    $name = 'CLASS_NAME_CONSTANT';
                } elseif ($name == 'USE' && isset($tokens[$i + 2][0]) && $tokens[$i + 2][0] == \T_FUNCTION) {
                    $name = 'USE_FUNCTION';
                    $text .= $tokens[$i + 1][1] . $tokens[$i + 2][1];
                    $skip = 2;
                }

                /** @var class-string<PHP_Token> $tokenClass */
                $tokenClass = 'PHP_Token_' . $name;
            } else {
                $text       = $token;
                $tokenClass = self::$customTokens[$token];
            }

            /*
             * @see https://github.com/sebastianbergmann/php-token-stream/issues/95
             */
            if (PHP_MAJOR_VERSION >= 8 &&
                $name === 'WHITESPACE' &&                                  // Current token is T_WHITESPACE
                isset($this->tokens[$id - 1]) &&                           // Current token is not the first token
                $this->tokens[$id - 1] instanceof PHP_Token_COMMENT &&     // Previous token is T_COMMENT
                strpos((string) $this->tokens[$id - 1], '/*') === false && // Previous token is comment that starts with '#' or '//'
                strpos($text, "\n") === 0                                  // Text of current token begins with newline
            ) {
                $this->tokens[$id - 1] = new PHP_Token_COMMENT(
                    $this->tokens[$id - 1] . "\n",
                    $this->tokens[$id - 1]->getLine(),
                    $this,
                    $id - 1
                );

                $text = substr($text, 1);

                $line++;

                if (empty($text)) {
                    continue;
                }
            }

            if (!isset($this->tokensByLine[$line])) {
                $this->tokensByLine[$line] = [];
            }

            $token = new $tokenClass($text, $line, $this, $id++);

            $this->tokens[]              = $token;
            $this->tokensByLine[$line][] = $token;

            $line += \substr_count($text, "\n");

            if ($tokenClass == PHP_Token_HALT_COMPILER::class) {
                break;
            }

            if ($name == 'DOUBLE_COLON') {
                $lastNonWhitespaceTokenWasDoubleColon = true;
            } elseif ($name != 'WHITESPACE') {
                $lastNonWhitespaceTokenWasDoubleColon = false;
            }

            $i += $skip;
        }

        foreach ($this->tokens as $token) {
            if (!$token instanceof PHP_Token_COMMENT && !$token instanceof PHP_Token_DOC_COMMENT) {
                continue;
            }

            foreach ($this->tokensByLine[$token->getLine()] as $_token) {
                if (!$_token instanceof PHP_Token_COMMENT && !$_token instanceof PHP_Token_DOC_COMMENT && !$_token instanceof PHP_Token_WHITESPACE) {
                    continue 2;
                }
            }

            $this->linesOfCode['cloc'] += max(1, \substr_count((string) $token, "\n"));
        }

        $this->linesOfCode['loc']   = \substr_count($sourceCode, "\n");
        $this->linesOfCode['ncloc'] = $this->linesOfCode['loc'] -
                                      $this->linesOfCode['cloc'];
    }

    protected function parse()/*: void*/
    {
        $this->interfaces = [];
        $this->classes    = [];
        $this->traits     = [];
        $this->functions  = [];
        $class            = [];
        $classEndLine     = [];
        $trait            = false;
        $traitEndLine     = false;
        $interface        = false;
        $interfaceEndLine = false;

        foreach ($this->tokens as $token) {
            switch (\get_class($token)) {
                case PHP_Token_HALT_COMPILER::class:
                    return;

                case PHP_Token_INTERFACE::class:
                    $interface        = $token->getName();
                    $interfaceEndLine = $token->getEndLine();

                    $this->interfaces[$interface] = [
                        'methods'   => [],
                        'parent'    => $token->getParent(),
                        'keywords'  => $token->getKeywords(),
                        'docblock'  => $token->getDocblock(),
                        'startLine' => $token->getLine(),
                        'endLine'   => $interfaceEndLine,
                        'package'   => $token->getPackage(),
                        'file'      => $this->filename,
                    ];

                    break;

                case PHP_Token_CLASS::class:
                case PHP_Token_TRAIT::class:
                    $tmp = [
                        'methods'   => [],
                        'parent'    => $token->getParent(),
                        'interfaces'=> $token->getInterfaces(),
                        'keywords'  => $token->getKeywords(),
                        'docblock'  => $token->getDocblock(),
                        'startLine' => $token->getLine(),
                        'endLine'   => $token->getEndLine(),
                        'package'   => $token->getPackage(),
                        'file'      => $this->filename,
                    ];

                    if ($token instanceof PHP_Token_CLASS) {
                        $class[]        = $token->getName();
                        $classEndLine[] = $token->getEndLine();

                        if ($token->getName() !== null) {
                            $this->classes[$class[\count($class) - 1]] = $tmp;
                        }
                    } else {
                        $trait                = $token->getName();
                        $traitEndLine         = $token->getEndLine();
                        $this->traits[$trait] = $tmp;
                    }

                    break;

                case PHP_Token_FUNCTION::class:
                    $name = $token->getName();
                    $tmp  = [
                        'docblock'  => $token->getDocblock(),
                        'keywords'  => $token->getKeywords(),
                        'visibility'=> $token->getVisibility(),
                        'signature' => $token->getSignature(),
                        'startLine' => $token->getLine(),
                        'endLine'   => $token->getEndLine(),
                        'ccn'       => $token->getCCN(),
                        'file'      => $this->filename,
                    ];

                    if (empty($class) &&
                        $trait === false &&
                        $interface === false) {
                        $this->functions[$name] = $tmp;

                        $this->addFunctionToMap(
                            $name,
                            $tmp['startLine'],
                            $tmp['endLine']
                        );
                    } elseif (!empty($class)) {
                        if ($class[\count($class) - 1] !== null) {
                            $this->classes[$class[\count($class) - 1]]['methods'][$name] = $tmp;

                            $this->addFunctionToMap(
                                $class[\count($class) - 1] . '::' . $name,
                                $tmp['startLine'],
                                $tmp['endLine']
                            );
                        }
                    } elseif ($trait !== false) {
                        $this->traits[$trait]['methods'][$name] = $tmp;

                        $this->addFunctionToMap(
                            $trait . '::' . $name,
                            $tmp['startLine'],
                            $tmp['endLine']
                        );
                    } else {
                        $this->interfaces[$interface]['methods'][$name] = $tmp;
                    }

                    break;

                case PHP_Token_CLOSE_CURLY::class:
                    if (!empty($classEndLine) &&
                        $classEndLine[\count($classEndLine) - 1] == $token->getLine()) {
                        \array_pop($classEndLine);
                        \array_pop($class);
                    } elseif ($traitEndLine !== false &&
                        $traitEndLine == $token->getLine()) {
                        $trait        = false;
                        $traitEndLine = false;
                    } elseif ($interfaceEndLine !== false &&
                        $interfaceEndLine == $token->getLine()) {
                        $interface        = false;
                        $interfaceEndLine = false;
                    }

                    break;
            }
        }
    }

    /**
     * @param string $name
     * @param int    $startLine
     * @param int    $endLine
     */
    private function addFunctionToMap($name, $startLine, $endLine): void
    {
        for ($line = $startLine; $line <= $endLine; $line++) {
            $this->lineToFunctionMap[$line] = $name;
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DOLLAR_OPEN_CURLY_BRACES extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PRINT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IF extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
abstract class PHP_TokenWithScopeAndVisibility extends PHP_TokenWithScope
{
    /**
     * @return string
     */
    public function getVisibility()
    {
        $tokens = $this->tokenStream->tokens();

        for ($i = $this->id - 2; $i > $this->id - 7; $i -= 2) {
            if (isset($tokens[$i]) &&
                ($tokens[$i] instanceof PHP_Token_PRIVATE ||
                    $tokens[$i] instanceof PHP_Token_PROTECTED ||
                    $tokens[$i] instanceof PHP_Token_PUBLIC)) {
                return \strtolower(
                    \str_replace('PHP_Token_', '', PHP_Token_Util::getClass($tokens[$i]))
                );
            }

            if (isset($tokens[$i]) &&
                !($tokens[$i] instanceof PHP_Token_STATIC ||
                    $tokens[$i] instanceof PHP_Token_FINAL ||
                    $tokens[$i] instanceof PHP_Token_ABSTRACT)) {
                // no keywords; stop visibility search
                break;
            }
        }
    }

    /**
     * @return string
     */
    public function getKeywords()
    {
        $keywords = [];
        $tokens   = $this->tokenStream->tokens();

        for ($i = $this->id - 2; $i > $this->id - 7; $i -= 2) {
            if (isset($tokens[$i]) &&
                ($tokens[$i] instanceof PHP_Token_PRIVATE ||
                    $tokens[$i] instanceof PHP_Token_PROTECTED ||
                    $tokens[$i] instanceof PHP_Token_PUBLIC)) {
                continue;
            }

            if (isset($tokens[$i]) &&
                ($tokens[$i] instanceof PHP_Token_STATIC ||
                    $tokens[$i] instanceof PHP_Token_FINAL ||
                    $tokens[$i] instanceof PHP_Token_ABSTRACT)) {
                $keywords[] = \strtolower(
                    \str_replace('PHP_Token_', '', PHP_Token_Util::getClass($tokens[$i]))
                );
            }
        }

        return \implode(',', $keywords);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NS_SEPARATOR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_MINUS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OPEN_TAG_WITH_ECHO extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OPEN_SQUARE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OBJECT_OPERATOR extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OPEN_BRACKET extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_USE_FUNCTION extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CHARACTER extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PRIVATE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_UNSET_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_STRING_VARNAME extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CARET extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_POW extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ELLIPSIS extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FN extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_XOR_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NAMESPACE extends PHP_TokenWithScope
{
    /**
     * @return string
     */
    public function getName()
    {
        $tokens    = $this->tokenStream->tokens();
        $namespace = (string) $tokens[$this->id + 2];

        for ($i = $this->id + 3;; $i += 2) {
            if (isset($tokens[$i]) &&
                $tokens[$i] instanceof PHP_Token_NS_SEPARATOR) {
                $namespace .= '\\' . $tokens[$i + 1];
            } else {
                break;
            }
        }

        return $namespace;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NAME_QUALIFIED extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SWITCH extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FOREACH extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_COMMENT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INCLUDE_ONCE extends PHP_Token_Includes
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NEW extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INT_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_STRING extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_END_HEREDOC extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLASS_C extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_OR_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EXIT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
abstract class PHP_Token_Includes extends PHP_Token
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $type;

    /**
     * @return string
     */
    public function getName()
    {
        if ($this->name === null) {
            $this->process();
        }

        return $this->name;
    }

    /**
     * @return string
     */
    public function getType()
    {
        if ($this->type === null) {
            $this->process();
        }

        return $this->type;
    }

    private function process(): void
    {
        $tokens = $this->tokenStream->tokens();

        if ($tokens[$this->id + 2] instanceof PHP_Token_CONSTANT_ENCAPSED_STRING) {
            $this->name = \trim((string) $tokens[$this->id + 2], "'\"");
            $this->type = \strtolower(
                \str_replace('PHP_Token_', '', PHP_Token_Util::getClass($tokens[$this->id]))
            );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_GREATER_OR_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_NAME_RELATIVE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
final class PHP_Token_Util
{
    public static function getClass($object): string
    {
        $parts = \explode('\\', \get_class($object));

        return \array_pop($parts);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BOOL_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_WHITESPACE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ELSE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LNUMBER extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENCAPSED_AND_WHITESPACE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_IS_IDENTICAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_Stream_CachingFactory
{
    /**
     * @var array
     */
    protected static $cache = [];

    /**
     * @param string $filename
     *
     * @return PHP_Token_Stream
     */
    public static function get($filename)
    {
        if (!isset(self::$cache[$filename])) {
            self::$cache[$filename] = new PHP_Token_Stream($filename);
        }

        return self::$cache[$filename];
    }

    /**
     * @param string $filename
     */
    public static function clear($filename = null)/*: void*/
    {
        if (\is_string($filename)) {
            unset(self::$cache[$filename]);
        } else {
            self::$cache = [];
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CONCAT_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_TRY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_WHILE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BAD_CHARACTER extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BREAK extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_INLINE_HTML extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PIPE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_MUL_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_SEMICOLON extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ISSET extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_STRING_CAST extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_FINALLY extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_QUESTION_MARK extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_MULT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ENDFOREACH extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_LINE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_EXCLAMATION_MARK extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_METHOD_C extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_DEFAULT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_TRAIT extends PHP_Token_INTERFACE
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_COALESCE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_TILDE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PERCENT extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_ELSEIF extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_BACKTICK extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_PLUS_EQUAL extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_CLOSE_SQUARE extends PHP_Token
{
}
<?php declare(strict_types=1);
/*
 * This file is part of phpunit/php-token-stream.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
class PHP_Token_MOD_EQUAL extends PHP_Token
{
}
# Changes in PHPUnit 8.5

All notable changes of the PHPUnit 8.5 release series are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.

## [8.5.32] - 2023-01-26

### Fixed

* [#5120](https://github.com/sebastianbergmann/phpunit/issues/5120): Test Runner incorrectly treats `--testsuite` and `--list-tests` as not combinable options

## [8.5.31] - 2022-10-28

### Fixed

* [#5076](https://github.com/sebastianbergmann/phpunit/issues/5076): Test Runner does not warn about conflicting options

## [8.5.30] - 2022-09-25

### Changed

* The configuration generator now asks for a cache directory

### Fixed

* [#4913](https://github.com/sebastianbergmann/phpunit/issues/4913): Failed `assert()` should show a backtrace
* [#4966](https://github.com/sebastianbergmann/phpunit/issues/4966): `TestCase::assertSame()` (and related exact comparisons) must compare `float` exactly

## [8.5.29] - 2022-08-22

### Changed

* [#5033](https://github.com/sebastianbergmann/phpunit/issues/5033): Do not depend on phpspec/prophecy

## [8.5.28] - 2022-07-29

### Fixed

* [#5015](https://github.com/sebastianbergmann/phpunit/pull/5015): Ukraine banner unreadable on black background
* [#5016](https://github.com/sebastianbergmann/phpunit/issues/5016): PHPUnit 8.5.27 does not work on PHP 7.2.0-7.2.18 and PHP 7.3.0-7.3.5

## [8.5.27] - 2022-06-19

### Fixed

* [#4950](https://github.com/sebastianbergmann/phpunit/issues/4950): False error on `atMost()` invocation rule without call
* [#4962](https://github.com/sebastianbergmann/phpunit/issues/4962): Ukraine banner unreadable on white background

## [8.5.26] - 2022-04-01

### Fixed

* [#4938](https://github.com/sebastianbergmann/phpunit/issues/4938): Test Double code generator does not handle `void` return type declaration on `__clone()` methods

## [8.5.25] - 2022-03-16

### Fixed

* [#4934](https://github.com/sebastianbergmann/phpunit/issues/4934): Code Coverage does not work with PHPUnit 8.5.24 PHAR on PHP 7

## [8.5.24] - 2022-03-05 - #StandWithUkraine

### Changed

* [#4874](https://github.com/sebastianbergmann/phpunit/pull/4874): `PHP_FLOAT_EPSILON` is now used instead of hardcoded `0.0000000001` in `PHPUnit\Framework\Constraint\IsIdentical`

### Fixed

* When the HTML code coverage report's configured low upper bound is larger than the high lower bound then the default values are used instead

## [8.5.23] - 2022-01-21

### Fixed

* [#4799](https://github.com/sebastianbergmann/phpunit/pull/4799): Memory leaks in `PHPUnit\Framework\TestSuite` class
* [#4857](https://github.com/sebastianbergmann/phpunit/pull/4857): Result of `debug_backtrace()` is not used correctly

## [8.5.22] - 2021-12-25

### Changed

* [#4812](https://github.com/sebastianbergmann/phpunit/issues/4812): Do not enforce time limits when a debugging session through DBGp is active
* [#4835](https://github.com/sebastianbergmann/phpunit/issues/4835): Support for `$GLOBALS['_composer_autoload_path']` introduced in Composer 2.2

### Fixed

* [#4840](https://github.com/sebastianbergmann/phpunit/pull/4840): TestDox prettifying for class names does not correctly handle diacritics
* [#4846](https://github.com/sebastianbergmann/phpunit/pull/4846): Composer proxy script is not ignored

## [8.5.21] - 2021-09-25

### Changed

* PHPUnit no longer converts PHP deprecations to exceptions by default (configure `convertDeprecationsToExceptions="true"` to enable this)
* The PHPUnit XML configuration file generator now configures `convertDeprecationsToExceptions="true"`

### Fixed

* [#4772](https://github.com/sebastianbergmann/phpunit/pull/4772): TestDox HTML report not displayed correctly when browser has custom colour settings

## [8.5.20] - 2021-08-31

### Fixed

* [#4751](https://github.com/sebastianbergmann/phpunit/issues/4751): Configuration validation fails when using brackets in glob pattern

## [8.5.19] - 2021-07-31

### Fixed

* [#4740](https://github.com/sebastianbergmann/phpunit/issues/4740): `phpunit.phar` does not work with PHP 8.1

## [8.5.18] - 2021-07-19

### Fixed

* [#4720](https://github.com/sebastianbergmann/phpunit/issues/4720): PHPUnit does not verify its own PHP extension requirements

## [8.5.17] - 2021-06-23

### Changed

* PHPUnit now errors out on startup when `PHP_VERSION` contains a value that is not compatible with `version_compare()`, for instance `X.Y.Z-(to be removed in future macOS)`

## [8.5.16] - 2021-06-05

### Changed

* The test result cache (the storage for which is implemented in `PHPUnit\Runner\DefaultTestResultCache`) no longer uses PHP's `serialize()` and `unserialize()` functions for persistence. It now uses a versioned JSON format instead that is independent of PHP implementation details (see [#3581](https://github.com/sebastianbergmann/phpunit/issues/3581) and [#4662](https://github.com/sebastianbergmann/phpunit/pull/4662) for examples why this is a problem). When PHPUnit tries to load the test result cache from a file that does not exist, or from a file that does not contain data in JSON format, or from a file that contains data in a JSON format version other than the one used by the currently running PHPUnit version, then this is considered to be a "cache miss". An empty `DefaultTestResultCache` object is created in this case. This should also prevent PHPUnit from crashing when trying to load a test result cache file created by a different version of PHPUnit (see [#4580](https://github.com/sebastianbergmann/phpunit/issues/4580) for example).

### Fixed

* [#4663](https://github.com/sebastianbergmann/phpunit/issues/4663): `TestCase::expectError()` works on PHP 7.3, but not on PHP >= 7.4
* [#4678](https://github.com/sebastianbergmann/phpunit/pull/4678): Stubbed methods with `iterable` return types should return empty array by default
* [#4692](https://github.com/sebastianbergmann/phpunit/issues/4692): Annotations in single-line doc-comments are not handled correctly
* [#4694](https://github.com/sebastianbergmann/phpunit/issues/4694): `TestCase::getMockFromWsdl()` does not work with PHP 8.1-dev

## [8.5.15] - 2021-03-17

### Fixed

* [#4591](https://github.com/sebastianbergmann/phpunit/issues/4591): TeamCity logger logs warnings as test failures

## [8.5.14] - 2021-01-17

### Fixed

* [#4535](https://github.com/sebastianbergmann/phpunit/issues/4535): `getMockFromWsdl()` does not handle methods that do not have parameters correctly
* [#4572](https://github.com/sebastianbergmann/phpunit/issues/4572): Schema validation does not work with `%xx` sequences in path to `phpunit.xsd`
* [#4575](https://github.com/sebastianbergmann/phpunit/issues/4575): PHPUnit 8.5 incompatibility with PHP 8.1

## [8.5.13] - 2020-12-01

### Fixed

* Running tests in isolated processes did not work with PHP 8 on Windows

## [8.5.12] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.2` to `>=7.2` to allow the installation of PHPUnit 8.5 on PHP 8. Please note that the code coverage functionality is not available for PHPUnit 8.5 on PHP 8.

### Fixed

* [#4529](https://github.com/sebastianbergmann/phpunit/issues/4529): Debug mode of Xdebug 2 is not disabled for PHPT tests

## [8.5.11] - 2020-11-27

### Changed

* Bumped required version of `phpunit/php-code-coverage`

## [8.5.10] - 2020-11-27

### Added

* Support for Xdebug 3

### Fixed

* [#4516](https://github.com/sebastianbergmann/phpunit/issues/4516): `phpunit/phpunit-selenium` does not work with PHPUnit 8.5.9

## [8.5.9] - 2020-11-10

### Fixed

* [#3965](https://github.com/sebastianbergmann/phpunit/issues/3965): Process Isolation throws exceptions when PHPDBG is used
* [#4470](https://github.com/sebastianbergmann/phpunit/pull/4470): Infinite recursion when `--static-backup --strict-global-state` is used

## [8.5.8] - 2020-06-22

### Fixed

* [#4312](https://github.com/sebastianbergmann/phpunit/issues/4312): Fix for [#4299](https://github.com/sebastianbergmann/phpunit/issues/4299) breaks backward compatibility

## [8.5.7] - 2020-06-21

### Fixed

* [#4299](https://github.com/sebastianbergmann/phpunit/issues/4299): "No tests executed" does not always result in exit code `1`
* [#4306](https://github.com/sebastianbergmann/phpunit/issues/4306): Exceptions during code coverage driver initialization are not handled correctly

## [8.5.6] - 2020-06-15

### Fixed

* [#4211](https://github.com/sebastianbergmann/phpunit/issues/4211): `phpdbg_*()` functions are scoped to `PHPUnit\phpdbg_*()`

## [8.5.5] - 2020-05-22

### Fixed

* [#4033](https://github.com/sebastianbergmann/phpunit/issues/4033): Unexpected behaviour when `$GLOBALS` is deleted

## [8.5.4] - 2020-04-23

### Changed

* Changed how `PHPUnit\TextUI\Command` passes warnings to `PHPUnit\TextUI\TestRunner`

## [8.5.3] - 2020-03-31

### Fixed

* [#4017](https://github.com/sebastianbergmann/phpunit/issues/4017): Do not suggest refactoring to something that is also deprecated
* [#4133](https://github.com/sebastianbergmann/phpunit/issues/4133): `expectExceptionMessageRegExp()` has been removed in PHPUnit 9 without a deprecation warning being given in PHPUnit 8
* [#4139](https://github.com/sebastianbergmann/phpunit/issues/4139): Cannot double interfaces that declare a constructor with PHP 8
* [#4144](https://github.com/sebastianbergmann/phpunit/issues/4144): Empty objects are converted to empty arrays in JSON comparison failure diff

## [8.5.2] - 2020-01-08

### Removed

* `eval-stdin.php` has been removed, it was not used anymore since PHPUnit 7.2.7

## [8.5.1] - 2019-12-25

### Changed

* `eval-stdin.php` can now only be executed with `cli` and `phpdbg`

### Fixed

* [#3983](https://github.com/sebastianbergmann/phpunit/issues/3983): Deprecation warning given too eagerly

## [8.5.0] - 2019-12-06

### Added

* [#3911](https://github.com/sebastianbergmann/phpunit/issues/3911): Support combined use of `addMethods()` and `onlyMethods()`
* [#3949](https://github.com/sebastianbergmann/phpunit/issues/3949): Introduce specialized assertions `assertFileEqualsCanonicalizing()`, `assertFileEqualsIgnoringCase()`, `assertStringEqualsFileCanonicalizing()`, `assertStringEqualsFileIgnoringCase()`, `assertFileNotEqualsCanonicalizing()`, `assertFileNotEqualsIgnoringCase()`, `assertStringNotEqualsFileCanonicalizing()`, and `assertStringNotEqualsFileIgnoringCase()` as alternative to using `assertFileEquals()` etc. with optional parameters

### Changed

* [#3860](https://github.com/sebastianbergmann/phpunit/pull/3860): Deprecate invoking PHPUnit commandline test runner with just a class name
* [#3950](https://github.com/sebastianbergmann/phpunit/issues/3950): Deprecate optional parameters of `assertFileEquals()` etc.
* [#3955](https://github.com/sebastianbergmann/phpunit/issues/3955): Deprecate support for doubling multiple interfaces

### Fixed

* [#3953](https://github.com/sebastianbergmann/phpunit/issues/3953): Code Coverage for test executed in isolation does not work when the PHAR is used
* [#3967](https://github.com/sebastianbergmann/phpunit/issues/3967): Cannot double interface that extends interface that extends `\Throwable`
* [#3968](https://github.com/sebastianbergmann/phpunit/pull/3968): Test class run in a separate PHP process are passing when `exit` called inside

[8.5.32]: https://github.com/sebastianbergmann/phpunit/compare/8.5.31...8.5.32
[8.5.31]: https://github.com/sebastianbergmann/phpunit/compare/8.5.30...8.5.31
[8.5.30]: https://github.com/sebastianbergmann/phpunit/compare/8.5.29...8.5.30
[8.5.29]: https://github.com/sebastianbergmann/phpunit/compare/8.5.28...8.5.29
[8.5.28]: https://github.com/sebastianbergmann/phpunit/compare/8.5.27...8.5.28
[8.5.27]: https://github.com/sebastianbergmann/phpunit/compare/8.5.26...8.5.27
[8.5.26]: https://github.com/sebastianbergmann/phpunit/compare/8.5.25...8.5.26
[8.5.25]: https://github.com/sebastianbergmann/phpunit/compare/8.5.24...8.5.25
[8.5.24]: https://github.com/sebastianbergmann/phpunit/compare/8.5.23...8.5.24
[8.5.23]: https://github.com/sebastianbergmann/phpunit/compare/8.5.22...8.5.23
[8.5.22]: https://github.com/sebastianbergmann/phpunit/compare/8.5.21...8.5.22
[8.5.21]: https://github.com/sebastianbergmann/phpunit/compare/8.5.20...8.5.21
[8.5.20]: https://github.com/sebastianbergmann/phpunit/compare/8.5.19...8.5.20
[8.5.19]: https://github.com/sebastianbergmann/phpunit/compare/8.5.18...8.5.19
[8.5.18]: https://github.com/sebastianbergmann/phpunit/compare/8.5.17...8.5.18
[8.5.17]: https://github.com/sebastianbergmann/phpunit/compare/8.5.16...8.5.17
[8.5.16]: https://github.com/sebastianbergmann/phpunit/compare/8.5.15...8.5.16
[8.5.15]: https://github.com/sebastianbergmann/phpunit/compare/8.5.14...8.5.15
[8.5.14]: https://github.com/sebastianbergmann/phpunit/compare/8.5.13...8.5.14
[8.5.13]: https://github.com/sebastianbergmann/phpunit/compare/8.5.12...8.5.13
[8.5.12]: https://github.com/sebastianbergmann/phpunit/compare/8.5.11...8.5.12
[8.5.11]: https://github.com/sebastianbergmann/phpunit/compare/8.5.10...8.5.11
[8.5.10]: https://github.com/sebastianbergmann/phpunit/compare/8.5.9...8.5.10
[8.5.9]: https://github.com/sebastianbergmann/phpunit/compare/8.5.8...8.5.9
[8.5.8]: https://github.com/sebastianbergmann/phpunit/compare/8.5.7...8.5.8
[8.5.7]: https://github.com/sebastianbergmann/phpunit/compare/8.5.6...8.5.7
[8.5.6]: https://github.com/sebastianbergmann/phpunit/compare/8.5.5...8.5.6
[8.5.5]: https://github.com/sebastianbergmann/phpunit/compare/8.5.4...8.5.5
[8.5.4]: https://github.com/sebastianbergmann/phpunit/compare/8.5.3...8.5.4
[8.5.3]: https://github.com/sebastianbergmann/phpunit/compare/8.5.2...8.5.3
[8.5.2]: https://github.com/sebastianbergmann/phpunit/compare/8.5.1...8.5.2
[8.5.1]: https://github.com/sebastianbergmann/phpunit/compare/8.5.0...8.5.1
[8.5.0]: https://github.com/sebastianbergmann/phpunit/compare/8.4.3...8.5.0
BSD 3-Clause License

Copyright (c) 2001-2023, Sebastian Bergmann
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. 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.

3. Neither the name of the copyright holder 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 HOLDER OR 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.
<?php
namespace PHPSTORM_META {

    override(
        \PHPUnit\Framework\TestCase::createMock(0),
        map([""=>"$0"])
    );

    override(
        \PHPUnit\Framework\TestCase::createStub(0),
        map([""=>"$0"])
    );

    override(
        \PHPUnit\Framework\TestCase::createConfiguredMock(0),
        map([""=>"$0"])
    );

    override(
        \PHPUnit\Framework\TestCase::createPartialMock(0),
        map([""=>"$0"])
    );

    override(
        \PHPUnit\Framework\TestCase::createTestProxy(0),
        map([""=>"$0"])
    );

    override(
        \PHPUnit\Framework\TestCase::getMockForAbstractClass(0),
        map([""=>"$0"])
    );
}
<h1 align="center">🇺🇦 <a href="https://phpunit.de/stand-with-ukraine.html">UKRAINE NEEDS YOUR HELP NOW!</a></h1>

# PHPUnit

[![Latest Stable Version](https://poser.pugx.org/phpunit/phpunit/v/stable.png)](https://packagist.org/packages/phpunit/phpunit)
[![CI Status](https://github.com/sebastianbergmann/phpunit/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/phpunit/actions)
[![Type Coverage](https://shepherd.dev/github/sebastianbergmann/phpunit/coverage.svg)](https://shepherd.dev/github/sebastianbergmann/phpunit)
[![codecov](https://codecov.io/gh/sebastianbergmann/phpunit/branch/8.5/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/phpunit)

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.

## Installation

We distribute a [PHP Archive (PHAR)](https://php.net/phar) that has all required (as well as some optional) dependencies of PHPUnit bundled in a single file:

```bash
$ wget https://phar.phpunit.de/phpunit-X.Y.phar

$ php phpunit-X.Y.phar --version
```

Please replace `X.Y` with the version of PHPUnit you are interested in.

Alternatively, you may use [Composer](https://getcomposer.org/) to download and install PHPUnit as well as its dependencies. Please refer to the "[Getting Started](https://phpunit.de/getting-started-with-phpunit.html)" guide for details on how to install PHPUnit.

## Contribute

Please refer to [CONTRIBUTING.md](https://github.com/sebastianbergmann/phpunit/blob/master/.github/CONTRIBUTING.md) for information on how to contribute to PHPUnit and its related projects.

## List of Contributors

Thanks to everyone who has contributed to PHPUnit! You can find a detailed list of contributors on every PHPUnit related package on GitHub. This list shows only the major components:

* [PHPUnit](https://github.com/sebastianbergmann/phpunit/graphs/contributors)
* [php-code-coverage](https://github.com/sebastianbergmann/php-code-coverage/graphs/contributors)

A very special thanks to everyone who has contributed to the documentation and helps maintain the translations:

* [English](https://github.com/sebastianbergmann/phpunit-documentation-english/graphs/contributors)
* [Spanish](https://github.com/sebastianbergmann/phpunit-documentation-spanish/graphs/contributors)
* [French](https://github.com/sebastianbergmann/phpunit-documentation-french/graphs/contributors)
* [Japanese](https://github.com/sebastianbergmann/phpunit-documentation-japanese/graphs/contributors)
* [Brazilian Portuguese](https://github.com/sebastianbergmann/phpunit-documentation-brazilian-portuguese/graphs/contributors)
* [Simplified Chinese](https://github.com/sebastianbergmann/phpunit-documentation-chinese/graphs/contributors)

#!/usr/bin/env php
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (!version_compare(PHP_VERSION, PHP_VERSION, '=')) {
    fwrite(
        STDERR,
        sprintf(
            '%s declares an invalid value for PHP_VERSION.' . PHP_EOL .
            'This breaks fundamental functionality such as version_compare().' . PHP_EOL .
            'Please use a different PHP interpreter.' . PHP_EOL,

            PHP_BINARY
        )
    );

    die(1);
}

if (version_compare('7.2.0', PHP_VERSION, '>')) {
    fwrite(
        STDERR,
        sprintf(
            'This version of PHPUnit requires PHP >= 7.2.' . PHP_EOL .
            'You are using PHP %s (%s).' . PHP_EOL,
            PHP_VERSION,
            PHP_BINARY
        )
    );

    die(1);
}

foreach (['dom', 'json', 'libxml', 'mbstring', 'tokenizer', 'xml', 'xmlwriter'] as $extension) {
    if (extension_loaded($extension)) {
        continue;
    }

    fwrite(
        STDERR,
        sprintf(
            'PHPUnit requires the "%s" extension.' . PHP_EOL,
            $extension
        )
    );

    die(1);
}

if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}

if (isset($GLOBALS['_composer_autoload_path'])) {
    define('PHPUNIT_COMPOSER_INSTALL', $GLOBALS['_composer_autoload_path']);

    unset($GLOBALS['_composer_autoload_path']);
} else {
    foreach (array(__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
        if (file_exists($file)) {
            define('PHPUNIT_COMPOSER_INSTALL', $file);

            break;
        }
    }

    unset($file);
}

if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
    fwrite(
        STDERR,
        'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
        '    composer install' . PHP_EOL . PHP_EOL .
        'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
    );

    die(1);
}

$options = getopt('', array('prepend:'));

if (isset($options['prepend'])) {
    require $options['prepend'];
}

unset($options);

require PHPUNIT_COMPOSER_INSTALL;

PHPUnit\TextUI\Command::main();
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:annotation>
        <xs:documentation source="https://phpunit.de/documentation.html">
            This Schema file defines the rules by which the XML configuration file of PHPUnit 8.5 may be structured.
        </xs:documentation>
        <xs:appinfo source="https://phpunit.de/documentation.html"/>
    </xs:annotation>
    <xs:element name="phpunit" type="phpUnitType">
        <xs:annotation>
            <xs:documentation>Root Element</xs:documentation>
        </xs:annotation>
    </xs:element>
    <xs:complexType name="filtersType">
        <xs:sequence>
            <xs:element name="whitelist" type="whiteListType" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="filterType">
        <xs:sequence>
            <xs:choice maxOccurs="unbounded" minOccurs="0">
                <xs:group ref="pathGroup"/>
                <xs:element name="exclude">
                    <xs:complexType>
                        <xs:group ref="pathGroup"/>
                    </xs:complexType>
                </xs:element>
            </xs:choice>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="whiteListType">
        <xs:complexContent>
            <xs:extension base="filterType">
                <xs:attribute name="addUncoveredFilesFromWhitelist" default="true" type="xs:boolean"/>
                <xs:attribute name="processUncoveredFilesFromWhitelist" default="false" type="xs:boolean"/>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    <xs:complexType name="groupsType">
        <xs:choice>
            <xs:sequence>
                <xs:element name="include" type="groupType"/>
                <xs:element name="exclude" type="groupType" minOccurs="0"/>
            </xs:sequence>
            <xs:sequence>
                <xs:element name="exclude" type="groupType"/>
            </xs:sequence>
        </xs:choice>
    </xs:complexType>
    <xs:complexType name="groupType">
        <xs:sequence>
            <xs:element name="group" type="xs:string" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="extensionsType">
        <xs:sequence>
            <xs:element name="extension" type="objectType" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="listenersType">
        <xs:sequence>
            <xs:element name="listener" type="objectType" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="objectType">
        <xs:sequence>
            <xs:element name="arguments" minOccurs="0">
                <xs:complexType>
                    <xs:group ref="argumentsGroup"/>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
        <xs:attribute name="class" type="xs:string" use="required"/>
        <xs:attribute name="file" type="xs:anyURI"/>
    </xs:complexType>
    <xs:complexType name="arrayType">
        <xs:sequence>
            <xs:element name="element" type="argumentType" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="argumentType">
        <xs:group ref="argumentChoice"/>
        <xs:attribute name="key" use="required"/>
    </xs:complexType>
    <xs:group name="argumentsGroup">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="array" type="arrayType" />
                <xs:element name="integer" type="xs:integer" />
                <xs:element name="string" type="xs:string" />
                <xs:element name="double" type="xs:double" />
                <xs:element name="null" />
                <xs:element name="object" type="objectType" />
                <xs:element name="file" type="xs:anyURI" />
                <xs:element name="directory" type="xs:anyURI" />
                <xs:element name="boolean" type="xs:boolean" />
            </xs:choice>
        </xs:sequence>
    </xs:group>
    <xs:group name="argumentChoice">
        <xs:choice>
            <xs:element name="array" type="arrayType" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="integer" type="xs:integer" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="string" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="double" type="xs:double" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="null" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="object" type="objectType" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="file" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="directory" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element name="boolean" type="xs:boolean" minOccurs="0" maxOccurs="unbounded"/>
        </xs:choice>
    </xs:group>
    <xs:simpleType name="columnsType">
        <xs:union>
            <xs:simpleType>
                <xs:restriction base="xs:integer"/>
            </xs:simpleType>
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="max"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>
    <xs:complexType name="loggersType">
        <xs:sequence>
            <xs:element name="log" type="loggerType" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="loggerType">
        <xs:attribute name="type">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="coverage-html"/>
                    <xs:enumeration value="coverage-text"/>
                    <xs:enumeration value="coverage-clover"/>
                    <xs:enumeration value="coverage-crap4j"/>
                    <xs:enumeration value="coverage-xml"/>
                    <xs:enumeration value="coverage-php"/>
                    <xs:enumeration value="json"/>
                    <xs:enumeration value="plain"/>
                    <xs:enumeration value="tap"/>
                    <xs:enumeration value="teamcity"/>
                    <xs:enumeration value="junit"/>
                    <xs:enumeration value="testdox-html"/>
                    <xs:enumeration value="testdox-text"/>
                    <xs:enumeration value="testdox-xml"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:attribute>
        <xs:attribute name="target" type="xs:anyURI"/>
        <xs:attribute name="lowUpperBound" type="xs:nonNegativeInteger" default="50"/>
        <xs:attribute name="highLowerBound" type="xs:nonNegativeInteger" default="90"/>
        <xs:attribute name="showUncoveredFiles" type="xs:boolean" default="false"/>
        <xs:attribute name="showOnlySummary" type="xs:boolean" default="false"/>
        <xs:attribute name="threshold" type="xs:nonNegativeInteger" default="30"/>
    </xs:complexType>
    <xs:group name="pathGroup">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="directory" type="directoryFilterType"/>
                <xs:element name="file" type="fileFilterType"/>
            </xs:choice>
        </xs:sequence>
    </xs:group>
    <xs:complexType name="directoryFilterType">
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute type="xs:string" name="prefix" default=""/>
                <xs:attribute type="xs:string" name="suffix" default="Test.php"/>
                <xs:attributeGroup ref="phpVersionGroup"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
    <xs:simpleType name="executionOrderType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="default"/>
            <xs:enumeration value="defects"/>
            <xs:enumeration value="depends"/>
            <xs:enumeration value="depends,defects"/>
            <xs:enumeration value="depends,duration"/>
            <xs:enumeration value="depends,random"/>
            <xs:enumeration value="depends,reverse"/>
            <xs:enumeration value="depends,size"/>
            <xs:enumeration value="duration"/>
            <xs:enumeration value="no-depends"/>
            <xs:enumeration value="no-depends,defects"/>
            <xs:enumeration value="no-depends,duration"/>
            <xs:enumeration value="no-depends,random"/>
            <xs:enumeration value="no-depends,reverse"/>
            <xs:enumeration value="no-depends,size"/>
            <xs:enumeration value="random"/>
            <xs:enumeration value="reverse"/>
            <xs:enumeration value="size"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:complexType name="fileFilterType">
        <xs:simpleContent>
            <xs:extension base="xs:anyURI">
                <xs:attributeGroup ref="phpVersionGroup"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
    <xs:attributeGroup name="phpVersionGroup">
        <xs:attribute name="phpVersion" type="xs:string" default="5.3.0"/>
        <xs:attribute name="phpVersionOperator" type="xs:string" default="&gt;="/>
    </xs:attributeGroup>
    <xs:complexType name="phpType">
        <xs:sequence>
            <xs:choice maxOccurs="unbounded">
                <xs:element name="includePath" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="ini" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="const" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="var" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="env" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="post" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="get" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="cookie" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="server" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="files" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="request" type="namedValueType" minOccurs="0" maxOccurs="unbounded"/>
            </xs:choice>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="namedValueType">
        <xs:attribute name="name" use="required" type="xs:string"/>
        <xs:attribute name="value" use="required" type="xs:anySimpleType"/>
        <xs:attribute name="verbatim" use="optional" type="xs:boolean"/>
        <xs:attribute name="force" use="optional" type="xs:boolean"/>
    </xs:complexType>
    <xs:complexType name="phpUnitType">
        <xs:annotation>
            <xs:documentation>The main type specifying the document structure</xs:documentation>
        </xs:annotation>
        <xs:group ref="configGroup"/>
        <xs:attributeGroup ref="configAttributeGroup"/>
    </xs:complexType>
    <xs:attributeGroup name="configAttributeGroup">
        <xs:attribute name="backupGlobals" type="xs:boolean" default="false"/>
        <xs:attribute name="backupStaticAttributes" type="xs:boolean" default="false"/>
        <xs:attribute name="bootstrap" type="xs:anyURI"/>
        <xs:attribute name="cacheResult" type="xs:boolean" default="true"/>
        <xs:attribute name="cacheResultFile" type="xs:anyURI"/>
        <xs:attribute name="cacheTokens" type="xs:boolean" default="false"/>
        <xs:attribute name="colors" type="xs:boolean" default="false"/>
        <xs:attribute name="columns" type="columnsType" default="80"/>
        <xs:attribute name="convertDeprecationsToExceptions" type="xs:boolean" default="false"/>
        <xs:attribute name="convertErrorsToExceptions" type="xs:boolean" default="true"/>
        <xs:attribute name="convertNoticesToExceptions" type="xs:boolean" default="true"/>
        <xs:attribute name="convertWarningsToExceptions" type="xs:boolean" default="true"/>
        <xs:attribute name="disableCodeCoverageIgnore" type="xs:boolean" default="false"/>
        <xs:attribute name="forceCoversAnnotation" type="xs:boolean" default="false"/>
        <xs:attribute name="printerClass" type="xs:string" default="PHPUnit\TextUI\ResultPrinter"/>
        <xs:attribute name="printerFile" type="xs:anyURI"/>
        <xs:attribute name="processIsolation" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnDefect" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnError" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnFailure" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnWarning" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnIncomplete" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnRisky" type="xs:boolean" default="false"/>
        <xs:attribute name="stopOnSkipped" type="xs:boolean" default="false"/>
        <xs:attribute name="failOnRisky" type="xs:boolean" default="false"/>
        <xs:attribute name="failOnWarning" type="xs:boolean" default="false"/>
        <xs:attribute name="beStrictAboutChangesToGlobalState" type="xs:boolean" default="false"/>
        <xs:attribute name="beStrictAboutOutputDuringTests" type="xs:boolean" default="false"/>
        <xs:attribute name="beStrictAboutResourceUsageDuringSmallTests" type="xs:boolean" default="false"/>
        <xs:attribute name="beStrictAboutTestsThatDoNotTestAnything" type="xs:boolean" default="true"/>
        <xs:attribute name="beStrictAboutTodoAnnotatedTests" type="xs:boolean" default="false"/>
        <xs:attribute name="beStrictAboutCoversAnnotation" type="xs:boolean" default="false"/>
        <xs:attribute name="defaultTimeLimit" type="xs:integer" default="0"/>
        <xs:attribute name="enforceTimeLimit" type="xs:boolean" default="false"/>
        <xs:attribute name="ignoreDeprecatedCodeUnitsFromCodeCoverage" type="xs:boolean" default="false"/>
        <xs:attribute name="timeoutForSmallTests" type="xs:integer" default="1"/>
        <xs:attribute name="timeoutForMediumTests" type="xs:integer" default="10"/>
        <xs:attribute name="timeoutForLargeTests" type="xs:integer" default="60"/>
        <xs:attribute name="testSuiteLoaderClass" type="xs:string" default="PHPUnit\Runner\StandardTestSuiteLoader"/>
        <xs:attribute name="testSuiteLoaderFile" type="xs:anyURI"/>
        <xs:attribute name="defaultTestSuite" type="xs:string" default=""/>
        <xs:attribute name="verbose" type="xs:boolean" default="false"/>
        <xs:attribute name="testdox" type="xs:boolean" default="false"/>
        <xs:attribute name="stderr" type="xs:boolean" default="false"/>
        <xs:attribute name="reverseDefectList" type="xs:boolean" default="false"/>
        <xs:attribute name="registerMockObjectsFromTestArgumentsRecursively" type="xs:boolean" default="false"/>
        <xs:attribute name="extensionsDirectory" type="xs:anyURI"/>
        <xs:attribute name="executionOrder" type="executionOrderType" default="default"/>
        <xs:attribute name="resolveDependencies" type="xs:boolean" default="true"/>
        <xs:attribute name="noInteraction" type="xs:boolean" default="false"/>
    </xs:attributeGroup>
    <xs:group name="configGroup">
        <xs:all>
            <xs:element ref="testSuiteFacet" minOccurs="0"/>
            <xs:element name="groups" type="groupsType" minOccurs="0"/>
            <xs:element name="testdoxGroups" type="groupsType" minOccurs="0"/>
            <xs:element name="filter" type="filtersType" minOccurs="0"/>
            <xs:element name="logging" type="loggersType" minOccurs="0"/>
            <xs:element name="extensions" type="extensionsType" minOccurs="0"/>
            <xs:element name="listeners" type="listenersType" minOccurs="0"/>
            <xs:element name="php" type="phpType" minOccurs="0"/>
        </xs:all>
    </xs:group>
    <xs:element name="testSuiteFacet" abstract="true"/>
    <xs:element name="testsuite" type="testSuiteType" substitutionGroup="testSuiteFacet"/>
    <xs:element name="testsuites" type="testSuitesType" substitutionGroup="testSuiteFacet"/>
    <xs:complexType name="testSuitesType">
        <xs:sequence>
            <xs:element name="testsuite" type="testSuiteType" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="testSuiteType">
        <xs:sequence>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:group ref="pathGroup"/>
                <xs:element name="exclude" type="xs:string"/>
            </xs:choice>
        </xs:sequence>
        <xs:attribute name="name" type="xs:string" use="required"/>
    </xs:complexType>
</xs:schema>
{
    "name": "phpunit/phpunit",
    "description": "The PHP Unit Testing framework.",
    "type": "library",
    "keywords": [
        "phpunit",
        "xunit",
        "testing"
    ],
    "homepage": "https://phpunit.de/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/phpunit/issues"
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.2",
        "ext-dom": "*",
        "ext-json": "*",
        "ext-libxml": "*",
        "ext-mbstring": "*",
        "ext-xml": "*",
        "ext-xmlwriter": "*",
        "doctrine/instantiator": "^1.3.1",
        "myclabs/deep-copy": "^1.10.0",
        "phar-io/manifest": "^2.0.3",
        "phar-io/version": "^3.0.2",
        "phpunit/php-code-coverage": "^7.0.12",
        "phpunit/php-file-iterator": "^2.0.4",
        "phpunit/php-text-template": "^1.2.1",
        "phpunit/php-timer": "^2.1.2",
        "sebastian/comparator": "^3.0.5",
        "sebastian/diff": "^3.0.2",
        "sebastian/environment": "^4.2.3",
        "sebastian/exporter": "^3.1.5",
        "sebastian/global-state": "^3.0.0",
        "sebastian/object-enumerator": "^3.0.3",
        "sebastian/resource-operations": "^2.0.1",
        "sebastian/type": "^1.1.3",
        "sebastian/version": "^2.0.1"
    },
    "config": {
        "platform": {
            "php": "7.2.0"
        },
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "suggest": {
        "phpunit/php-invoker": "^2.0.0",
        "ext-soap": "*",
        "ext-xdebug": "*"
    },
    "bin": [
        "phpunit"
    ],
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/"
        ],
        "files": [
            "src/Framework/Assert/Functions.php",
            "tests/_files/CoverageNamespacedFunctionTest.php",
            "tests/_files/CoveredFunction.php",
            "tests/_files/NamespaceCoveredFunction.php"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "8.5-dev"
        }
    }
}
# Security Policy

PHPUnit is a framework for writing as well as a commandline tool for running tests. Writing and running tests is a development-time activity. There is no reason why PHPUnit should be installed on a webserver.

**If you upload PHPUnit to a webserver then your deployment process is broken. On a more general note, if your `vendor` directory is publicly accessible on your webserver then your deployment process is also broken.**

Please note that if you upload PHPUnit to a webserver "bad things" may happen. [You have been warned.](https://thephp.cc/articles/phpunit-a-security-risk)

## Security Contact Information

After the above, if you still would like to report a security vulnerability, please email `sebastian@phpunit.de`.
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI;

use const PHP_EOL;
use function array_map;
use function array_reverse;
use function count;
use function floor;
use function implode;
use function in_array;
use function is_int;
use function max;
use function preg_split;
use function sprintf;
use function str_pad;
use function str_repeat;
use function strlen;
use function trim;
use function vsprintf;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\Color;
use PHPUnit\Util\Printer;
use SebastianBergmann\Environment\Console;
use SebastianBergmann\Timer\Timer;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class ResultPrinter extends Printer implements TestListener
{
    public const EVENT_TEST_START = 0;

    public const EVENT_TEST_END = 1;

    public const EVENT_TESTSUITE_START = 2;

    public const EVENT_TESTSUITE_END = 3;

    public const COLOR_NEVER = 'never';

    public const COLOR_AUTO = 'auto';

    public const COLOR_ALWAYS = 'always';

    public const COLOR_DEFAULT = self::COLOR_NEVER;

    private const AVAILABLE_COLORS = [self::COLOR_NEVER, self::COLOR_AUTO, self::COLOR_ALWAYS];

    /**
     * @var int
     */
    protected $column = 0;

    /**
     * @var int
     */
    protected $maxColumn;

    /**
     * @var bool
     */
    protected $lastTestFailed = false;

    /**
     * @var int
     */
    protected $numAssertions = 0;

    /**
     * @var int
     */
    protected $numTests = -1;

    /**
     * @var int
     */
    protected $numTestsRun = 0;

    /**
     * @var int
     */
    protected $numTestsWidth;

    /**
     * @var bool
     */
    protected $colors = false;

    /**
     * @var bool
     */
    protected $debug = false;

    /**
     * @var bool
     */
    protected $verbose = false;

    /**
     * @var int
     */
    private $numberOfColumns;

    /**
     * @var bool
     */
    private $reverse;

    /**
     * @var bool
     */
    private $defectListPrinted = false;

    /**
     * Constructor.
     *
     * @param null|resource|string $out
     * @param int|string           $numberOfColumns
     *
     * @throws Exception
     */
    public function __construct($out = null, bool $verbose = false, string $colors = self::COLOR_DEFAULT, bool $debug = false, $numberOfColumns = 80, bool $reverse = false)
    {
        parent::__construct($out);

        if (!in_array($colors, self::AVAILABLE_COLORS, true)) {
            throw InvalidArgumentException::create(
                3,
                vsprintf('value from "%s", "%s" or "%s"', self::AVAILABLE_COLORS)
            );
        }

        if (!is_int($numberOfColumns) && $numberOfColumns !== 'max') {
            throw InvalidArgumentException::create(5, 'integer or "max"');
        }

        $console            = new Console;
        $maxNumberOfColumns = $console->getNumberOfColumns();

        if ($numberOfColumns === 'max' || ($numberOfColumns !== 80 && $numberOfColumns > $maxNumberOfColumns)) {
            $numberOfColumns = $maxNumberOfColumns;
        }

        $this->numberOfColumns = $numberOfColumns;
        $this->verbose         = $verbose;
        $this->debug           = $debug;
        $this->reverse         = $reverse;

        if ($colors === self::COLOR_AUTO && $console->hasColorSupport()) {
            $this->colors = true;
        } else {
            $this->colors = (self::COLOR_ALWAYS === $colors);
        }
    }

    /**
     * @throws \SebastianBergmann\Timer\RuntimeException
     */
    public function printResult(TestResult $result): void
    {
        $this->printHeader($result);
        $this->printErrors($result);
        $this->printWarnings($result);
        $this->printFailures($result);
        $this->printRisky($result);

        if ($this->verbose) {
            $this->printIncompletes($result);
            $this->printSkipped($result);
        }

        $this->printFooter($result);
    }

    /**
     * An error occurred.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        $this->writeProgressWithColor('fg-red, bold', 'E');
        $this->lastTestFailed = true;
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        $this->writeProgressWithColor('bg-red, fg-white', 'F');
        $this->lastTestFailed = true;
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        $this->writeProgressWithColor('fg-yellow, bold', 'W');
        $this->lastTestFailed = true;
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        $this->writeProgressWithColor('fg-yellow, bold', 'I');
        $this->lastTestFailed = true;
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        $this->writeProgressWithColor('fg-yellow, bold', 'R');
        $this->lastTestFailed = true;
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        $this->writeProgressWithColor('fg-cyan, bold', 'S');
        $this->lastTestFailed = true;
    }

    /**
     * A testsuite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
        if ($this->numTests == -1) {
            $this->numTests      = count($suite);
            $this->numTestsWidth = strlen((string) $this->numTests);
            $this->maxColumn     = $this->numberOfColumns - strlen('  /  (XXX%)') - (2 * $this->numTestsWidth);
        }
    }

    /**
     * A testsuite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
    }

    /**
     * A test started.
     */
    public function startTest(Test $test): void
    {
        if ($this->debug) {
            $this->write(
                sprintf(
                    "Test '%s' started\n",
                    \PHPUnit\Util\Test::describeAsString($test)
                )
            );
        }
    }

    /**
     * A test ended.
     */
    public function endTest(Test $test, float $time): void
    {
        if ($this->debug) {
            $this->write(
                sprintf(
                    "Test '%s' ended\n",
                    \PHPUnit\Util\Test::describeAsString($test)
                )
            );
        }

        if (!$this->lastTestFailed) {
            $this->writeProgress('.');
        }

        if ($test instanceof TestCase) {
            $this->numAssertions += $test->getNumAssertions();
        } elseif ($test instanceof PhptTestCase) {
            $this->numAssertions++;
        }

        $this->lastTestFailed = false;

        if ($test instanceof TestCase && !$test->hasExpectationOnOutput()) {
            $this->write($test->getActualOutput());
        }
    }

    protected function printDefects(array $defects, string $type): void
    {
        $count = count($defects);

        if ($count == 0) {
            return;
        }

        if ($this->defectListPrinted) {
            $this->write("\n--\n\n");
        }

        $this->write(
            sprintf(
                "There %s %d %s%s:\n",
                ($count == 1) ? 'was' : 'were',
                $count,
                $type,
                ($count == 1) ? '' : 's'
            )
        );

        $i = 1;

        if ($this->reverse) {
            $defects = array_reverse($defects);
        }

        foreach ($defects as $defect) {
            $this->printDefect($defect, $i++);
        }

        $this->defectListPrinted = true;
    }

    protected function printDefect(TestFailure $defect, int $count): void
    {
        $this->printDefectHeader($defect, $count);
        $this->printDefectTrace($defect);
    }

    protected function printDefectHeader(TestFailure $defect, int $count): void
    {
        $this->write(
            sprintf(
                "\n%d) %s\n",
                $count,
                $defect->getTestName()
            )
        );
    }

    protected function printDefectTrace(TestFailure $defect): void
    {
        $e = $defect->thrownException();
        $this->write((string) $e);

        while ($e = $e->getPrevious()) {
            $this->write("\nCaused by\n" . trim((string) $e) . "\n");
        }
    }

    protected function printErrors(TestResult $result): void
    {
        $this->printDefects($result->errors(), 'error');
    }

    protected function printFailures(TestResult $result): void
    {
        $this->printDefects($result->failures(), 'failure');
    }

    protected function printWarnings(TestResult $result): void
    {
        $this->printDefects($result->warnings(), 'warning');
    }

    protected function printIncompletes(TestResult $result): void
    {
        $this->printDefects($result->notImplemented(), 'incomplete test');
    }

    protected function printRisky(TestResult $result): void
    {
        $this->printDefects($result->risky(), 'risky test');
    }

    protected function printSkipped(TestResult $result): void
    {
        $this->printDefects($result->skipped(), 'skipped test');
    }

    /**
     * @throws \SebastianBergmann\Timer\RuntimeException
     */
    protected function printHeader(TestResult $result): void
    {
        if (count($result) > 0) {
            $this->write(PHP_EOL . PHP_EOL . Timer::resourceUsage() . PHP_EOL . PHP_EOL);
        }
    }

    protected function printFooter(TestResult $result): void
    {
        if (count($result) === 0) {
            $this->writeWithColor(
                'fg-black, bg-yellow',
                'No tests executed!'
            );

            return;
        }

        if ($result->wasSuccessfulAndNoTestIsRiskyOrSkippedOrIncomplete()) {
            $this->writeWithColor(
                'fg-black, bg-green',
                sprintf(
                    'OK (%d test%s, %d assertion%s)',
                    count($result),
                    (count($result) == 1) ? '' : 's',
                    $this->numAssertions,
                    ($this->numAssertions == 1) ? '' : 's'
                )
            );

            return;
        }

        $color = 'fg-black, bg-yellow';

        if ($result->wasSuccessful()) {
            if ($this->verbose || !$result->allHarmless()) {
                $this->write("\n");
            }

            $this->writeWithColor(
                $color,
                'OK, but incomplete, skipped, or risky tests!'
            );
        } else {
            $this->write("\n");

            if ($result->errorCount()) {
                $color = 'fg-white, bg-red';

                $this->writeWithColor(
                    $color,
                    'ERRORS!'
                );
            } elseif ($result->failureCount()) {
                $color = 'fg-white, bg-red';

                $this->writeWithColor(
                    $color,
                    'FAILURES!'
                );
            } elseif ($result->warningCount()) {
                $color = 'fg-black, bg-yellow';

                $this->writeWithColor(
                    $color,
                    'WARNINGS!'
                );
            }
        }

        $this->writeCountString(count($result), 'Tests', $color, true);
        $this->writeCountString($this->numAssertions, 'Assertions', $color, true);
        $this->writeCountString($result->errorCount(), 'Errors', $color);
        $this->writeCountString($result->failureCount(), 'Failures', $color);
        $this->writeCountString($result->warningCount(), 'Warnings', $color);
        $this->writeCountString($result->skippedCount(), 'Skipped', $color);
        $this->writeCountString($result->notImplementedCount(), 'Incomplete', $color);
        $this->writeCountString($result->riskyCount(), 'Risky', $color);
        $this->writeWithColor($color, '.');
    }

    protected function writeProgress(string $progress): void
    {
        if ($this->debug) {
            return;
        }

        $this->write($progress);
        $this->column++;
        $this->numTestsRun++;

        if ($this->column == $this->maxColumn || $this->numTestsRun == $this->numTests) {
            if ($this->numTestsRun == $this->numTests) {
                $this->write(str_repeat(' ', $this->maxColumn - $this->column));
            }

            $this->write(
                sprintf(
                    ' %' . $this->numTestsWidth . 'd / %' .
                    $this->numTestsWidth . 'd (%3s%%)',
                    $this->numTestsRun,
                    $this->numTests,
                    floor(($this->numTestsRun / $this->numTests) * 100)
                )
            );

            if ($this->column == $this->maxColumn) {
                $this->writeNewLine();
            }
        }
    }

    protected function writeNewLine(): void
    {
        $this->column = 0;
        $this->write("\n");
    }

    /**
     * Formats a buffer with a specified ANSI color sequence if colors are
     * enabled.
     */
    protected function colorizeTextBox(string $color, string $buffer): string
    {
        if (!$this->colors) {
            return $buffer;
        }

        $lines   = preg_split('/\r\n|\r|\n/', $buffer);
        $padding = max(array_map('\strlen', $lines));

        $styledLines = [];

        foreach ($lines as $line) {
            $styledLines[] = Color::colorize($color, str_pad($line, $padding));
        }

        return implode(PHP_EOL, $styledLines);
    }

    /**
     * Writes a buffer out with a color sequence if colors are enabled.
     */
    protected function writeWithColor(string $color, string $buffer, bool $lf = true): void
    {
        $this->write($this->colorizeTextBox($color, $buffer));

        if ($lf) {
            $this->write(PHP_EOL);
        }
    }

    /**
     * Writes progress with a color sequence if colors are enabled.
     */
    protected function writeProgressWithColor(string $color, string $buffer): void
    {
        $buffer = $this->colorizeTextBox($color, $buffer);
        $this->writeProgress($buffer);
    }

    private function writeCountString(int $count, string $name, string $color, bool $always = false): void
    {
        static $first = true;

        if ($always || $count > 0) {
            $this->writeWithColor(
                $color,
                sprintf(
                    '%s%s: %d',
                    !$first ? ', ' : '',
                    $name,
                    $count
                ),
                false
            );

            $first = false;
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI;

use const PHP_EOL;
use const PHP_MAJOR_VERSION;
use const PHP_SAPI;
use function array_diff;
use function assert;
use function class_exists;
use function count;
use function dirname;
use function extension_loaded;
use function file_put_contents;
use function htmlspecialchars;
use function ini_get;
use function is_int;
use function is_string;
use function is_subclass_of;
use function mt_srand;
use function range;
use function realpath;
use function sprintf;
use function strpos;
use function time;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\AfterLastTestHook;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\BeforeFirstTestHook;
use PHPUnit\Runner\DefaultTestResultCache;
use PHPUnit\Runner\Filter\ExcludeGroupFilterIterator;
use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\Filter\IncludeGroupFilterIterator;
use PHPUnit\Runner\Filter\NameFilterIterator;
use PHPUnit\Runner\Hook;
use PHPUnit\Runner\NullTestResultCache;
use PHPUnit\Runner\ResultCacheExtension;
use PHPUnit\Runner\StandardTestSuiteLoader;
use PHPUnit\Runner\TestHook;
use PHPUnit\Runner\TestListenerAdapter;
use PHPUnit\Runner\TestSuiteLoader;
use PHPUnit\Runner\TestSuiteSorter;
use PHPUnit\Runner\Version;
use PHPUnit\Util\Configuration;
use PHPUnit\Util\Filesystem;
use PHPUnit\Util\Log\JUnit;
use PHPUnit\Util\Log\TeamCity;
use PHPUnit\Util\Printer;
use PHPUnit\Util\TestDox\CliTestDoxPrinter;
use PHPUnit\Util\TestDox\HtmlResultPrinter;
use PHPUnit\Util\TestDox\TextResultPrinter;
use PHPUnit\Util\TestDox\XmlResultPrinter;
use PHPUnit\Util\XdebugFilterScriptGenerator;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Exception as CodeCoverageException;
use SebastianBergmann\CodeCoverage\Filter as CodeCoverageFilter;
use SebastianBergmann\CodeCoverage\Report\Clover as CloverReport;
use SebastianBergmann\CodeCoverage\Report\Crap4j as Crap4jReport;
use SebastianBergmann\CodeCoverage\Report\Html\Facade as HtmlReport;
use SebastianBergmann\CodeCoverage\Report\PHP as PhpReport;
use SebastianBergmann\CodeCoverage\Report\Text as TextReport;
use SebastianBergmann\CodeCoverage\Report\Xml\Facade as XmlReport;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Environment\Runtime;
use SebastianBergmann\Invoker\Invoker;
use SebastianBergmann\Timer\Timer;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestRunner extends BaseTestRunner
{
    public const SUCCESS_EXIT = 0;

    public const FAILURE_EXIT = 1;

    public const EXCEPTION_EXIT = 2;

    /**
     * @var CodeCoverageFilter
     */
    private $codeCoverageFilter;

    /**
     * @var TestSuiteLoader
     */
    private $loader;

    /**
     * @psalm-var Printer&TestListener
     */
    private $printer;

    /**
     * @var Runtime
     */
    private $runtime;

    /**
     * @var bool
     */
    private $messagePrinted = false;

    /**
     * @var Hook[]
     */
    private $extensions = [];

    public function __construct(TestSuiteLoader $loader = null, CodeCoverageFilter $filter = null)
    {
        if ($filter === null) {
            $filter = new CodeCoverageFilter;
        }

        $this->codeCoverageFilter = $filter;
        $this->loader             = $loader;
        $this->runtime            = new Runtime;
    }

    /**
     * @throws \PHPUnit\Runner\Exception
     * @throws Exception
     */
    public function doRun(Test $suite, array $arguments = [], array $warnings = [], bool $exit = true): TestResult
    {
        if (isset($arguments['configuration'])) {
            $GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] = $arguments['configuration'];
        }

        $this->handleConfiguration($arguments);

        if (is_int($arguments['columns']) && $arguments['columns'] < 16) {
            $arguments['columns']   = 16;
            $tooFewColumnsRequested = true;
        }

        if (isset($arguments['bootstrap'])) {
            $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $arguments['bootstrap'];
        }

        if ($suite instanceof TestCase || $suite instanceof TestSuite) {
            if ($arguments['backupGlobals'] === true) {
                $suite->setBackupGlobals(true);
            }

            if ($arguments['backupStaticAttributes'] === true) {
                $suite->setBackupStaticAttributes(true);
            }

            if ($arguments['beStrictAboutChangesToGlobalState'] === true) {
                $suite->setBeStrictAboutChangesToGlobalState(true);
            }
        }

        if ($arguments['executionOrder'] === TestSuiteSorter::ORDER_RANDOMIZED) {
            mt_srand($arguments['randomOrderSeed']);
        }

        if ($arguments['cacheResult']) {
            if (!isset($arguments['cacheResultFile'])) {
                if (isset($arguments['configuration']) && $arguments['configuration'] instanceof Configuration) {
                    $cacheLocation = $arguments['configuration']->getFilename();
                } else {
                    $cacheLocation = $_SERVER['PHP_SELF'];
                }

                $arguments['cacheResultFile'] = null;

                $cacheResultFile = realpath($cacheLocation);

                if ($cacheResultFile !== false) {
                    $arguments['cacheResultFile'] = dirname($cacheResultFile);
                }
            }

            $cache = new DefaultTestResultCache($arguments['cacheResultFile']);

            $this->addExtension(new ResultCacheExtension($cache));
        }

        if ($arguments['executionOrder'] !== TestSuiteSorter::ORDER_DEFAULT || $arguments['executionOrderDefects'] !== TestSuiteSorter::ORDER_DEFAULT || $arguments['resolveDependencies']) {
            $cache = $cache ?? new NullTestResultCache;

            $cache->load();

            $sorter = new TestSuiteSorter($cache);

            $sorter->reorderTestsInSuite($suite, $arguments['executionOrder'], $arguments['resolveDependencies'], $arguments['executionOrderDefects']);
            $originalExecutionOrder = $sorter->getOriginalExecutionOrder();

            unset($sorter);
        }

        if (is_int($arguments['repeat']) && $arguments['repeat'] > 0) {
            $_suite = new TestSuite;

            /* @noinspection PhpUnusedLocalVariableInspection */
            foreach (range(1, $arguments['repeat']) as $step) {
                $_suite->addTest($suite);
            }

            $suite = $_suite;

            unset($_suite);
        }

        $result = $this->createTestResult();

        $listener       = new TestListenerAdapter;
        $listenerNeeded = false;

        foreach ($this->extensions as $extension) {
            if ($extension instanceof TestHook) {
                $listener->add($extension);

                $listenerNeeded = true;
            }
        }

        if ($listenerNeeded) {
            $result->addListener($listener);
        }

        unset($listener, $listenerNeeded);

        if ($arguments['convertDeprecationsToExceptions']) {
            $result->convertDeprecationsToExceptions(true);
        }

        if (!$arguments['convertErrorsToExceptions']) {
            $result->convertErrorsToExceptions(false);
        }

        if (!$arguments['convertNoticesToExceptions']) {
            $result->convertNoticesToExceptions(false);
        }

        if (!$arguments['convertWarningsToExceptions']) {
            $result->convertWarningsToExceptions(false);
        }

        if ($arguments['stopOnError']) {
            $result->stopOnError(true);
        }

        if ($arguments['stopOnFailure']) {
            $result->stopOnFailure(true);
        }

        if ($arguments['stopOnWarning']) {
            $result->stopOnWarning(true);
        }

        if ($arguments['stopOnIncomplete']) {
            $result->stopOnIncomplete(true);
        }

        if ($arguments['stopOnRisky']) {
            $result->stopOnRisky(true);
        }

        if ($arguments['stopOnSkipped']) {
            $result->stopOnSkipped(true);
        }

        if ($arguments['stopOnDefect']) {
            $result->stopOnDefect(true);
        }

        if ($arguments['registerMockObjectsFromTestArgumentsRecursively']) {
            $result->setRegisterMockObjectsFromTestArgumentsRecursively(true);
        }

        if ($this->printer === null) {
            if (isset($arguments['printer'])) {
                if ($arguments['printer'] instanceof Printer && $arguments['printer'] instanceof TestListener) {
                    $this->printer = $arguments['printer'];
                } elseif (is_string($arguments['printer']) && class_exists($arguments['printer'], false)) {
                    try {
                        new ReflectionClass($arguments['printer']);
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new Exception(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    if (is_subclass_of($arguments['printer'], ResultPrinter::class)) {
                        $this->printer = $this->createPrinter($arguments['printer'], $arguments);
                    }
                }
            } else {
                $this->printer = $this->createPrinter(ResultPrinter::class, $arguments);
            }
        }

        if (isset($originalExecutionOrder) && $this->printer instanceof CliTestDoxPrinter) {
            assert($this->printer instanceof CliTestDoxPrinter);

            $this->printer->setOriginalExecutionOrder($originalExecutionOrder);
            $this->printer->setShowProgressAnimation(!$arguments['noInteraction']);
        }

        $this->write(Version::getVersionString() . "\n");

        if ($arguments['verbose']) {
            $this->writeMessage('Runtime', $this->runtime->getNameWithVersionAndCodeCoverageDriver());

            if (isset($arguments['configuration'])) {
                $this->writeMessage(
                    'Configuration',
                    $arguments['configuration']->getFilename()
                );
            }

            foreach ($arguments['loadedExtensions'] as $extension) {
                $this->writeMessage(
                    'Extension',
                    $extension
                );
            }

            foreach ($arguments['notLoadedExtensions'] as $extension) {
                $this->writeMessage(
                    'Extension',
                    $extension
                );
            }
        }

        foreach ($warnings as $warning) {
            $this->writeMessage('Warning', $warning);
        }

        if ($arguments['executionOrder'] === TestSuiteSorter::ORDER_RANDOMIZED) {
            $this->writeMessage(
                'Random seed',
                (string) $arguments['randomOrderSeed']
            );
        }

        if (isset($tooFewColumnsRequested)) {
            $this->writeMessage('Error', 'Less than 16 columns requested, number of columns set to 16');
        }

        if ($this->runtime->discardsComments()) {
            $this->writeMessage('Warning', 'opcache.save_comments=0 set; annotations will not work');
        }

        if (isset($arguments['configuration']) && $arguments['configuration']->hasValidationErrors()) {
            $this->write(
                "\n  Warning - The configuration file did not pass validation!\n  The following problems have been detected:\n"
            );

            foreach ($arguments['configuration']->getValidationErrors() as $line => $errors) {
                $this->write(sprintf("\n  Line %d:\n", $line));

                foreach ($errors as $msg) {
                    $this->write(sprintf("  - %s\n", $msg));
                }
            }

            $this->write("\n  Test results may not be as expected.\n\n");
        }

        if (isset($arguments['conflictBetweenPrinterClassAndTestdox'])) {
            $this->writeMessage('Warning', 'Directives printerClass and testdox are mutually exclusive');
        }

        foreach ($arguments['listeners'] as $listener) {
            $result->addListener($listener);
        }

        $result->addListener($this->printer);

        $codeCoverageReports = 0;

        if (!isset($arguments['noLogging'])) {
            if (isset($arguments['testdoxHTMLFile'])) {
                $result->addListener(
                    new HtmlResultPrinter(
                        $arguments['testdoxHTMLFile'],
                        $arguments['testdoxGroups'],
                        $arguments['testdoxExcludeGroups']
                    )
                );
            }

            if (isset($arguments['testdoxTextFile'])) {
                $result->addListener(
                    new TextResultPrinter(
                        $arguments['testdoxTextFile'],
                        $arguments['testdoxGroups'],
                        $arguments['testdoxExcludeGroups']
                    )
                );
            }

            if (isset($arguments['testdoxXMLFile'])) {
                $result->addListener(
                    new XmlResultPrinter(
                        $arguments['testdoxXMLFile']
                    )
                );
            }

            if (isset($arguments['teamcityLogfile'])) {
                $result->addListener(
                    new TeamCity($arguments['teamcityLogfile'])
                );
            }

            if (isset($arguments['junitLogfile'])) {
                $result->addListener(
                    new JUnit(
                        $arguments['junitLogfile'],
                        $arguments['reportUselessTests']
                    )
                );
            }

            if (isset($arguments['coverageClover'])) {
                $codeCoverageReports++;
            }

            if (isset($arguments['coverageCrap4J'])) {
                $codeCoverageReports++;
            }

            if (isset($arguments['coverageHtml'])) {
                $codeCoverageReports++;
            }

            if (isset($arguments['coveragePHP'])) {
                $codeCoverageReports++;
            }

            if (isset($arguments['coverageText'])) {
                $codeCoverageReports++;
            }

            if (isset($arguments['coverageXml'])) {
                $codeCoverageReports++;
            }
        }

        if (isset($arguments['noCoverage'])) {
            $codeCoverageReports = 0;
        }

        if ($codeCoverageReports > 0 && PHP_MAJOR_VERSION < 8 && !$this->runtime->canCollectCodeCoverage()) {
            $this->writeMessage('Error', 'No code coverage driver is available');

            $codeCoverageReports = 0;
        }

        if ($codeCoverageReports > 0 || isset($arguments['xdebugFilterFile'])) {
            $whitelistFromConfigurationFile = false;
            $whitelistFromOption            = false;

            if (isset($arguments['whitelist'])) {
                $this->codeCoverageFilter->addDirectoryToWhitelist($arguments['whitelist']);

                $whitelistFromOption = true;
            }

            if (isset($arguments['configuration'])) {
                $filterConfiguration = $arguments['configuration']->getFilterConfiguration();

                if (!empty($filterConfiguration['whitelist'])) {
                    $whitelistFromConfigurationFile = true;
                }

                if (!empty($filterConfiguration['whitelist'])) {
                    foreach ($filterConfiguration['whitelist']['include']['directory'] as $dir) {
                        $this->codeCoverageFilter->addDirectoryToWhitelist(
                            $dir['path'],
                            $dir['suffix'],
                            $dir['prefix']
                        );
                    }

                    foreach ($filterConfiguration['whitelist']['include']['file'] as $file) {
                        $this->codeCoverageFilter->addFileToWhitelist($file);
                    }

                    foreach ($filterConfiguration['whitelist']['exclude']['directory'] as $dir) {
                        $this->codeCoverageFilter->removeDirectoryFromWhitelist(
                            $dir['path'],
                            $dir['suffix'],
                            $dir['prefix']
                        );
                    }

                    foreach ($filterConfiguration['whitelist']['exclude']['file'] as $file) {
                        $this->codeCoverageFilter->removeFileFromWhitelist($file);
                    }
                }
            }
        }

        if ($codeCoverageReports > 0) {
            if (PHP_MAJOR_VERSION >= 8) {
                $this->writeMessage('Error', 'This version of PHPUnit does not support code coverage on PHP 8');

                $codeCoverageReports = 0;
            } else {
                try {
                    $codeCoverage = new CodeCoverage(
                        null,
                        $this->codeCoverageFilter
                    );

                    $codeCoverage->setUnintentionallyCoveredSubclassesWhitelist(
                        [Comparator::class]
                    );

                    $codeCoverage->setCheckForUnintentionallyCoveredCode(
                        $arguments['strictCoverage']
                    );

                    $codeCoverage->setCheckForMissingCoversAnnotation(
                        $arguments['strictCoverage']
                    );

                    if (isset($arguments['forceCoversAnnotation'])) {
                        $codeCoverage->setForceCoversAnnotation(
                            $arguments['forceCoversAnnotation']
                        );
                    }

                    if (isset($arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'])) {
                        $codeCoverage->setIgnoreDeprecatedCode(
                            $arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage']
                        );
                    }

                    if (isset($arguments['disableCodeCoverageIgnore'])) {
                        $codeCoverage->setDisableIgnoredLines(true);
                    }

                    if (!empty($filterConfiguration['whitelist'])) {
                        $codeCoverage->setAddUncoveredFilesFromWhitelist(
                            $filterConfiguration['whitelist']['addUncoveredFilesFromWhitelist']
                        );

                        $codeCoverage->setProcessUncoveredFilesFromWhitelist(
                            $filterConfiguration['whitelist']['processUncoveredFilesFromWhitelist']
                        );
                    }

                    if (!$this->codeCoverageFilter->hasWhitelist()) {
                        if (!$whitelistFromConfigurationFile && !$whitelistFromOption) {
                            $this->writeMessage('Error', 'No whitelist is configured, no code coverage will be generated.');
                        } else {
                            $this->writeMessage('Error', 'Incorrect whitelist config, no code coverage will be generated.');
                        }

                        $codeCoverageReports = 0;

                        unset($codeCoverage);
                    }
                } catch (CodeCoverageException $e) {
                    $this->writeMessage('Error', $e->getMessage());

                    $codeCoverageReports = 0;
                }
            }
        }

        if (isset($arguments['xdebugFilterFile'], $filterConfiguration)) {
            $this->write("\n");

            $script = (new XdebugFilterScriptGenerator)->generate($filterConfiguration['whitelist']);

            if ($arguments['xdebugFilterFile'] !== 'php://stdout' && $arguments['xdebugFilterFile'] !== 'php://stderr' && !Filesystem::createDirectory(dirname($arguments['xdebugFilterFile']))) {
                $this->write(sprintf('Cannot write Xdebug filter script to %s ' . PHP_EOL, $arguments['xdebugFilterFile']));

                exit(self::EXCEPTION_EXIT);
            }

            file_put_contents($arguments['xdebugFilterFile'], $script);

            $this->write(sprintf('Wrote Xdebug filter script to %s ' . PHP_EOL, $arguments['xdebugFilterFile']));

            exit(self::SUCCESS_EXIT);
        }

        $this->write("\n");

        if (isset($codeCoverage)) {
            $result->setCodeCoverage($codeCoverage);

            if ($codeCoverageReports > 1 && isset($arguments['cacheTokens'])) {
                $codeCoverage->setCacheTokens($arguments['cacheTokens']);
            }
        }

        $result->beStrictAboutTestsThatDoNotTestAnything($arguments['reportUselessTests']);
        $result->beStrictAboutOutputDuringTests($arguments['disallowTestOutput']);
        $result->beStrictAboutTodoAnnotatedTests($arguments['disallowTodoAnnotatedTests']);
        $result->beStrictAboutResourceUsageDuringSmallTests($arguments['beStrictAboutResourceUsageDuringSmallTests']);

        if ($arguments['enforceTimeLimit'] === true) {
            if (!class_exists(Invoker::class)) {
                $this->writeMessage('Error', 'Package phpunit/php-invoker is required for enforcing time limits');
            }

            if (!extension_loaded('pcntl') || strpos(ini_get('disable_functions'), 'pcntl') !== false) {
                $this->writeMessage('Error', 'PHP extension pcntl is required for enforcing time limits');
            }
        }
        $result->enforceTimeLimit($arguments['enforceTimeLimit']);
        $result->setDefaultTimeLimit($arguments['defaultTimeLimit']);
        $result->setTimeoutForSmallTests($arguments['timeoutForSmallTests']);
        $result->setTimeoutForMediumTests($arguments['timeoutForMediumTests']);
        $result->setTimeoutForLargeTests($arguments['timeoutForLargeTests']);

        if ($suite instanceof TestSuite) {
            $this->processSuiteFilters($suite, $arguments);
            $suite->setRunTestInSeparateProcess($arguments['processIsolation']);
        }

        foreach ($this->extensions as $extension) {
            if ($extension instanceof BeforeFirstTestHook) {
                $extension->executeBeforeFirstTest();
            }
        }

        $suite->run($result);

        foreach ($this->extensions as $extension) {
            if ($extension instanceof AfterLastTestHook) {
                $extension->executeAfterLastTest();
            }
        }

        $result->flushListeners();

        if ($this->printer instanceof ResultPrinter) {
            $this->printer->printResult($result);
        }

        if (isset($codeCoverage)) {
            if (isset($arguments['coverageClover'])) {
                $this->codeCoverageGenerationStart('Clover XML');

                try {
                    $writer = new CloverReport;
                    $writer->process($codeCoverage, $arguments['coverageClover']);

                    $this->codeCoverageGenerationSucceeded();

                    unset($writer);
                } catch (CodeCoverageException $e) {
                    $this->codeCoverageGenerationFailed($e);
                }
            }

            if (isset($arguments['coverageCrap4J'])) {
                $this->codeCoverageGenerationStart('Crap4J XML');

                try {
                    $writer = new Crap4jReport($arguments['crap4jThreshold']);
                    $writer->process($codeCoverage, $arguments['coverageCrap4J']);

                    $this->codeCoverageGenerationSucceeded();

                    unset($writer);
                } catch (CodeCoverageException $e) {
                    $this->codeCoverageGenerationFailed($e);
                }
            }

            if (isset($arguments['coverageHtml'])) {
                $this->codeCoverageGenerationStart('HTML');

                try {
                    $writer = new HtmlReport(
                        $arguments['reportLowUpperBound'],
                        $arguments['reportHighLowerBound'],
                        sprintf(
                            ' and <a href="https://phpunit.de/">PHPUnit %s</a>',
                            Version::id()
                        )
                    );

                    $writer->process($codeCoverage, $arguments['coverageHtml']);

                    $this->codeCoverageGenerationSucceeded();

                    unset($writer);
                } catch (CodeCoverageException $e) {
                    $this->codeCoverageGenerationFailed($e);
                }
            }

            if (isset($arguments['coveragePHP'])) {
                $this->codeCoverageGenerationStart('PHP');

                try {
                    $writer = new PhpReport;
                    $writer->process($codeCoverage, $arguments['coveragePHP']);

                    $this->codeCoverageGenerationSucceeded();

                    unset($writer);
                } catch (CodeCoverageException $e) {
                    $this->codeCoverageGenerationFailed($e);
                }
            }

            if (isset($arguments['coverageText'])) {
                if ($arguments['coverageText'] === 'php://stdout') {
                    $outputStream = $this->printer;
                    $colors       = $arguments['colors'] && $arguments['colors'] !== ResultPrinter::COLOR_NEVER;
                } else {
                    $outputStream = new Printer($arguments['coverageText']);
                    $colors       = false;
                }

                $processor = new TextReport(
                    $arguments['reportLowUpperBound'],
                    $arguments['reportHighLowerBound'],
                    $arguments['coverageTextShowUncoveredFiles'],
                    $arguments['coverageTextShowOnlySummary']
                );

                $outputStream->write(
                    $processor->process($codeCoverage, $colors)
                );
            }

            if (isset($arguments['coverageXml'])) {
                $this->codeCoverageGenerationStart('PHPUnit XML');

                try {
                    $writer = new XmlReport(Version::id());
                    $writer->process($codeCoverage, $arguments['coverageXml']);

                    $this->codeCoverageGenerationSucceeded();

                    unset($writer);
                } catch (CodeCoverageException $e) {
                    $this->codeCoverageGenerationFailed($e);
                }
            }
        }

        if ($exit) {
            if ($result->wasSuccessfulIgnoringWarnings()) {
                if ($arguments['failOnRisky'] && !$result->allHarmless()) {
                    exit(self::FAILURE_EXIT);
                }

                if ($arguments['failOnWarning'] && $result->warningCount() > 0) {
                    exit(self::FAILURE_EXIT);
                }

                exit(self::SUCCESS_EXIT);
            }

            if ($result->errorCount() > 0) {
                exit(self::EXCEPTION_EXIT);
            }

            if ($result->failureCount() > 0) {
                exit(self::FAILURE_EXIT);
            }
        }

        return $result;
    }

    public function setPrinter(ResultPrinter $resultPrinter): void
    {
        $this->printer = $resultPrinter;
    }

    /**
     * Returns the loader to be used.
     */
    public function getLoader(): TestSuiteLoader
    {
        if ($this->loader === null) {
            $this->loader = new StandardTestSuiteLoader;
        }

        return $this->loader;
    }

    public function addExtension(Hook $extension): void
    {
        $this->extensions[] = $extension;
    }

    /**
     * Override to define how to handle a failed loading of
     * a test suite.
     */
    protected function runFailed(string $message): void
    {
        $this->write($message . PHP_EOL);

        exit(self::FAILURE_EXIT);
    }

    private function createTestResult(): TestResult
    {
        return new TestResult;
    }

    private function write(string $buffer): void
    {
        if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
            $buffer = htmlspecialchars($buffer);
        }

        if ($this->printer !== null) {
            $this->printer->write($buffer);
        } else {
            print $buffer;
        }
    }

    /**
     * @throws Exception
     */
    private function handleConfiguration(array &$arguments): void
    {
        if (isset($arguments['configuration']) &&
            !$arguments['configuration'] instanceof Configuration) {
            $arguments['configuration'] = Configuration::getInstance(
                $arguments['configuration']
            );
        }

        $arguments['debug']     = $arguments['debug'] ?? false;
        $arguments['filter']    = $arguments['filter'] ?? false;
        $arguments['listeners'] = $arguments['listeners'] ?? [];

        if (isset($arguments['configuration'])) {
            $arguments['configuration']->handlePHPConfiguration();

            $phpunitConfiguration = $arguments['configuration']->getPHPUnitConfiguration();

            if (isset($phpunitConfiguration['backupGlobals']) && !isset($arguments['backupGlobals'])) {
                $arguments['backupGlobals'] = $phpunitConfiguration['backupGlobals'];
            }

            if (isset($phpunitConfiguration['backupStaticAttributes']) && !isset($arguments['backupStaticAttributes'])) {
                $arguments['backupStaticAttributes'] = $phpunitConfiguration['backupStaticAttributes'];
            }

            if (isset($phpunitConfiguration['beStrictAboutChangesToGlobalState']) && !isset($arguments['beStrictAboutChangesToGlobalState'])) {
                $arguments['beStrictAboutChangesToGlobalState'] = $phpunitConfiguration['beStrictAboutChangesToGlobalState'];
            }

            if (isset($phpunitConfiguration['bootstrap']) && !isset($arguments['bootstrap'])) {
                $arguments['bootstrap'] = $phpunitConfiguration['bootstrap'];
            }

            if (isset($phpunitConfiguration['cacheResult']) && !isset($arguments['cacheResult'])) {
                $arguments['cacheResult'] = $phpunitConfiguration['cacheResult'];
            }

            if (isset($phpunitConfiguration['cacheResultFile']) && !isset($arguments['cacheResultFile'])) {
                $arguments['cacheResultFile'] = $phpunitConfiguration['cacheResultFile'];
            }

            if (isset($phpunitConfiguration['cacheTokens']) && !isset($arguments['cacheTokens'])) {
                $arguments['cacheTokens'] = $phpunitConfiguration['cacheTokens'];
            }

            if (isset($phpunitConfiguration['cacheTokens']) && !isset($arguments['cacheTokens'])) {
                $arguments['cacheTokens'] = $phpunitConfiguration['cacheTokens'];
            }

            if (isset($phpunitConfiguration['colors']) && !isset($arguments['colors'])) {
                $arguments['colors'] = $phpunitConfiguration['colors'];
            }

            if (isset($phpunitConfiguration['convertDeprecationsToExceptions']) && !isset($arguments['convertDeprecationsToExceptions'])) {
                $arguments['convertDeprecationsToExceptions'] = $phpunitConfiguration['convertDeprecationsToExceptions'];
            }

            if (isset($phpunitConfiguration['convertErrorsToExceptions']) && !isset($arguments['convertErrorsToExceptions'])) {
                $arguments['convertErrorsToExceptions'] = $phpunitConfiguration['convertErrorsToExceptions'];
            }

            if (isset($phpunitConfiguration['convertNoticesToExceptions']) && !isset($arguments['convertNoticesToExceptions'])) {
                $arguments['convertNoticesToExceptions'] = $phpunitConfiguration['convertNoticesToExceptions'];
            }

            if (isset($phpunitConfiguration['convertWarningsToExceptions']) && !isset($arguments['convertWarningsToExceptions'])) {
                $arguments['convertWarningsToExceptions'] = $phpunitConfiguration['convertWarningsToExceptions'];
            }

            if (isset($phpunitConfiguration['processIsolation']) && !isset($arguments['processIsolation'])) {
                $arguments['processIsolation'] = $phpunitConfiguration['processIsolation'];
            }

            if (isset($phpunitConfiguration['stopOnDefect']) && !isset($arguments['stopOnDefect'])) {
                $arguments['stopOnDefect'] = $phpunitConfiguration['stopOnDefect'];
            }

            if (isset($phpunitConfiguration['stopOnError']) && !isset($arguments['stopOnError'])) {
                $arguments['stopOnError'] = $phpunitConfiguration['stopOnError'];
            }

            if (isset($phpunitConfiguration['stopOnFailure']) && !isset($arguments['stopOnFailure'])) {
                $arguments['stopOnFailure'] = $phpunitConfiguration['stopOnFailure'];
            }

            if (isset($phpunitConfiguration['stopOnWarning']) && !isset($arguments['stopOnWarning'])) {
                $arguments['stopOnWarning'] = $phpunitConfiguration['stopOnWarning'];
            }

            if (isset($phpunitConfiguration['stopOnIncomplete']) && !isset($arguments['stopOnIncomplete'])) {
                $arguments['stopOnIncomplete'] = $phpunitConfiguration['stopOnIncomplete'];
            }

            if (isset($phpunitConfiguration['stopOnRisky']) && !isset($arguments['stopOnRisky'])) {
                $arguments['stopOnRisky'] = $phpunitConfiguration['stopOnRisky'];
            }

            if (isset($phpunitConfiguration['stopOnSkipped']) && !isset($arguments['stopOnSkipped'])) {
                $arguments['stopOnSkipped'] = $phpunitConfiguration['stopOnSkipped'];
            }

            if (isset($phpunitConfiguration['failOnWarning']) && !isset($arguments['failOnWarning'])) {
                $arguments['failOnWarning'] = $phpunitConfiguration['failOnWarning'];
            }

            if (isset($phpunitConfiguration['failOnRisky']) && !isset($arguments['failOnRisky'])) {
                $arguments['failOnRisky'] = $phpunitConfiguration['failOnRisky'];
            }

            if (isset($phpunitConfiguration['timeoutForSmallTests']) && !isset($arguments['timeoutForSmallTests'])) {
                $arguments['timeoutForSmallTests'] = $phpunitConfiguration['timeoutForSmallTests'];
            }

            if (isset($phpunitConfiguration['timeoutForMediumTests']) && !isset($arguments['timeoutForMediumTests'])) {
                $arguments['timeoutForMediumTests'] = $phpunitConfiguration['timeoutForMediumTests'];
            }

            if (isset($phpunitConfiguration['timeoutForLargeTests']) && !isset($arguments['timeoutForLargeTests'])) {
                $arguments['timeoutForLargeTests'] = $phpunitConfiguration['timeoutForLargeTests'];
            }

            if (isset($phpunitConfiguration['reportUselessTests']) && !isset($arguments['reportUselessTests'])) {
                $arguments['reportUselessTests'] = $phpunitConfiguration['reportUselessTests'];
            }

            if (isset($phpunitConfiguration['strictCoverage']) && !isset($arguments['strictCoverage'])) {
                $arguments['strictCoverage'] = $phpunitConfiguration['strictCoverage'];
            }

            if (isset($phpunitConfiguration['ignoreDeprecatedCodeUnitsFromCodeCoverage']) && !isset($arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'])) {
                $arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'] = $phpunitConfiguration['ignoreDeprecatedCodeUnitsFromCodeCoverage'];
            }

            if (isset($phpunitConfiguration['disallowTestOutput']) && !isset($arguments['disallowTestOutput'])) {
                $arguments['disallowTestOutput'] = $phpunitConfiguration['disallowTestOutput'];
            }

            if (isset($phpunitConfiguration['defaultTimeLimit']) && !isset($arguments['defaultTimeLimit'])) {
                $arguments['defaultTimeLimit'] = $phpunitConfiguration['defaultTimeLimit'];
            }

            if (isset($phpunitConfiguration['enforceTimeLimit']) && !isset($arguments['enforceTimeLimit'])) {
                $arguments['enforceTimeLimit'] = $phpunitConfiguration['enforceTimeLimit'];
            }

            if (isset($phpunitConfiguration['disallowTodoAnnotatedTests']) && !isset($arguments['disallowTodoAnnotatedTests'])) {
                $arguments['disallowTodoAnnotatedTests'] = $phpunitConfiguration['disallowTodoAnnotatedTests'];
            }

            if (isset($phpunitConfiguration['beStrictAboutResourceUsageDuringSmallTests']) && !isset($arguments['beStrictAboutResourceUsageDuringSmallTests'])) {
                $arguments['beStrictAboutResourceUsageDuringSmallTests'] = $phpunitConfiguration['beStrictAboutResourceUsageDuringSmallTests'];
            }

            if (isset($phpunitConfiguration['verbose']) && !isset($arguments['verbose'])) {
                $arguments['verbose'] = $phpunitConfiguration['verbose'];
            }

            if (isset($phpunitConfiguration['reverseDefectList']) && !isset($arguments['reverseList'])) {
                $arguments['reverseList'] = $phpunitConfiguration['reverseDefectList'];
            }

            if (isset($phpunitConfiguration['forceCoversAnnotation']) && !isset($arguments['forceCoversAnnotation'])) {
                $arguments['forceCoversAnnotation'] = $phpunitConfiguration['forceCoversAnnotation'];
            }

            if (isset($phpunitConfiguration['disableCodeCoverageIgnore']) && !isset($arguments['disableCodeCoverageIgnore'])) {
                $arguments['disableCodeCoverageIgnore'] = $phpunitConfiguration['disableCodeCoverageIgnore'];
            }

            if (isset($phpunitConfiguration['registerMockObjectsFromTestArgumentsRecursively']) && !isset($arguments['registerMockObjectsFromTestArgumentsRecursively'])) {
                $arguments['registerMockObjectsFromTestArgumentsRecursively'] = $phpunitConfiguration['registerMockObjectsFromTestArgumentsRecursively'];
            }

            if (isset($phpunitConfiguration['executionOrder']) && !isset($arguments['executionOrder'])) {
                $arguments['executionOrder'] = $phpunitConfiguration['executionOrder'];
            }

            if (isset($phpunitConfiguration['executionOrderDefects']) && !isset($arguments['executionOrderDefects'])) {
                $arguments['executionOrderDefects'] = $phpunitConfiguration['executionOrderDefects'];
            }

            if (isset($phpunitConfiguration['resolveDependencies']) && !isset($arguments['resolveDependencies'])) {
                $arguments['resolveDependencies'] = $phpunitConfiguration['resolveDependencies'];
            }

            if (isset($phpunitConfiguration['noInteraction']) && !isset($arguments['noInteraction'])) {
                $arguments['noInteraction'] = $phpunitConfiguration['noInteraction'];
            }

            if (isset($phpunitConfiguration['conflictBetweenPrinterClassAndTestdox'])) {
                $arguments['conflictBetweenPrinterClassAndTestdox'] = true;
            }

            $groupCliArgs = [];

            if (!empty($arguments['groups'])) {
                $groupCliArgs = $arguments['groups'];
            }

            $groupConfiguration = $arguments['configuration']->getGroupConfiguration();

            if (!empty($groupConfiguration['include']) && !isset($arguments['groups'])) {
                $arguments['groups'] = $groupConfiguration['include'];
            }

            if (!empty($groupConfiguration['exclude']) && !isset($arguments['excludeGroups'])) {
                $arguments['excludeGroups'] = array_diff($groupConfiguration['exclude'], $groupCliArgs);
            }

            foreach ($arguments['configuration']->getExtensionConfiguration() as $extension) {
                if ($extension['file'] !== '' && !class_exists($extension['class'], false)) {
                    require_once $extension['file'];
                }

                if (!class_exists($extension['class'])) {
                    throw new Exception(
                        sprintf(
                            'Class "%s" does not exist',
                            $extension['class']
                        )
                    );
                }

                try {
                    $extensionClass = new ReflectionClass($extension['class']);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if (!$extensionClass->implementsInterface(Hook::class)) {
                    throw new Exception(
                        sprintf(
                            'Class "%s" does not implement a PHPUnit\Runner\Hook interface',
                            $extension['class']
                        )
                    );
                }

                if (count($extension['arguments']) === 0) {
                    $extensionObject = $extensionClass->newInstance();
                } else {
                    $extensionObject = $extensionClass->newInstanceArgs(
                        $extension['arguments']
                    );
                }

                assert($extensionObject instanceof Hook);

                $this->addExtension($extensionObject);
            }

            foreach ($arguments['configuration']->getListenerConfiguration() as $listener) {
                if ($listener['file'] !== '' && !class_exists($listener['class'], false)) {
                    require_once $listener['file'];
                }

                if (!class_exists($listener['class'])) {
                    throw new Exception(
                        sprintf(
                            'Class "%s" does not exist',
                            $listener['class']
                        )
                    );
                }

                try {
                    $listenerClass = new ReflectionClass($listener['class']);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if (!$listenerClass->implementsInterface(TestListener::class)) {
                    throw new Exception(
                        sprintf(
                            'Class "%s" does not implement the PHPUnit\Framework\TestListener interface',
                            $listener['class']
                        )
                    );
                }

                if (count($listener['arguments']) === 0) {
                    $listener = new $listener['class'];
                } else {
                    $listener = $listenerClass->newInstanceArgs(
                        $listener['arguments']
                    );
                }

                $arguments['listeners'][] = $listener;
            }

            $loggingConfiguration = $arguments['configuration']->getLoggingConfiguration();

            if (isset($loggingConfiguration['coverage-clover']) && !isset($arguments['coverageClover'])) {
                $arguments['coverageClover'] = $loggingConfiguration['coverage-clover'];
            }

            if (isset($loggingConfiguration['coverage-crap4j']) && !isset($arguments['coverageCrap4J'])) {
                $arguments['coverageCrap4J'] = $loggingConfiguration['coverage-crap4j'];

                if (isset($loggingConfiguration['crap4jThreshold']) && !isset($arguments['crap4jThreshold'])) {
                    $arguments['crap4jThreshold'] = $loggingConfiguration['crap4jThreshold'];
                }
            }

            if (isset($loggingConfiguration['coverage-html']) && !isset($arguments['coverageHtml'])) {
                if (isset($loggingConfiguration['lowUpperBound']) && !isset($arguments['reportLowUpperBound'])) {
                    $arguments['reportLowUpperBound'] = $loggingConfiguration['lowUpperBound'];
                }

                if (isset($loggingConfiguration['highLowerBound']) && !isset($arguments['reportHighLowerBound'])) {
                    $arguments['reportHighLowerBound'] = $loggingConfiguration['highLowerBound'];
                }

                $arguments['coverageHtml'] = $loggingConfiguration['coverage-html'];
            }

            if (isset($loggingConfiguration['coverage-php']) && !isset($arguments['coveragePHP'])) {
                $arguments['coveragePHP'] = $loggingConfiguration['coverage-php'];
            }

            if (isset($loggingConfiguration['coverage-text']) && !isset($arguments['coverageText'])) {
                $arguments['coverageText']                   = $loggingConfiguration['coverage-text'];
                $arguments['coverageTextShowUncoveredFiles'] = $loggingConfiguration['coverageTextShowUncoveredFiles'] ?? false;
                $arguments['coverageTextShowOnlySummary']    = $loggingConfiguration['coverageTextShowOnlySummary'] ?? false;
            }

            if (isset($loggingConfiguration['coverage-xml']) && !isset($arguments['coverageXml'])) {
                $arguments['coverageXml'] = $loggingConfiguration['coverage-xml'];
            }

            if (isset($loggingConfiguration['plain'])) {
                $arguments['listeners'][] = new ResultPrinter(
                    $loggingConfiguration['plain'],
                    true
                );
            }

            if (isset($loggingConfiguration['teamcity']) && !isset($arguments['teamcityLogfile'])) {
                $arguments['teamcityLogfile'] = $loggingConfiguration['teamcity'];
            }

            if (isset($loggingConfiguration['junit']) && !isset($arguments['junitLogfile'])) {
                $arguments['junitLogfile'] = $loggingConfiguration['junit'];
            }

            if (isset($loggingConfiguration['testdox-html']) && !isset($arguments['testdoxHTMLFile'])) {
                $arguments['testdoxHTMLFile'] = $loggingConfiguration['testdox-html'];
            }

            if (isset($loggingConfiguration['testdox-text']) && !isset($arguments['testdoxTextFile'])) {
                $arguments['testdoxTextFile'] = $loggingConfiguration['testdox-text'];
            }

            if (isset($loggingConfiguration['testdox-xml']) && !isset($arguments['testdoxXMLFile'])) {
                $arguments['testdoxXMLFile'] = $loggingConfiguration['testdox-xml'];
            }

            $testdoxGroupConfiguration = $arguments['configuration']->getTestdoxGroupConfiguration();

            if (isset($testdoxGroupConfiguration['include']) &&
                !isset($arguments['testdoxGroups'])) {
                $arguments['testdoxGroups'] = $testdoxGroupConfiguration['include'];
            }

            if (isset($testdoxGroupConfiguration['exclude']) &&
                !isset($arguments['testdoxExcludeGroups'])) {
                $arguments['testdoxExcludeGroups'] = $testdoxGroupConfiguration['exclude'];
            }
        }

        $arguments['addUncoveredFilesFromWhitelist']                  = $arguments['addUncoveredFilesFromWhitelist'] ?? true;
        $arguments['backupGlobals']                                   = $arguments['backupGlobals'] ?? null;
        $arguments['backupStaticAttributes']                          = $arguments['backupStaticAttributes'] ?? null;
        $arguments['beStrictAboutChangesToGlobalState']               = $arguments['beStrictAboutChangesToGlobalState'] ?? null;
        $arguments['beStrictAboutResourceUsageDuringSmallTests']      = $arguments['beStrictAboutResourceUsageDuringSmallTests'] ?? false;
        $arguments['cacheResult']                                     = $arguments['cacheResult'] ?? true;
        $arguments['cacheTokens']                                     = $arguments['cacheTokens'] ?? false;
        $arguments['colors']                                          = $arguments['colors'] ?? ResultPrinter::COLOR_DEFAULT;
        $arguments['columns']                                         = $arguments['columns'] ?? 80;
        $arguments['convertDeprecationsToExceptions']                 = $arguments['convertDeprecationsToExceptions'] ?? false;
        $arguments['convertErrorsToExceptions']                       = $arguments['convertErrorsToExceptions'] ?? true;
        $arguments['convertNoticesToExceptions']                      = $arguments['convertNoticesToExceptions'] ?? true;
        $arguments['convertWarningsToExceptions']                     = $arguments['convertWarningsToExceptions'] ?? true;
        $arguments['crap4jThreshold']                                 = $arguments['crap4jThreshold'] ?? 30;
        $arguments['disallowTestOutput']                              = $arguments['disallowTestOutput'] ?? false;
        $arguments['disallowTodoAnnotatedTests']                      = $arguments['disallowTodoAnnotatedTests'] ?? false;
        $arguments['defaultTimeLimit']                                = $arguments['defaultTimeLimit'] ?? 0;
        $arguments['enforceTimeLimit']                                = $arguments['enforceTimeLimit'] ?? false;
        $arguments['excludeGroups']                                   = $arguments['excludeGroups'] ?? [];
        $arguments['executionOrder']                                  = $arguments['executionOrder'] ?? TestSuiteSorter::ORDER_DEFAULT;
        $arguments['executionOrderDefects']                           = $arguments['executionOrderDefects'] ?? TestSuiteSorter::ORDER_DEFAULT;
        $arguments['failOnRisky']                                     = $arguments['failOnRisky'] ?? false;
        $arguments['failOnWarning']                                   = $arguments['failOnWarning'] ?? false;
        $arguments['groups']                                          = $arguments['groups'] ?? [];
        $arguments['noInteraction']                                   = $arguments['noInteraction'] ?? false;
        $arguments['processIsolation']                                = $arguments['processIsolation'] ?? false;
        $arguments['processUncoveredFilesFromWhitelist']              = $arguments['processUncoveredFilesFromWhitelist'] ?? false;
        $arguments['randomOrderSeed']                                 = $arguments['randomOrderSeed'] ?? time();
        $arguments['registerMockObjectsFromTestArgumentsRecursively'] = $arguments['registerMockObjectsFromTestArgumentsRecursively'] ?? false;
        $arguments['repeat']                                          = $arguments['repeat'] ?? false;
        $arguments['reportHighLowerBound']                            = $arguments['reportHighLowerBound'] ?? 90;
        $arguments['reportLowUpperBound']                             = $arguments['reportLowUpperBound'] ?? 50;
        $arguments['reportUselessTests']                              = $arguments['reportUselessTests'] ?? true;
        $arguments['reverseList']                                     = $arguments['reverseList'] ?? false;
        $arguments['resolveDependencies']                             = $arguments['resolveDependencies'] ?? true;
        $arguments['stopOnError']                                     = $arguments['stopOnError'] ?? false;
        $arguments['stopOnFailure']                                   = $arguments['stopOnFailure'] ?? false;
        $arguments['stopOnIncomplete']                                = $arguments['stopOnIncomplete'] ?? false;
        $arguments['stopOnRisky']                                     = $arguments['stopOnRisky'] ?? false;
        $arguments['stopOnSkipped']                                   = $arguments['stopOnSkipped'] ?? false;
        $arguments['stopOnWarning']                                   = $arguments['stopOnWarning'] ?? false;
        $arguments['stopOnDefect']                                    = $arguments['stopOnDefect'] ?? false;
        $arguments['strictCoverage']                                  = $arguments['strictCoverage'] ?? false;
        $arguments['testdoxExcludeGroups']                            = $arguments['testdoxExcludeGroups'] ?? [];
        $arguments['testdoxGroups']                                   = $arguments['testdoxGroups'] ?? [];
        $arguments['timeoutForLargeTests']                            = $arguments['timeoutForLargeTests'] ?? 60;
        $arguments['timeoutForMediumTests']                           = $arguments['timeoutForMediumTests'] ?? 10;
        $arguments['timeoutForSmallTests']                            = $arguments['timeoutForSmallTests'] ?? 1;
        $arguments['verbose']                                         = $arguments['verbose'] ?? false;

        if ($arguments['reportLowUpperBound'] > $arguments['reportHighLowerBound']) {
            $arguments['reportLowUpperBound']  = 50;
            $arguments['reportHighLowerBound'] = 90;
        }
    }

    private function processSuiteFilters(TestSuite $suite, array $arguments): void
    {
        if (!$arguments['filter'] &&
            empty($arguments['groups']) &&
            empty($arguments['excludeGroups'])) {
            return;
        }

        $filterFactory = new Factory;

        if (!empty($arguments['excludeGroups'])) {
            $filterFactory->addFilter(
                new ReflectionClass(ExcludeGroupFilterIterator::class),
                $arguments['excludeGroups']
            );
        }

        if (!empty($arguments['groups'])) {
            $filterFactory->addFilter(
                new ReflectionClass(IncludeGroupFilterIterator::class),
                $arguments['groups']
            );
        }

        if ($arguments['filter']) {
            $filterFactory->addFilter(
                new ReflectionClass(NameFilterIterator::class),
                $arguments['filter']
            );
        }

        $suite->injectFilter($filterFactory);
    }

    private function writeMessage(string $type, string $message): void
    {
        if (!$this->messagePrinted) {
            $this->write("\n");
        }

        $this->write(
            sprintf(
                "%-15s%s\n",
                $type . ':',
                $message
            )
        );

        $this->messagePrinted = true;
    }

    /**
     * @template T as Printer
     *
     * @param class-string<T> $class
     *
     * @return T
     */
    private function createPrinter(string $class, array $arguments): Printer
    {
        return new $class(
            (isset($arguments['stderr']) && $arguments['stderr'] === true) ? 'php://stderr' : null,
            $arguments['verbose'],
            $arguments['colors'],
            $arguments['debug'],
            $arguments['columns'],
            $arguments['reverseList']
        );
    }

    private function codeCoverageGenerationStart(string $format): void
    {
        $this->write(
            sprintf(
                "\nGenerating code coverage report in %s format ... ",
                $format
            )
        );

        Timer::start();
    }

    private function codeCoverageGenerationSucceeded(): void
    {
        $this->write(
            sprintf(
                "done [%s]\n",
                Timer::secondsToTimeString(Timer::stop())
            )
        );
    }

    private function codeCoverageGenerationFailed(\Exception $e): void
    {
        $this->write(
            sprintf(
                "failed [%s]\n%s\n",
                Timer::secondsToTimeString(Timer::stop()),
                $e->getMessage()
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI;

use const PHP_EOL;
use function count;
use function explode;
use function max;
use function preg_replace_callback;
use function str_pad;
use function str_repeat;
use function strlen;
use function wordwrap;
use PHPUnit\Util\Color;
use SebastianBergmann\Environment\Console;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Help
{
    private const LEFT_MARGIN = '  ';

    private const HELP_TEXT = [
        'Usage'                  => [
            ['text' => 'phpunit [options] UnitTest [UnitTest.php]'],
            ['text' => 'phpunit [options] <directory>'],
        ],
        'Code Coverage Options'  => [
            ['arg' => '--coverage-clover <file>', 'desc' => 'Generate code coverage report in Clover XML format'],
            ['arg' => '--coverage-crap4j <file>', 'desc' => 'Generate code coverage report in Crap4J XML format'],
            ['arg' => '--coverage-html <dir>', 'desc' => 'Generate code coverage report in HTML format'],
            ['arg' => '--coverage-php <file>', 'desc' => 'Export PHP_CodeCoverage object to file'],
            ['arg' => '--coverage-text=<file>', 'desc' => 'Generate code coverage report in text format [default: standard output]'],
            ['arg' => '--coverage-xml <dir>', 'desc' => 'Generate code coverage report in PHPUnit XML format'],
            ['arg' => '--whitelist <dir>', 'desc' => 'Whitelist <dir> for code coverage analysis'],
            ['arg' => '--disable-coverage-ignore', 'desc' => 'Disable annotations for ignoring code coverage'],
            ['arg' => '--no-coverage', 'desc' => 'Ignore code coverage configuration'],
            ['arg' => '--dump-xdebug-filter <file>', 'desc' => 'Generate script to set Xdebug code coverage filter'],
        ],

        'Logging Options'        => [
            ['arg' => '--log-junit <file>', 'desc' => 'Log test execution in JUnit XML format to file'],
            ['arg' => '--log-teamcity <file>', 'desc' => 'Log test execution in TeamCity format to file'],
            ['arg' => '--testdox-html <file>', 'desc' => 'Write agile documentation in HTML format to file'],
            ['arg' => '--testdox-text <file>', 'desc' => 'Write agile documentation in Text format to file'],
            ['arg' => '--testdox-xml <file>', 'desc' => 'Write agile documentation in XML format to file'],
            ['arg' => '--reverse-list', 'desc' => 'Print defects in reverse order'],
            ['arg' => '--no-logging', 'desc' => 'Ignore logging configuration'],
        ],

        'Test Selection Options' => [
            ['arg' => '--filter <pattern>', 'desc' => 'Filter which tests to run'],
            ['arg' => '--testsuite <name>', 'desc' => 'Filter which testsuite to run'],
            ['arg' => '--group <name>', 'desc' => 'Only runs tests from the specified group(s)'],
            ['arg' => '--exclude-group <name>', 'desc' => 'Exclude tests from the specified group(s)'],
            ['arg' => '--list-groups', 'desc' => 'List available test groups'],
            ['arg' => '--list-suites', 'desc' => 'List available test suites'],
            ['arg' => '--list-tests', 'desc' => 'List available tests'],
            ['arg' => '--list-tests-xml <file>', 'desc' => 'List available tests in XML format'],
            ['arg' => '--test-suffix <suffixes>', 'desc' => 'Only search for test in files with specified suffix(es). Default: Test.php,.phpt'],
        ],

        'Test Execution Options' => [
            ['arg' => '--dont-report-useless-tests', 'desc' => 'Do not report tests that do not test anything'],
            ['arg'    => '--strict-coverage', 'desc' => 'Be strict about @covers annotation usage'],
            ['arg'    => '--strict-global-state', 'desc' => 'Be strict about changes to global state'],
            ['arg'    => '--disallow-test-output', 'desc' => 'Be strict about output during tests'],
            ['arg'    => '--disallow-resource-usage', 'desc' => 'Be strict about resource usage during small tests'],
            ['arg'    => '--enforce-time-limit', 'desc' => 'Enforce time limit based on test size'],
            ['arg'    => '--default-time-limit=<sec>', 'desc' => 'Timeout in seconds for tests without @small, @medium or @large'],
            ['arg'    => '--disallow-todo-tests', 'desc' => 'Disallow @todo-annotated tests'],
            ['spacer' => ''],

            ['arg'    => '--process-isolation', 'desc' => 'Run each test in a separate PHP process'],
            ['arg'    => '--globals-backup', 'desc' => 'Backup and restore $GLOBALS for each test'],
            ['arg'    => '--static-backup', 'desc' => 'Backup and restore static attributes for each test'],
            ['spacer' => ''],

            ['arg'    => '--colors=<flag>', 'desc' => 'Use colors in output ("never", "auto" or "always")'],
            ['arg'    => '--columns <n>', 'desc' => 'Number of columns to use for progress output'],
            ['arg'    => '--columns max', 'desc' => 'Use maximum number of columns for progress output'],
            ['arg'    => '--stderr', 'desc' => 'Write to STDERR instead of STDOUT'],
            ['arg'    => '--stop-on-defect', 'desc' => 'Stop execution upon first not-passed test'],
            ['arg'    => '--stop-on-error', 'desc' => 'Stop execution upon first error'],
            ['arg'    => '--stop-on-failure', 'desc' => 'Stop execution upon first error or failure'],
            ['arg'    => '--stop-on-warning', 'desc' => 'Stop execution upon first warning'],
            ['arg'    => '--stop-on-risky', 'desc' => 'Stop execution upon first risky test'],
            ['arg'    => '--stop-on-skipped', 'desc' => 'Stop execution upon first skipped test'],
            ['arg'    => '--stop-on-incomplete', 'desc' => 'Stop execution upon first incomplete test'],
            ['arg'    => '--fail-on-warning', 'desc' => 'Treat tests with warnings as failures'],
            ['arg'    => '--fail-on-risky', 'desc' => 'Treat risky tests as failures'],
            ['arg'    => '-v|--verbose', 'desc' => 'Output more verbose information'],
            ['arg'    => '--debug', 'desc' => 'Display debugging information'],
            ['spacer' => ''],

            ['arg'    => '--loader <loader>', 'desc' => 'TestSuiteLoader implementation to use'],
            ['arg'    => '--repeat <times>', 'desc' => 'Runs the test(s) repeatedly'],
            ['arg'    => '--teamcity', 'desc' => 'Report test execution progress in TeamCity format'],
            ['arg'    => '--testdox', 'desc' => 'Report test execution progress in TestDox format'],
            ['arg'    => '--testdox-group', 'desc' => 'Only include tests from the specified group(s)'],
            ['arg'    => '--testdox-exclude-group', 'desc' => 'Exclude tests from the specified group(s)'],
            ['arg'    => '--no-interaction', 'desc' => 'Disable TestDox progress animation'],
            ['arg'    => '--printer <printer>', 'desc' => 'TestListener implementation to use'],
            ['spacer' => ''],

            ['arg'    => '--order-by=<order>', 'desc' => 'Run tests in order: default|defects|duration|no-depends|random|reverse|size'],
            ['arg'    => '--random-order-seed=<N>', 'desc' => 'Use a specific random seed <N> for random order'],
            ['arg'    => '--cache-result', 'desc' => 'Write test results to cache file'],
            ['arg'    => '--do-not-cache-result', 'desc' => 'Do not write test results to cache file'],
        ],

        'Configuration Options'  => [
            ['arg' => '--prepend <file>', 'desc' => 'A PHP script that is included as early as possible'],
            ['arg' => '--bootstrap <file>', 'desc' => 'A PHP script that is included before the tests run'],
            ['arg' => '-c|--configuration <file>', 'desc' => 'Read configuration from XML file'],
            ['arg' => '--no-configuration', 'desc' => 'Ignore default configuration file (phpunit.xml)'],
            ['arg' => '--no-extensions', 'desc' => 'Do not load PHPUnit extensions'],
            ['arg' => '--include-path <path(s)>', 'desc' => 'Prepend PHP\'s include_path with given path(s)'],
            ['arg' => '-d <key[=value]>', 'desc' => 'Sets a php.ini value'],
            ['arg' => '--generate-configuration', 'desc' => 'Generate configuration file with suggested settings'],
            ['arg' => '--cache-result-file=<file>', 'desc' => 'Specify result cache path and filename'],
        ],

        'Miscellaneous Options'  => [
            ['arg' => '-h|--help', 'desc' => 'Prints this usage information'],
            ['arg' => '--version', 'desc' => 'Prints the version and exits'],
            ['arg' => '--atleast-version <min>', 'desc' => 'Checks that version is greater than min and exits'],
            ['arg' => '--check-version', 'desc' => 'Check whether PHPUnit is the latest version'],
        ],

    ];

    /**
     * @var int Number of columns required to write the longest option name to the console
     */
    private $maxArgLength = 0;

    /**
     * @var int Number of columns left for the description field after padding and option
     */
    private $maxDescLength;

    /**
     * @var bool Use color highlights for sections, options and parameters
     */
    private $hasColor = false;

    public function __construct(?int $width = null, ?bool $withColor = null)
    {
        if ($width === null) {
            $width = (new Console)->getNumberOfColumns();
        }

        if ($withColor === null) {
            $this->hasColor = (new Console)->hasColorSupport();
        } else {
            $this->hasColor = $withColor;
        }

        foreach (self::HELP_TEXT as $options) {
            foreach ($options as $option) {
                if (isset($option['arg'])) {
                    $this->maxArgLength = max($this->maxArgLength, isset($option['arg']) ? strlen($option['arg']) : 0);
                }
            }
        }

        $this->maxDescLength = $width - $this->maxArgLength - 4;
    }

    /**
     * Write the help file to the CLI, adapting width and colors to the console.
     */
    public function writeToConsole(): void
    {
        if ($this->hasColor) {
            $this->writeWithColor();
        } else {
            $this->writePlaintext();
        }
    }

    private function writePlaintext(): void
    {
        foreach (self::HELP_TEXT as $section => $options) {
            print "{$section}:" . PHP_EOL;

            if ($section !== 'Usage') {
                print PHP_EOL;
            }

            foreach ($options as $option) {
                if (isset($option['spacer'])) {
                    print PHP_EOL;
                }

                if (isset($option['text'])) {
                    print self::LEFT_MARGIN . $option['text'] . PHP_EOL;
                }

                if (isset($option['arg'])) {
                    $arg = str_pad($option['arg'], $this->maxArgLength);
                    print self::LEFT_MARGIN . $arg . ' ' . $option['desc'] . PHP_EOL;
                }
            }

            print PHP_EOL;
        }
    }

    private function writeWithColor(): void
    {
        foreach (self::HELP_TEXT as $section => $options) {
            print Color::colorize('fg-yellow', "{$section}:") . PHP_EOL;

            foreach ($options as $option) {
                if (isset($option['spacer'])) {
                    print PHP_EOL;
                }

                if (isset($option['text'])) {
                    print self::LEFT_MARGIN . $option['text'] . PHP_EOL;
                }

                if (isset($option['arg'])) {
                    $arg = Color::colorize('fg-green', str_pad($option['arg'], $this->maxArgLength));
                    $arg = preg_replace_callback(
                        '/(<[^>]+>)/',
                        static function ($matches)
                        {
                            return Color::colorize('fg-cyan', $matches[0]);
                        },
                        $arg
                    );
                    $desc = explode(PHP_EOL, wordwrap($option['desc'], $this->maxDescLength, PHP_EOL));

                    print self::LEFT_MARGIN . $arg . ' ' . $desc[0] . PHP_EOL;

                    for ($i = 1; $i < count($desc); $i++) {
                        print str_repeat(' ', $this->maxArgLength + 3) . $desc[$i] . PHP_EOL;
                    }
                }
            }

            print PHP_EOL;
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI;

use const PATH_SEPARATOR;
use const PHP_EOL;
use const STDIN;
use function array_keys;
use function assert;
use function class_exists;
use function explode;
use function extension_loaded;
use function fgets;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function getcwd;
use function ini_get;
use function ini_set;
use function is_callable;
use function is_dir;
use function is_file;
use function is_numeric;
use function is_string;
use function printf;
use function realpath;
use function sort;
use function sprintf;
use function str_replace;
use function stream_resolve_include_path;
use function strrpos;
use function substr;
use function trim;
use function version_compare;
use PharIo\Manifest\ApplicationName;
use PharIo\Manifest\Exception as ManifestException;
use PharIo\Manifest\ManifestLoader;
use PharIo\Version\Version as PharIoVersion;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\StandardTestSuiteLoader;
use PHPUnit\Runner\TestSuiteLoader;
use PHPUnit\Runner\TestSuiteSorter;
use PHPUnit\Runner\Version;
use PHPUnit\Util\Configuration;
use PHPUnit\Util\ConfigurationGenerator;
use PHPUnit\Util\FileLoader;
use PHPUnit\Util\Filesystem;
use PHPUnit\Util\Getopt;
use PHPUnit\Util\Log\TeamCity;
use PHPUnit\Util\Printer;
use PHPUnit\Util\TestDox\CliTestDoxPrinter;
use PHPUnit\Util\TextTestListRenderer;
use PHPUnit\Util\XmlTestListRenderer;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
use Throwable;

/**
 * A TestRunner for the Command Line Interface (CLI)
 * PHP SAPI Module.
 */
class Command
{
    /**
     * @var array<string,mixed>
     */
    protected $arguments = [
        'listGroups'              => false,
        'listSuites'              => false,
        'listTests'               => false,
        'listTestsXml'            => false,
        'loader'                  => null,
        'useDefaultConfiguration' => true,
        'loadedExtensions'        => [],
        'notLoadedExtensions'     => [],
    ];

    /**
     * @var array<string,mixed>
     */
    protected $options = [];

    /**
     * @var array<string,mixed>
     */
    protected $longOptions = [
        'atleast-version='          => null,
        'prepend='                  => null,
        'bootstrap='                => null,
        'cache-result'              => null,
        'do-not-cache-result'       => null,
        'cache-result-file='        => null,
        'check-version'             => null,
        'colors=='                  => null,
        'columns='                  => null,
        'configuration='            => null,
        'coverage-clover='          => null,
        'coverage-crap4j='          => null,
        'coverage-html='            => null,
        'coverage-php='             => null,
        'coverage-text=='           => null,
        'coverage-xml='             => null,
        'debug'                     => null,
        'disallow-test-output'      => null,
        'disallow-resource-usage'   => null,
        'disallow-todo-tests'       => null,
        'default-time-limit='       => null,
        'enforce-time-limit'        => null,
        'exclude-group='            => null,
        'filter='                   => null,
        'generate-configuration'    => null,
        'globals-backup'            => null,
        'group='                    => null,
        'help'                      => null,
        'resolve-dependencies'      => null,
        'ignore-dependencies'       => null,
        'include-path='             => null,
        'list-groups'               => null,
        'list-suites'               => null,
        'list-tests'                => null,
        'list-tests-xml='           => null,
        'loader='                   => null,
        'log-junit='                => null,
        'log-teamcity='             => null,
        'no-configuration'          => null,
        'no-coverage'               => null,
        'no-logging'                => null,
        'no-interaction'            => null,
        'no-extensions'             => null,
        'order-by='                 => null,
        'printer='                  => null,
        'process-isolation'         => null,
        'repeat='                   => null,
        'dont-report-useless-tests' => null,
        'random-order'              => null,
        'random-order-seed='        => null,
        'reverse-order'             => null,
        'reverse-list'              => null,
        'static-backup'             => null,
        'stderr'                    => null,
        'stop-on-defect'            => null,
        'stop-on-error'             => null,
        'stop-on-failure'           => null,
        'stop-on-warning'           => null,
        'stop-on-incomplete'        => null,
        'stop-on-risky'             => null,
        'stop-on-skipped'           => null,
        'fail-on-warning'           => null,
        'fail-on-risky'             => null,
        'strict-coverage'           => null,
        'disable-coverage-ignore'   => null,
        'strict-global-state'       => null,
        'teamcity'                  => null,
        'testdox'                   => null,
        'testdox-group='            => null,
        'testdox-exclude-group='    => null,
        'testdox-html='             => null,
        'testdox-text='             => null,
        'testdox-xml='              => null,
        'test-suffix='              => null,
        'testsuite='                => null,
        'verbose'                   => null,
        'version'                   => null,
        'whitelist='                => null,
        'dump-xdebug-filter='       => null,
    ];

    /**
     * @var @psalm-var list<string>
     */
    private $warnings = [];

    /**
     * @var bool
     */
    private $versionStringPrinted = false;

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    public static function main(bool $exit = true): int
    {
        return (new static)->run($_SERVER['argv'], $exit);
    }

    /**
     * @throws Exception
     */
    public function run(array $argv, bool $exit = true): int
    {
        $this->handleArguments($argv);

        $runner = $this->createRunner();

        if ($this->arguments['test'] instanceof Test) {
            $suite = $this->arguments['test'];
        } else {
            $suite = $runner->getTest(
                $this->arguments['test'],
                $this->arguments['testFile'],
                $this->arguments['testSuffixes']
            );
        }

        if ($this->arguments['listGroups']) {
            return $this->handleListGroups($suite, $exit);
        }

        if ($this->arguments['listSuites']) {
            return $this->handleListSuites($exit);
        }

        if ($this->arguments['listTests']) {
            return $this->handleListTests($suite, $exit);
        }

        if ($this->arguments['listTestsXml']) {
            return $this->handleListTestsXml($suite, $this->arguments['listTestsXml'], $exit);
        }

        unset($this->arguments['test'], $this->arguments['testFile']);

        try {
            $result = $runner->doRun($suite, $this->arguments, $this->warnings, $exit);
        } catch (Exception $e) {
            print $e->getMessage() . PHP_EOL;
        }

        $return = TestRunner::FAILURE_EXIT;

        if (isset($result) && $result->wasSuccessful()) {
            $return = TestRunner::SUCCESS_EXIT;
        } elseif (!isset($result) || $result->errorCount() > 0) {
            $return = TestRunner::EXCEPTION_EXIT;
        }

        if ($exit) {
            exit($return);
        }

        return $return;
    }

    /**
     * Create a TestRunner, override in subclasses.
     */
    protected function createRunner(): TestRunner
    {
        return new TestRunner($this->arguments['loader']);
    }

    /**
     * Handles the command-line arguments.
     *
     * A child class of PHPUnit\TextUI\Command can hook into the argument
     * parsing by adding the switch(es) to the $longOptions array and point to a
     * callback method that handles the switch(es) in the child class like this
     *
     * <code>
     * <?php
     * class MyCommand extends PHPUnit\TextUI\Command
     * {
     *     public function __construct()
     *     {
     *         // my-switch won't accept a value, it's an on/off
     *         $this->longOptions['my-switch'] = 'myHandler';
     *         // my-secondswitch will accept a value - note the equals sign
     *         $this->longOptions['my-secondswitch='] = 'myOtherHandler';
     *     }
     *
     *     // --my-switch  -> myHandler()
     *     protected function myHandler()
     *     {
     *     }
     *
     *     // --my-secondswitch foo -> myOtherHandler('foo')
     *     protected function myOtherHandler ($value)
     *     {
     *     }
     *
     *     // You will also need this - the static keyword in the
     *     // PHPUnit\TextUI\Command will mean that it'll be
     *     // PHPUnit\TextUI\Command that gets instantiated,
     *     // not MyCommand
     *     public static function main($exit = true)
     *     {
     *         $command = new static;
     *
     *         return $command->run($_SERVER['argv'], $exit);
     *     }
     *
     * }
     * </code>
     *
     * @throws Exception
     */
    protected function handleArguments(array $argv): void
    {
        try {
            $this->options = Getopt::parse(
                $argv,
                'd:c:hv',
                array_keys($this->longOptions)
            );
        } catch (Exception $t) {
            $this->exitWithErrorMessage($t->getMessage());
        }

        foreach ($this->options[0] as $option) {
            switch ($option[0]) {
                case '--colors':
                    $this->arguments['colors'] = $option[1] ?: ResultPrinter::COLOR_AUTO;

                    break;

                case '--bootstrap':
                    $this->arguments['bootstrap'] = $option[1];

                    break;

                case '--cache-result':
                    $this->arguments['cacheResult'] = true;

                    break;

                case '--do-not-cache-result':
                    $this->arguments['cacheResult'] = false;

                    break;

                case '--cache-result-file':
                    $this->arguments['cacheResultFile'] = $option[1];

                    break;

                case '--columns':
                    if (is_numeric($option[1])) {
                        $this->arguments['columns'] = (int) $option[1];
                    } elseif ($option[1] === 'max') {
                        $this->arguments['columns'] = 'max';
                    }

                    break;

                case 'c':
                case '--configuration':
                    $this->arguments['configuration'] = $option[1];

                    break;

                case '--coverage-clover':
                    $this->arguments['coverageClover'] = $option[1];

                    break;

                case '--coverage-crap4j':
                    $this->arguments['coverageCrap4J'] = $option[1];

                    break;

                case '--coverage-html':
                    $this->arguments['coverageHtml'] = $option[1];

                    break;

                case '--coverage-php':
                    $this->arguments['coveragePHP'] = $option[1];

                    break;

                case '--coverage-text':
                    if ($option[1] === null) {
                        $option[1] = 'php://stdout';
                    }

                    $this->arguments['coverageText']                   = $option[1];
                    $this->arguments['coverageTextShowUncoveredFiles'] = false;
                    $this->arguments['coverageTextShowOnlySummary']    = false;

                    break;

                case '--coverage-xml':
                    $this->arguments['coverageXml'] = $option[1];

                    break;

                case 'd':
                    $ini = explode('=', $option[1]);

                    if (isset($ini[0])) {
                        if (isset($ini[1])) {
                            ini_set($ini[0], $ini[1]);
                        } else {
                            ini_set($ini[0], '1');
                        }
                    }

                    break;

                case '--debug':
                    $this->arguments['debug'] = true;

                    break;

                case 'h':
                case '--help':
                    $this->showHelp();

                    exit(TestRunner::SUCCESS_EXIT);

                    break;

                case '--filter':
                    $this->arguments['filter'] = $option[1];

                    break;

                case '--testsuite':
                    $this->arguments['testsuite'] = $option[1];

                    break;

                case '--generate-configuration':
                    $this->printVersionString();

                    print 'Generating phpunit.xml in ' . getcwd() . PHP_EOL . PHP_EOL;

                    print 'Bootstrap script (relative to path shown above; default: vendor/autoload.php): ';
                    $bootstrapScript = trim(fgets(STDIN));

                    print 'Tests directory (relative to path shown above; default: tests): ';
                    $testsDirectory = trim(fgets(STDIN));

                    print 'Source directory (relative to path shown above; default: src): ';
                    $src = trim(fgets(STDIN));

                    print 'Cache directory (relative to path shown above; default: .phpunit.cache): ';
                    $cacheDirectory = trim(fgets(STDIN));

                    if ($bootstrapScript === '') {
                        $bootstrapScript = 'vendor/autoload.php';
                    }

                    if ($testsDirectory === '') {
                        $testsDirectory = 'tests';
                    }

                    if ($src === '') {
                        $src = 'src';
                    }

                    if ($cacheDirectory === '') {
                        $cacheDirectory = '.phpunit.cache';
                    }

                    $generator = new ConfigurationGenerator;

                    file_put_contents(
                        'phpunit.xml',
                        $generator->generateDefaultConfiguration(
                            Version::series(),
                            $bootstrapScript,
                            $testsDirectory,
                            $src,
                            $cacheDirectory
                        )
                    );

                    print PHP_EOL . 'Generated phpunit.xml in ' . getcwd() . PHP_EOL;
                    print 'Make sure to exclude the ' . $cacheDirectory . ' directory from version control.' . PHP_EOL;

                    exit(TestRunner::SUCCESS_EXIT);

                    break;

                case '--group':
                    $this->arguments['groups'] = explode(',', $option[1]);

                    break;

                case '--exclude-group':
                    $this->arguments['excludeGroups'] = explode(
                        ',',
                        $option[1]
                    );

                    break;

                case '--test-suffix':
                    $this->arguments['testSuffixes'] = explode(
                        ',',
                        $option[1]
                    );

                    break;

                case '--include-path':
                    $includePath = $option[1];

                    break;

                case '--list-groups':
                    $this->arguments['listGroups'] = true;

                    break;

                case '--list-suites':
                    $this->arguments['listSuites'] = true;

                    break;

                case '--list-tests':
                    $this->arguments['listTests'] = true;

                    break;

                case '--list-tests-xml':
                    $this->arguments['listTestsXml'] = $option[1];

                    break;

                case '--printer':
                    $this->arguments['printer'] = $option[1];

                    break;

                case '--loader':
                    $this->arguments['loader'] = $option[1];

                    break;

                case '--log-junit':
                    $this->arguments['junitLogfile'] = $option[1];

                    break;

                case '--log-teamcity':
                    $this->arguments['teamcityLogfile'] = $option[1];

                    break;

                case '--order-by':
                    $this->handleOrderByOption($option[1]);

                    break;

                case '--process-isolation':
                    $this->arguments['processIsolation'] = true;

                    break;

                case '--repeat':
                    $this->arguments['repeat'] = (int) $option[1];

                    break;

                case '--stderr':
                    $this->arguments['stderr'] = true;

                    break;

                case '--stop-on-defect':
                    $this->arguments['stopOnDefect'] = true;

                    break;

                case '--stop-on-error':
                    $this->arguments['stopOnError'] = true;

                    break;

                case '--stop-on-failure':
                    $this->arguments['stopOnFailure'] = true;

                    break;

                case '--stop-on-warning':
                    $this->arguments['stopOnWarning'] = true;

                    break;

                case '--stop-on-incomplete':
                    $this->arguments['stopOnIncomplete'] = true;

                    break;

                case '--stop-on-risky':
                    $this->arguments['stopOnRisky'] = true;

                    break;

                case '--stop-on-skipped':
                    $this->arguments['stopOnSkipped'] = true;

                    break;

                case '--fail-on-warning':
                    $this->arguments['failOnWarning'] = true;

                    break;

                case '--fail-on-risky':
                    $this->arguments['failOnRisky'] = true;

                    break;

                case '--teamcity':
                    $this->arguments['printer'] = TeamCity::class;

                    break;

                case '--testdox':
                    $this->arguments['printer'] = CliTestDoxPrinter::class;

                    break;

                case '--testdox-group':
                    $this->arguments['testdoxGroups'] = explode(
                        ',',
                        $option[1]
                    );

                    break;

                case '--testdox-exclude-group':
                    $this->arguments['testdoxExcludeGroups'] = explode(
                        ',',
                        $option[1]
                    );

                    break;

                case '--testdox-html':
                    $this->arguments['testdoxHTMLFile'] = $option[1];

                    break;

                case '--testdox-text':
                    $this->arguments['testdoxTextFile'] = $option[1];

                    break;

                case '--testdox-xml':
                    $this->arguments['testdoxXMLFile'] = $option[1];

                    break;

                case '--no-configuration':
                    $this->arguments['useDefaultConfiguration'] = false;

                    break;

                case '--no-extensions':
                    $this->arguments['noExtensions'] = true;

                    break;

                case '--no-coverage':
                    $this->arguments['noCoverage'] = true;

                    break;

                case '--no-logging':
                    $this->arguments['noLogging'] = true;

                    break;

                case '--no-interaction':
                    $this->arguments['noInteraction'] = true;

                    break;

                case '--globals-backup':
                    $this->arguments['backupGlobals'] = true;

                    break;

                case '--static-backup':
                    $this->arguments['backupStaticAttributes'] = true;

                    break;

                case 'v':
                case '--verbose':
                    $this->arguments['verbose'] = true;

                    break;

                case '--atleast-version':
                    if (version_compare(Version::id(), $option[1], '>=')) {
                        exit(TestRunner::SUCCESS_EXIT);
                    }

                    exit(TestRunner::FAILURE_EXIT);

                    break;

                case '--version':
                    $this->printVersionString();

                    exit(TestRunner::SUCCESS_EXIT);

                    break;

                case '--dont-report-useless-tests':
                    $this->arguments['reportUselessTests'] = false;

                    break;

                case '--strict-coverage':
                    $this->arguments['strictCoverage'] = true;

                    break;

                case '--disable-coverage-ignore':
                    $this->arguments['disableCodeCoverageIgnore'] = true;

                    break;

                case '--strict-global-state':
                    $this->arguments['beStrictAboutChangesToGlobalState'] = true;

                    break;

                case '--disallow-test-output':
                    $this->arguments['disallowTestOutput'] = true;

                    break;

                case '--disallow-resource-usage':
                    $this->arguments['beStrictAboutResourceUsageDuringSmallTests'] = true;

                    break;

                case '--default-time-limit':
                    $this->arguments['defaultTimeLimit'] = (int) $option[1];

                    break;

                case '--enforce-time-limit':
                    $this->arguments['enforceTimeLimit'] = true;

                    break;

                case '--disallow-todo-tests':
                    $this->arguments['disallowTodoAnnotatedTests'] = true;

                    break;

                case '--reverse-list':
                    $this->arguments['reverseList'] = true;

                    break;

                case '--check-version':
                    $this->handleVersionCheck();

                    break;

                case '--whitelist':
                    $this->arguments['whitelist'] = $option[1];

                    break;

                case '--random-order':
                    $this->handleOrderByOption('random');

                    break;

                case '--random-order-seed':
                    $this->arguments['randomOrderSeed'] = (int) $option[1];

                    break;

                case '--resolve-dependencies':
                    $this->handleOrderByOption('depends');

                    break;

                case '--ignore-dependencies':
                    $this->handleOrderByOption('no-depends');

                    break;

                case '--reverse-order':
                    $this->handleOrderByOption('reverse');

                    break;

                case '--dump-xdebug-filter':
                    $this->arguments['xdebugFilterFile'] = $option[1];

                    break;

                default:
                    $optionName = str_replace('--', '', $option[0]);

                    $handler = null;

                    if (isset($this->longOptions[$optionName])) {
                        $handler = $this->longOptions[$optionName];
                    } elseif (isset($this->longOptions[$optionName . '='])) {
                        $handler = $this->longOptions[$optionName . '='];
                    }

                    if (isset($handler) && is_callable([$this, $handler])) {
                        $this->{$handler}($option[1]);
                    }
            }
        }

        $this->handleCustomTestSuite();

        if (!isset($this->arguments['testSuffixes'])) {
            $this->arguments['testSuffixes'] = ['Test.php', '.phpt'];
        }

        if (isset($this->options[1][0]) &&
            substr($this->options[1][0], -5, 5) !== '.phpt' &&
            substr($this->options[1][0], -4, 4) !== '.php' &&
            substr($this->options[1][0], -1, 1) !== '/' &&
            !is_dir($this->options[1][0])) {
            $this->warnings[] = 'Invocation with class name is deprecated';
        }

        if (!isset($this->arguments['test'])) {
            if (isset($this->options[1][0])) {
                $this->arguments['test'] = $this->options[1][0];
            }

            if (isset($this->options[1][1])) {
                $testFile = realpath($this->options[1][1]);

                if ($testFile === false) {
                    $this->exitWithErrorMessage(
                        sprintf(
                            'Cannot open file "%s".',
                            $this->options[1][1]
                        )
                    );
                }
                $this->arguments['testFile'] = $testFile;
            } else {
                $this->arguments['testFile'] = '';
            }

            if (isset($this->arguments['test']) &&
                is_file($this->arguments['test']) &&
                strrpos($this->arguments['test'], '.') !== false &&
                substr($this->arguments['test'], -5, 5) !== '.phpt') {
                $this->arguments['testFile'] = realpath($this->arguments['test']);
                $this->arguments['test']     = substr($this->arguments['test'], 0, strrpos($this->arguments['test'], '.'));
            }

            if (isset($this->arguments['test']) &&
                is_string($this->arguments['test']) &&
                substr($this->arguments['test'], -5, 5) === '.phpt') {
                $suite = new TestSuite;
                $suite->addTestFile($this->arguments['test']);
                $this->arguments['test'] = $suite;
            }
        }

        if (isset($includePath)) {
            ini_set(
                'include_path',
                $includePath . PATH_SEPARATOR . ini_get('include_path')
            );
        }

        if ($this->arguments['loader'] !== null) {
            $this->arguments['loader'] = $this->handleLoader($this->arguments['loader']);
        }

        if (isset($this->arguments['configuration']) &&
            is_dir($this->arguments['configuration'])) {
            $configurationFile = $this->arguments['configuration'] . '/phpunit.xml';

            if (file_exists($configurationFile)) {
                $this->arguments['configuration'] = realpath(
                    $configurationFile
                );
            } elseif (file_exists($configurationFile . '.dist')) {
                $this->arguments['configuration'] = realpath(
                    $configurationFile . '.dist'
                );
            }
        } elseif (!isset($this->arguments['configuration']) &&
            $this->arguments['useDefaultConfiguration']) {
            if (file_exists('phpunit.xml')) {
                $this->arguments['configuration'] = realpath('phpunit.xml');
            } elseif (file_exists('phpunit.xml.dist')) {
                $this->arguments['configuration'] = realpath(
                    'phpunit.xml.dist'
                );
            }
        }

        if (isset($this->arguments['configuration'])) {
            try {
                $configuration = Configuration::getInstance(
                    $this->arguments['configuration']
                );
            } catch (Throwable $t) {
                print $t->getMessage() . PHP_EOL;

                exit(TestRunner::FAILURE_EXIT);
            }

            $phpunitConfiguration = $configuration->getPHPUnitConfiguration();

            $configuration->handlePHPConfiguration();

            /*
             * Issue #1216
             */
            if (isset($this->arguments['bootstrap'])) {
                $this->handleBootstrap($this->arguments['bootstrap']);
            } elseif (isset($phpunitConfiguration['bootstrap'])) {
                $this->handleBootstrap($phpunitConfiguration['bootstrap']);
            }

            /*
             * Issue #657
             */
            if (isset($phpunitConfiguration['stderr']) && !isset($this->arguments['stderr'])) {
                $this->arguments['stderr'] = $phpunitConfiguration['stderr'];
            }

            if (isset($phpunitConfiguration['extensionsDirectory']) && !isset($this->arguments['noExtensions']) && extension_loaded('phar')) {
                $this->handleExtensions($phpunitConfiguration['extensionsDirectory']);
            }

            if (isset($phpunitConfiguration['columns']) && !isset($this->arguments['columns'])) {
                $this->arguments['columns'] = $phpunitConfiguration['columns'];
            }

            if (!isset($this->arguments['printer']) && isset($phpunitConfiguration['printerClass'])) {
                $file = $phpunitConfiguration['printerFile'] ?? '';

                $this->arguments['printer'] = $this->handlePrinter(
                    $phpunitConfiguration['printerClass'],
                    $file
                );
            }

            if (isset($phpunitConfiguration['testSuiteLoaderClass'])) {
                $file = $phpunitConfiguration['testSuiteLoaderFile'] ?? '';

                $this->arguments['loader'] = $this->handleLoader(
                    $phpunitConfiguration['testSuiteLoaderClass'],
                    $file
                );
            }

            if (!isset($this->arguments['testsuite']) && isset($phpunitConfiguration['defaultTestSuite'])) {
                $this->arguments['testsuite'] = $phpunitConfiguration['defaultTestSuite'];
            }

            if (!isset($this->arguments['test'])) {
                $testSuite = $configuration->getTestSuiteConfiguration($this->arguments['testsuite'] ?? '');

                if ($testSuite !== null) {
                    $this->arguments['test'] = $testSuite;
                }
            }
        } elseif (isset($this->arguments['bootstrap'])) {
            $this->handleBootstrap($this->arguments['bootstrap']);
        }

        if (isset($this->arguments['printer']) &&
            is_string($this->arguments['printer'])) {
            $this->arguments['printer'] = $this->handlePrinter($this->arguments['printer']);
        }

        if (!isset($this->arguments['test'])) {
            $this->showHelp();

            exit(TestRunner::EXCEPTION_EXIT);
        }
    }

    /**
     * Handles the loading of the PHPUnit\Runner\TestSuiteLoader implementation.
     */
    protected function handleLoader(string $loaderClass, string $loaderFile = ''): ?TestSuiteLoader
    {
        if (!class_exists($loaderClass, false)) {
            if ($loaderFile == '') {
                $loaderFile = Filesystem::classNameToFilename(
                    $loaderClass
                );
            }

            $loaderFile = stream_resolve_include_path($loaderFile);

            if ($loaderFile) {
                require $loaderFile;
            }
        }

        if (class_exists($loaderClass, false)) {
            try {
                $class = new ReflectionClass($loaderClass);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if ($class->implementsInterface(TestSuiteLoader::class) && $class->isInstantiable()) {
                $object = $class->newInstance();

                assert($object instanceof TestSuiteLoader);

                return $object;
            }
        }

        if ($loaderClass == StandardTestSuiteLoader::class) {
            return null;
        }

        $this->exitWithErrorMessage(
            sprintf(
                'Could not use "%s" as loader.',
                $loaderClass
            )
        );

        return null;
    }

    /**
     * Handles the loading of the PHPUnit\Util\Printer implementation.
     *
     * @return null|Printer|string
     */
    protected function handlePrinter(string $printerClass, string $printerFile = '')
    {
        if (!class_exists($printerClass, false)) {
            if ($printerFile == '') {
                $printerFile = Filesystem::classNameToFilename(
                    $printerClass
                );
            }

            $printerFile = stream_resolve_include_path($printerFile);

            if ($printerFile) {
                require $printerFile;
            }
        }

        if (!class_exists($printerClass)) {
            $this->exitWithErrorMessage(
                sprintf(
                    'Could not use "%s" as printer: class does not exist',
                    $printerClass
                )
            );
        }

        try {
            $class = new ReflectionClass($printerClass);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
            // @codeCoverageIgnoreEnd
        }

        if (!$class->implementsInterface(TestListener::class)) {
            $this->exitWithErrorMessage(
                sprintf(
                    'Could not use "%s" as printer: class does not implement %s',
                    $printerClass,
                    TestListener::class
                )
            );
        }

        if (!$class->isSubclassOf(Printer::class)) {
            $this->exitWithErrorMessage(
                sprintf(
                    'Could not use "%s" as printer: class does not extend %s',
                    $printerClass,
                    Printer::class
                )
            );
        }

        if (!$class->isInstantiable()) {
            $this->exitWithErrorMessage(
                sprintf(
                    'Could not use "%s" as printer: class cannot be instantiated',
                    $printerClass
                )
            );
        }

        if ($class->isSubclassOf(ResultPrinter::class)) {
            return $printerClass;
        }

        $outputStream = isset($this->arguments['stderr']) ? 'php://stderr' : null;

        return $class->newInstance($outputStream);
    }

    /**
     * Loads a bootstrap file.
     */
    protected function handleBootstrap(string $filename): void
    {
        try {
            FileLoader::checkAndLoad($filename);
        } catch (Exception $e) {
            $this->exitWithErrorMessage($e->getMessage());
        }
    }

    protected function handleVersionCheck(): void
    {
        $this->printVersionString();

        $latestVersion = file_get_contents('https://phar.phpunit.de/latest-version-of/phpunit');
        $isOutdated    = version_compare($latestVersion, Version::id(), '>');

        if ($isOutdated) {
            printf(
                'You are not using the latest version of PHPUnit.' . PHP_EOL .
                'The latest version is PHPUnit %s.' . PHP_EOL,
                $latestVersion
            );
        } else {
            print 'You are using the latest version of PHPUnit.' . PHP_EOL;
        }

        exit(TestRunner::SUCCESS_EXIT);
    }

    /**
     * Show the help message.
     */
    protected function showHelp(): void
    {
        $this->printVersionString();
        (new Help)->writeToConsole();
    }

    /**
     * Custom callback for test suite discovery.
     */
    protected function handleCustomTestSuite(): void
    {
    }

    private function printVersionString(): void
    {
        if ($this->versionStringPrinted) {
            return;
        }

        print Version::getVersionString() . PHP_EOL . PHP_EOL;

        $this->versionStringPrinted = true;
    }

    private function exitWithErrorMessage(string $message): void
    {
        $this->printVersionString();

        print $message . PHP_EOL;

        exit(TestRunner::FAILURE_EXIT);
    }

    private function handleExtensions(string $directory): void
    {
        foreach ((new FileIteratorFacade)->getFilesAsArray($directory, '.phar') as $file) {
            if (!file_exists('phar://' . $file . '/manifest.xml')) {
                $this->arguments['notLoadedExtensions'][] = $file . ' is not an extension for PHPUnit';

                continue;
            }

            try {
                $applicationName = new ApplicationName('phpunit/phpunit');
                $version         = new PharIoVersion(Version::series());
                $manifest        = ManifestLoader::fromFile('phar://' . $file . '/manifest.xml');

                if (!$manifest->isExtensionFor($applicationName)) {
                    $this->arguments['notLoadedExtensions'][] = $file . ' is not an extension for PHPUnit';

                    continue;
                }

                if (!$manifest->isExtensionFor($applicationName, $version)) {
                    $this->arguments['notLoadedExtensions'][] = $file . ' is not compatible with this version of PHPUnit';

                    continue;
                }
            } catch (ManifestException $e) {
                $this->arguments['notLoadedExtensions'][] = $file . ': ' . $e->getMessage();

                continue;
            }

            require $file;

            $this->arguments['loadedExtensions'][] = $manifest->getName()->asString() . ' ' . $manifest->getVersion()->getVersionString();
        }
    }

    private function handleListGroups(TestSuite $suite, bool $exit): int
    {
        $this->printVersionString();

        $this->warnAboutConflictingOptions(
            'listGroups',
            [
                'filter',
                'groups',
                'excludeGroups',
                'testsuite',
            ]
        );

        print 'Available test group(s):' . PHP_EOL;

        $groups = $suite->getGroups();
        sort($groups);

        foreach ($groups as $group) {
            printf(
                ' - %s' . PHP_EOL,
                $group
            );
        }

        if ($exit) {
            exit(TestRunner::SUCCESS_EXIT);
        }

        return TestRunner::SUCCESS_EXIT;
    }

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    private function handleListSuites(bool $exit): int
    {
        $this->printVersionString();

        $this->warnAboutConflictingOptions(
            'listSuites',
            [
                'filter',
                'groups',
                'excludeGroups',
                'testsuite',
            ]
        );

        print 'Available test suite(s):' . PHP_EOL;

        $configuration = Configuration::getInstance(
            $this->arguments['configuration']
        );

        foreach ($configuration->getTestSuiteNames() as $suiteName) {
            printf(
                ' - %s' . PHP_EOL,
                $suiteName
            );
        }

        if ($exit) {
            exit(TestRunner::SUCCESS_EXIT);
        }

        return TestRunner::SUCCESS_EXIT;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function handleListTests(TestSuite $suite, bool $exit): int
    {
        $this->printVersionString();

        $this->warnAboutConflictingOptions(
            'listTests',
            [
                'filter',
                'groups',
                'excludeGroups',
            ]
        );

        $renderer = new TextTestListRenderer;

        print $renderer->render($suite);

        if ($exit) {
            exit(TestRunner::SUCCESS_EXIT);
        }

        return TestRunner::SUCCESS_EXIT;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function handleListTestsXml(TestSuite $suite, string $target, bool $exit): int
    {
        $this->printVersionString();

        $this->warnAboutConflictingOptions(
            'listTestsXml',
            [
                'filter',
                'groups',
                'excludeGroups',
            ]
        );

        $renderer = new XmlTestListRenderer;

        file_put_contents($target, $renderer->render($suite));

        printf(
            'Wrote list of tests that would have been run to %s' . PHP_EOL,
            $target
        );

        if ($exit) {
            exit(TestRunner::SUCCESS_EXIT);
        }

        return TestRunner::SUCCESS_EXIT;
    }

    private function handleOrderByOption(string $value): void
    {
        foreach (explode(',', $value) as $order) {
            switch ($order) {
                case 'default':
                    $this->arguments['executionOrder']        = TestSuiteSorter::ORDER_DEFAULT;
                    $this->arguments['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFAULT;
                    $this->arguments['resolveDependencies']   = true;

                    break;

                case 'defects':
                    $this->arguments['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFECTS_FIRST;

                    break;

                case 'depends':
                    $this->arguments['resolveDependencies'] = true;

                    break;

                case 'duration':
                    $this->arguments['executionOrder'] = TestSuiteSorter::ORDER_DURATION;

                    break;

                case 'no-depends':
                    $this->arguments['resolveDependencies'] = false;

                    break;

                case 'random':
                    $this->arguments['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;

                    break;

                case 'reverse':
                    $this->arguments['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;

                    break;

                case 'size':
                    $this->arguments['executionOrder'] = TestSuiteSorter::ORDER_SIZE;

                    break;

                default:
                    $this->exitWithErrorMessage("unrecognized --order-by option: {$order}");
            }
        }
    }

    /**
     * @psalm-param "listGroups"|"listSuites"|"listTests"|"listTestsXml"|"filter"|"groups"|"excludeGroups"|"testsuite" $key
     * @psalm-param list<"listGroups"|"listSuites"|"listTests"|"listTestsXml"|"filter"|"groups"|"excludeGroups"|"testsuite"> $keys
     */
    private function warnAboutConflictingOptions(string $key, array $keys): void
    {
        $warningPrinted = false;

        foreach ($keys as $_key) {
            if (!empty($this->arguments[$_key])) {
                printf(
                    'The %s and %s options cannot be combined, %s is ignored' . PHP_EOL,
                    $this->mapKeyToOptionForWarning($_key),
                    $this->mapKeyToOptionForWarning($key),
                    $this->mapKeyToOptionForWarning($_key)
                );

                $warningPrinted = true;
            }
        }

        if ($warningPrinted) {
            print PHP_EOL;
        }
    }

    /**
     * @psalm-param "listGroups"|"listSuites"|"listTests"|"listTestsXml"|"filter"|"groups"|"excludeGroups"|"testsuite" $key
     */
    private function mapKeyToOptionForWarning(string $key): string
    {
        switch ($key) {
            case 'listGroups':
                return '--list-groups';

            case 'listSuites':
                return '--list-suites';

            case 'listTests':
                return '--list-tests';

            case 'listTestsXml':
                return '--list-tests-xml';

            case 'filter':
                return '--filter';

            case 'groups':
                return '--group';

            case 'excludeGroups':
                return '--exclude-group';

            case 'testsuite':
                return '--testsuite';
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\TextUI;

use RuntimeException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Exception extends RuntimeException implements \PHPUnit\Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function preg_match;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class RegularExpression
{
    /**
     * @return false|int
     */
    public static function safeMatch(string $pattern, string $subject)
    {
        return ErrorHandler::invokeIgnoringWarnings(
            static function () use ($pattern, $subject)
            {
                return preg_match($pattern, $subject);
            }
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Type
{
    public static function isType(string $type): bool
    {
        switch ($type) {
            case 'numeric':
            case 'integer':
            case 'int':
            case 'iterable':
            case 'float':
            case 'string':
            case 'boolean':
            case 'bool':
            case 'null':
            case 'array':
            case 'object':
            case 'resource':
            case 'scalar':
                return true;

            default:
                return false;
        }
    }

    public static function isCloneable(object $object): bool
    {
        try {
            $clone = clone $object;
        } catch (Throwable $t) {
            return false;
        }

        return $clone instanceof $object;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_SLASHES;
use const JSON_UNESCAPED_UNICODE;
use function count;
use function is_array;
use function is_object;
use function json_decode;
use function json_encode;
use function json_last_error;
use function ksort;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Json
{
    /**
     * Prettify json string.
     *
     * @throws \PHPUnit\Framework\Exception
     */
    public static function prettify(string $json): string
    {
        $decodedJson = json_decode($json, false);

        if (json_last_error()) {
            throw new Exception(
                'Cannot prettify invalid json'
            );
        }

        return json_encode($decodedJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }

    /**
     * To allow comparison of JSON strings, first process them into a consistent
     * format so that they can be compared as strings.
     *
     * @return array ($error, $canonicalized_json)  The $error parameter is used
     *               to indicate an error decoding the json. This is used to avoid ambiguity
     *               with JSON strings consisting entirely of 'null' or 'false'.
     */
    public static function canonicalize(string $json): array
    {
        $decodedJson = json_decode($json);

        if (json_last_error()) {
            return [true, null];
        }

        self::recursiveSort($decodedJson);

        $reencodedJson = json_encode($decodedJson);

        return [false, $reencodedJson];
    }

    /**
     * JSON object keys are unordered while PHP array keys are ordered.
     *
     * Sort all array keys to ensure both the expected and actual values have
     * their keys in the same order.
     */
    private static function recursiveSort(&$json): void
    {
        if (!is_array($json)) {
            // If the object is not empty, change it to an associative array
            // so we can sort the keys (and we will still re-encode it
            // correctly, since PHP encodes associative arrays as JSON objects.)
            // But EMPTY objects MUST remain empty objects. (Otherwise we will
            // re-encode it as a JSON array rather than a JSON object.)
            // See #2919.
            if (is_object($json) && count((array) $json) > 0) {
                $json = (array) $json;
            } else {
                return;
            }
        }

        ksort($json);

        foreach ($json as $key => &$value) {
            self::recursiveSort($value);
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use function array_diff;
use function array_keys;
use function fopen;
use function get_defined_vars;
use function sprintf;
use function stream_resolve_include_path;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class FileLoader
{
    /**
     * Checks if a PHP sourcecode file is readable. The sourcecode file is loaded through the load() method.
     *
     * As a fallback, PHP looks in the directory of the file executing the stream_resolve_include_path function.
     * We do not want to load the Test.php file here, so skip it if it found that.
     * PHP prioritizes the include_path setting, so if the current directory is in there, it will first look in the
     * current working directory.
     *
     * @throws Exception
     */
    public static function checkAndLoad(string $filename): string
    {
        $includePathFilename = stream_resolve_include_path($filename);

        if (!$includePathFilename) {
            throw new Exception(
                sprintf('Cannot open file "%s".' . "\n", $filename)
            );
        }

        $localFile = __DIR__ . DIRECTORY_SEPARATOR . $filename;

        if ($includePathFilename === $localFile || !self::isReadable($includePathFilename)) {
            throw new Exception(
                sprintf('Cannot open file "%s".' . "\n", $filename)
            );
        }

        self::load($includePathFilename);

        return $includePathFilename;
    }

    /**
     * Loads a PHP sourcefile.
     */
    public static function load(string $filename): void
    {
        $oldVariableNames = array_keys(get_defined_vars());

        include_once $filename;

        $newVariables = get_defined_vars();

        foreach (array_diff(array_keys($newVariables), $oldVariableNames) as $variableName) {
            if ($variableName !== 'oldVariableNames') {
                $GLOBALS[$variableName] = $newVariables[$variableName];
            }
        }
    }

    /**
     * @see https://github.com/sebastianbergmann/phpunit/pull/2751
     */
    private static function isReadable(string $filename): bool
    {
        return @fopen($filename, 'r') !== false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use function is_dir;
use function mkdir;
use function str_replace;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Filesystem
{
    /**
     * Maps class names to source file names:
     *   - PEAR CS:   Foo_Bar_Baz -> Foo/Bar/Baz.php
     *   - Namespace: Foo\Bar\Baz -> Foo/Bar/Baz.php.
     */
    public static function classNameToFilename(string $className): string
    {
        return str_replace(
            ['_', '\\'],
            DIRECTORY_SEPARATOR,
            $className
        ) . '.php';
    }

    public static function createDirectory(string $directory): bool
    {
        return !(!is_dir($directory) && !@mkdir($directory, 0777, true) && !is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function str_replace;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ConfigurationGenerator
{
    /**
     * @var string
     */
    private const TEMPLATE = <<<'EOT'
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/{phpunit_version}/phpunit.xsd"
         bootstrap="{bootstrap_script}"
         cacheResultFile="{cache_directory}/test-results"
         executionOrder="depends,defects"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         convertDeprecationsToExceptions="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory>{tests_directory}</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">{src_directory}</directory>
        </whitelist>
    </filter>
</phpunit>

EOT;

    public function generateDefaultConfiguration(string $phpunitVersion, string $bootstrapScript, string $testsDirectory, string $srcDirectory, string $cacheDirectory): string
    {
        return str_replace(
            [
                '{phpunit_version}',
                '{bootstrap_script}',
                '{tests_directory}',
                '{src_directory}',
                '{cache_directory}',
            ],
            [
                $phpunitVersion,
                $bootstrapScript,
                $testsDirectory,
                $srcDirectory,
                $cacheDirectory,
            ],
            self::TEMPLATE
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use function class_exists;
use function defined;
use function dirname;
use function strpos;
use function sys_get_temp_dir;
use Composer\Autoload\ClassLoader;
use DeepCopy\DeepCopy;
use Doctrine\Instantiator\Instantiator;
use PharIo\Manifest\Manifest;
use PharIo\Version\Version as PharIoVersion;
use PHP_Token;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Project;
use phpDocumentor\Reflection\Type;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophet;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeUnitReverseLookup\Wizard;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Diff\Diff;
use SebastianBergmann\Environment\Runtime;
use SebastianBergmann\Exporter\Exporter;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
use SebastianBergmann\GlobalState\Snapshot;
use SebastianBergmann\Invoker\Invoker;
use SebastianBergmann\ObjectEnumerator\Enumerator;
use SebastianBergmann\RecursionContext\Context;
use SebastianBergmann\ResourceOperations\ResourceOperations;
use SebastianBergmann\Timer\Timer;
use SebastianBergmann\Type\TypeName;
use SebastianBergmann\Version;
use Text_Template;
use TheSeer\Tokenizer\Tokenizer;
use Webmozart\Assert\Assert;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Blacklist
{
    /**
     * @var array<string,int>
     */
    public static $blacklistedClassNames = [
        // composer
        ClassLoader::class        => 1,

        // doctrine/instantiator
        Instantiator::class       => 1,

        // myclabs/deepcopy
        DeepCopy::class           => 1,

        // phar-io/manifest
        Manifest::class           => 1,

        // phar-io/version
        PharIoVersion::class      => 1,

        // phpdocumentor/reflection-common
        Project::class            => 1,

        // phpdocumentor/reflection-docblock
        DocBlock::class           => 1,

        // phpdocumentor/type-resolver
        Type::class               => 1,

        // phpspec/prophecy
        Prophet::class            => 1,

        // phpunit/phpunit
        TestCase::class           => 2,

        // phpunit/php-code-coverage
        CodeCoverage::class       => 1,

        // phpunit/php-file-iterator
        FileIteratorFacade::class => 1,

        // phpunit/php-invoker
        Invoker::class            => 1,

        // phpunit/php-text-template
        Text_Template::class      => 1,

        // phpunit/php-timer
        Timer::class              => 1,

        // phpunit/php-token-stream
        PHP_Token::class          => 1,

        // sebastian/code-unit-reverse-lookup
        Wizard::class             => 1,

        // sebastian/comparator
        Comparator::class         => 1,

        // sebastian/diff
        Diff::class               => 1,

        // sebastian/environment
        Runtime::class            => 1,

        // sebastian/exporter
        Exporter::class           => 1,

        // sebastian/global-state
        Snapshot::class           => 1,

        // sebastian/object-enumerator
        Enumerator::class         => 1,

        // sebastian/recursion-context
        Context::class            => 1,

        // sebastian/resource-operations
        ResourceOperations::class => 1,

        // sebastian/type
        TypeName::class           => 1,

        // sebastian/version
        Version::class            => 1,

        // theseer/tokenizer
        Tokenizer::class          => 1,

        // webmozart/assert
        Assert::class             => 1,
    ];

    /**
     * @var string[]
     */
    private static $directories;

    /**
     * @throws Exception
     *
     * @return string[]
     */
    public function getBlacklistedDirectories(): array
    {
        $this->initialize();

        return self::$directories;
    }

    /**
     * @throws Exception
     */
    public function isBlacklisted(string $file): bool
    {
        if (defined('PHPUNIT_TESTSUITE')) {
            return false;
        }

        $this->initialize();

        foreach (self::$directories as $directory) {
            if (strpos($file, $directory) === 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * @throws Exception
     */
    private function initialize(): void
    {
        if (self::$directories === null) {
            self::$directories = [];

            foreach (self::$blacklistedClassNames as $className => $parent) {
                if (!class_exists($className)) {
                    continue;
                }

                try {
                    $directory = (new ReflectionClass($className))->getFileName();
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                for ($i = 0; $i < $parent; $i++) {
                    $directory = dirname($directory);
                }

                self::$directories[] = $directory;
            }

            // Hide process isolation workaround on Windows.
            if (DIRECTORY_SEPARATOR === '\\') {
                // tempnam() prefix is limited to first 3 chars.
                // @see https://php.net/manual/en/function.tempnam.php
                self::$directories[] = sys_get_temp_dir() . '\\PHP';
            }
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function array_map;
use function array_merge;
use function array_shift;
use function array_slice;
use function count;
use function current;
use function explode;
use function key;
use function next;
use function preg_replace;
use function reset;
use function sort;
use function strlen;
use function strpos;
use function strstr;
use function substr;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Getopt
{
    /**
     * @throws Exception
     */
    public static function parse(array $args, string $short_options, array $long_options = null): array
    {
        if (empty($args)) {
            return [[], []];
        }

        $opts     = [];
        $non_opts = [];

        if ($long_options) {
            sort($long_options);
        }

        if (isset($args[0][0]) && $args[0][0] !== '-') {
            array_shift($args);
        }

        reset($args);

        $args = array_map('trim', $args);

        /* @noinspection ComparisonOperandsOrderInspection */
        while (false !== $arg = current($args)) {
            $i = key($args);
            next($args);

            if ($arg === '') {
                continue;
            }

            if ($arg === '--') {
                $non_opts = array_merge($non_opts, array_slice($args, $i + 1));

                break;
            }

            if ($arg[0] !== '-' || (strlen($arg) > 1 && $arg[1] === '-' && !$long_options)) {
                $non_opts[] = $args[$i];

                continue;
            }

            if (strlen($arg) > 1 && $arg[1] === '-') {
                self::parseLongOption(
                    substr($arg, 2),
                    $long_options,
                    $opts,
                    $args
                );
            } else {
                self::parseShortOption(
                    substr($arg, 1),
                    $short_options,
                    $opts,
                    $args
                );
            }
        }

        return [$opts, $non_opts];
    }

    /**
     * @throws Exception
     */
    private static function parseShortOption(string $arg, string $short_options, array &$opts, array &$args): void
    {
        $argLen = strlen($arg);

        for ($i = 0; $i < $argLen; $i++) {
            $opt     = $arg[$i];
            $opt_arg = null;

            if ($arg[$i] === ':' || ($spec = strstr($short_options, $opt)) === false) {
                throw new Exception(
                    "unrecognized option -- {$opt}"
                );
            }

            if (strlen($spec) > 1 && $spec[1] === ':') {
                if ($i + 1 < $argLen) {
                    $opts[] = [$opt, substr($arg, $i + 1)];

                    break;
                }

                if (!(strlen($spec) > 2 && $spec[2] === ':')) {
                    /* @noinspection ComparisonOperandsOrderInspection */
                    if (false === $opt_arg = current($args)) {
                        throw new Exception(
                            "option requires an argument -- {$opt}"
                        );
                    }

                    next($args);
                }
            }

            $opts[] = [$opt, $opt_arg];
        }
    }

    /**
     * @throws Exception
     */
    private static function parseLongOption(string $arg, array $long_options, array &$opts, array &$args): void
    {
        $count   = count($long_options);
        $list    = explode('=', $arg);
        $opt     = $list[0];
        $opt_arg = null;

        if (count($list) > 1) {
            $opt_arg = $list[1];
        }

        $opt_len = strlen($opt);

        foreach ($long_options as $i => $long_opt) {
            $opt_start = substr($long_opt, 0, $opt_len);

            if ($opt_start !== $opt) {
                continue;
            }

            $opt_rest = substr($long_opt, $opt_len);

            if ($opt_rest !== '' && $i + 1 < $count && $opt[0] !== '=' && strpos($long_options[$i + 1], $opt) === 0) {
                throw new Exception(
                    "option --{$opt} is ambiguous"
                );
            }

            if (substr($long_opt, -1) === '=') {
                /* @noinspection StrlenInEmptyStringCheckContextInspection */
                if (substr($long_opt, -2) !== '==' && !strlen((string) $opt_arg)) {
                    /* @noinspection ComparisonOperandsOrderInspection */
                    if (false === $opt_arg = current($args)) {
                        throw new Exception(
                            "option --{$opt} requires an argument"
                        );
                    }

                    next($args);
                }
            } elseif ($opt_arg) {
                throw new Exception(
                    "option --{$opt} doesn't allow an argument"
                );
            }

            $full_option = '--' . preg_replace('/={1,2}$/', '', $long_opt);
            $opts[]      = [$full_option, $opt_arg];

            return;
        }

        throw new Exception("unrecognized option --{$opt}");
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionMethod;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Reflection
{
    /**
     * @psalm-return list<ReflectionMethod>
     */
    public function publicMethodsInTestClass(ReflectionClass $class): array
    {
        return $this->filterMethods($class, ReflectionMethod::IS_PUBLIC);
    }

    /**
     * @psalm-return list<ReflectionMethod>
     */
    public function methodsInTestClass(ReflectionClass $class): array
    {
        return $this->filterMethods($class, null);
    }

    /**
     * @psalm-return list<ReflectionMethod>
     */
    private function filterMethods(ReflectionClass $class, ?int $filter): array
    {
        $methods = [];

        // PHP <7.2.18 and <7.3.5 throw error when null is passed
        // to ReflectionClass::getMethods() when strict_types is enabled.
        $classMethods = $filter === null ? $class->getMethods() : $class->getMethods($filter);

        foreach ($classMethods as $method) {
            if ($method->getDeclaringClass()->getName() === TestCase::class) {
                continue;
            }

            if ($method->getDeclaringClass()->getName() === Assert::class) {
                continue;
            }

            $methods[] = $method;
        }

        return $methods;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const ENT_QUOTES;
use function assert;
use function chdir;
use function class_exists;
use function dirname;
use function error_reporting;
use function file_get_contents;
use function getcwd;
use function gettype;
use function htmlspecialchars;
use function is_string;
use function libxml_get_errors;
use function libxml_use_internal_errors;
use function mb_convert_encoding;
use function ord;
use function preg_replace;
use function settype;
use function sprintf;
use function strlen;
use DOMCharacterData;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMText;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Xml
{
    public static function import(DOMElement $element): DOMElement
    {
        return (new DOMDocument)->importNode($element, true);
    }

    /**
     * Load an $actual document into a DOMDocument.  This is called
     * from the selector assertions.
     *
     * If $actual is already a DOMDocument, it is returned with
     * no changes.  Otherwise, $actual is loaded into a new DOMDocument
     * as either HTML or XML, depending on the value of $isHtml. If $isHtml is
     * false and $xinclude is true, xinclude is performed on the loaded
     * DOMDocument.
     *
     * Note: prior to PHPUnit 3.3.0, this method loaded a file and
     * not a string as it currently does.  To load a file into a
     * DOMDocument, use loadFile() instead.
     *
     * @param DOMDocument|string $actual
     *
     * @throws Exception
     */
    public static function load($actual, bool $isHtml = false, string $filename = '', bool $xinclude = false, bool $strict = false): DOMDocument
    {
        if ($actual instanceof DOMDocument) {
            return $actual;
        }

        if (!is_string($actual)) {
            throw new Exception('Could not load XML from ' . gettype($actual));
        }

        if ($actual === '') {
            throw new Exception('Could not load XML from empty string');
        }

        // Required for XInclude on Windows.
        if ($xinclude) {
            $cwd = getcwd();
            @chdir(dirname($filename));
        }

        $document                     = new DOMDocument;
        $document->preserveWhiteSpace = false;

        $internal  = libxml_use_internal_errors(true);
        $message   = '';
        $reporting = error_reporting(0);

        if ($filename !== '') {
            // Required for XInclude
            $document->documentURI = $filename;
        }

        if ($isHtml) {
            $loaded = $document->loadHTML($actual);
        } else {
            $loaded = $document->loadXML($actual);
        }

        if (!$isHtml && $xinclude) {
            $document->xinclude();
        }

        foreach (libxml_get_errors() as $error) {
            $message .= "\n" . $error->message;
        }

        libxml_use_internal_errors($internal);
        error_reporting($reporting);

        if (isset($cwd)) {
            @chdir($cwd);
        }

        if ($loaded === false || ($strict && $message !== '')) {
            if ($filename !== '') {
                throw new Exception(
                    sprintf(
                        'Could not load "%s".%s',
                        $filename,
                        $message !== '' ? "\n" . $message : ''
                    )
                );
            }

            if ($message === '') {
                $message = 'Could not load XML for unknown reason';
            }

            throw new Exception($message);
        }

        return $document;
    }

    /**
     * Loads an XML (or HTML) file into a DOMDocument object.
     *
     * @throws Exception
     */
    public static function loadFile(string $filename, bool $isHtml = false, bool $xinclude = false, bool $strict = false): DOMDocument
    {
        $reporting = error_reporting(0);
        $contents  = file_get_contents($filename);

        error_reporting($reporting);

        if ($contents === false) {
            throw new Exception(
                sprintf(
                    'Could not read "%s".',
                    $filename
                )
            );
        }

        return self::load($contents, $isHtml, $filename, $xinclude, $strict);
    }

    public static function removeCharacterDataNodes(DOMNode $node): void
    {
        if ($node->hasChildNodes()) {
            for ($i = $node->childNodes->length - 1; $i >= 0; $i--) {
                if (($child = $node->childNodes->item($i)) instanceof DOMCharacterData) {
                    $node->removeChild($child);
                }
            }
        }
    }

    /**
     * Escapes a string for the use in XML documents.
     *
     * Any Unicode character is allowed, excluding the surrogate blocks, FFFE,
     * and FFFF (not even as character reference).
     *
     * @see https://www.w3.org/TR/xml/#charsets
     */
    public static function prepareString(string $string): string
    {
        return preg_replace(
            '/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/',
            '',
            htmlspecialchars(
                self::convertToUtf8($string),
                ENT_QUOTES
            )
        );
    }

    /**
     * "Convert" a DOMElement object into a PHP variable.
     */
    public static function xmlToVariable(DOMElement $element)
    {
        $variable = null;

        switch ($element->tagName) {
            case 'array':
                $variable = [];

                foreach ($element->childNodes as $entry) {
                    if (!$entry instanceof DOMElement || $entry->tagName !== 'element') {
                        continue;
                    }
                    $item = $entry->childNodes->item(0);

                    if ($item instanceof DOMText) {
                        $item = $entry->childNodes->item(1);
                    }

                    $value = self::xmlToVariable($item);

                    if ($entry->hasAttribute('key')) {
                        $variable[(string) $entry->getAttribute('key')] = $value;
                    } else {
                        $variable[] = $value;
                    }
                }

                break;

            case 'object':
                $className = $element->getAttribute('class');

                if ($element->hasChildNodes()) {
                    $arguments       = $element->childNodes->item(0)->childNodes;
                    $constructorArgs = [];

                    foreach ($arguments as $argument) {
                        if ($argument instanceof DOMElement) {
                            $constructorArgs[] = self::xmlToVariable($argument);
                        }
                    }

                    try {
                        assert(class_exists($className));

                        $variable = (new ReflectionClass($className))->newInstanceArgs($constructorArgs);
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new Exception(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd
                } else {
                    $variable = new $className;
                }

                break;

            case 'boolean':
                $variable = $element->textContent === 'true';

                break;

            case 'integer':
            case 'double':
            case 'string':
                $variable = $element->textContent;

                settype($variable, $element->tagName);

                break;
        }

        return $variable;
    }

    private static function convertToUtf8(string $string): string
    {
        if (!self::isUtf8($string)) {
            $string = mb_convert_encoding($string, 'UTF-8');
        }

        return $string;
    }

    private static function isUtf8(string $string): bool
    {
        $length = strlen($string);

        for ($i = 0; $i < $length; $i++) {
            if (ord($string[$i]) < 0x80) {
                $n = 0;
            } elseif ((ord($string[$i]) & 0xE0) === 0xC0) {
                $n = 1;
            } elseif ((ord($string[$i]) & 0xF0) === 0xE0) {
                $n = 2;
            } elseif ((ord($string[$i]) & 0xF0) === 0xF0) {
                $n = 3;
            } else {
                return false;
            }

            for ($j = 0; $j < $n; $j++) {
                if ((++$i === $length) || ((ord($string[$i]) & 0xC0) !== 0x80)) {
                    return false;
                }
            }
        }

        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Annotation;

use function array_key_exists;
use PHPUnit\Util\Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;

/**
 * Reflection information, and therefore DocBlock information, is static within
 * a single PHP process. It is therefore okay to use a Singleton registry here.
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Registry
{
    /** @var null|self */
    private static $instance;

    /** @var array<string, DocBlock> indexed by class name */
    private $classDocBlocks = [];

    /** @var array<string, array<string, DocBlock>> indexed by class name and method name */
    private $methodDocBlocks = [];

    public static function getInstance(): self
    {
        return self::$instance ?? self::$instance = new self;
    }

    private function __construct()
    {
    }

    /**
     * @throws Exception
     *
     * @psalm-param class-string $class
     */
    public function forClassName(string $class): DocBlock
    {
        if (array_key_exists($class, $this->classDocBlocks)) {
            return $this->classDocBlocks[$class];
        }

        try {
            $reflection = new ReflectionClass($class);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        return $this->classDocBlocks[$class] = DocBlock::ofClass($reflection);
    }

    /**
     * @throws Exception
     *
     * @psalm-param class-string $classInHierarchy
     */
    public function forMethod(string $classInHierarchy, string $method): DocBlock
    {
        if (isset($this->methodDocBlocks[$classInHierarchy][$method])) {
            return $this->methodDocBlocks[$classInHierarchy][$method];
        }

        try {
            $reflection = new ReflectionMethod($classInHierarchy, $method);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        return $this->methodDocBlocks[$classInHierarchy][$method] = DocBlock::ofMethod($reflection, $classInHierarchy);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Annotation;

use const JSON_ERROR_NONE;
use const PREG_OFFSET_CAPTURE;
use function array_filter;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_pop;
use function array_slice;
use function array_values;
use function constant;
use function count;
use function defined;
use function explode;
use function file;
use function implode;
use function is_array;
use function is_int;
use function is_numeric;
use function is_string;
use function json_decode;
use function json_last_error;
use function json_last_error_msg;
use function preg_match;
use function preg_match_all;
use function preg_replace;
use function preg_split;
use function realpath;
use function rtrim;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
use function substr_count;
use function trim;
use PharIo\Version\VersionConstraintParser;
use PHPUnit\Framework\InvalidDataProviderException;
use PHPUnit\Framework\SkippedTestError;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Exception;
use PHPUnit\Util\InvalidDataSetException;
use ReflectionClass;
use ReflectionException;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use Reflector;
use Traversable;

/**
 * This is an abstraction around a PHPUnit-specific docBlock,
 * allowing us to ask meaningful questions about a specific
 * reflection symbol.
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DocBlock
{
    /**
     * @todo This constant should be private (it's public because of TestTest::testGetProvidedDataRegEx)
     */
    public const REGEX_DATA_PROVIDER = '/@dataProvider\s+([a-zA-Z0-9._:-\\\\x7f-\xff]+)/';

    private const REGEX_REQUIRES_VERSION = '/@requires\s+(?P<name>PHP(?:Unit)?)\s+(?P<operator>[<>=!]{0,2})\s*(?P<version>[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?)[ \t]*\r?$/m';

    private const REGEX_REQUIRES_VERSION_CONSTRAINT = '/@requires\s+(?P<name>PHP(?:Unit)?)\s+(?P<constraint>[\d\t \-.|~^]+)[ \t]*\r?$/m';

    private const REGEX_REQUIRES_OS = '/@requires\s+(?P<name>OS(?:FAMILY)?)\s+(?P<value>.+?)[ \t]*\r?$/m';

    private const REGEX_REQUIRES_SETTING = '/@requires\s+(?P<name>setting)\s+(?P<setting>([^ ]+?))\s*(?P<value>[\w\.-]+[\w\.]?)?[ \t]*\r?$/m';

    private const REGEX_REQUIRES = '/@requires\s+(?P<name>function|extension)\s+(?P<value>([^\s<>=!]+))\s*(?P<operator>[<>=!]{0,2})\s*(?P<version>[\d\.-]+[\d\.]?)?[ \t]*\r?$/m';

    private const REGEX_TEST_WITH = '/@testWith\s+/';

    private const REGEX_EXPECTED_EXCEPTION = '(@expectedException\s+([:.\w\\\\x7f-\xff]+)(?:[\t ]+(\S*))?(?:[\t ]+(\S*))?\s*$)m';

    /** @var string */
    private $docComment;

    /** @var bool */
    private $isMethod;

    /** @var array<string, array<int, string>> pre-parsed annotations indexed by name and occurrence index */
    private $symbolAnnotations;

    /**
     * @var null|array<string, mixed>
     *
     * @psalm-var null|(array{
     *   __OFFSET: array<string, int>&array{__FILE: string},
     *   setting?: array<string, string>,
     *   extension_versions?: array<string, array{version: string, operator: string}>
     * }&array<
     *   string,
     *   string|array{version: string, operator: string}|array{constraint: string}|array<int|string, string>
     * >)
     */
    private $parsedRequirements;

    /** @var int */
    private $startLine;

    /** @var int */
    private $endLine;

    /** @var string */
    private $fileName;

    /** @var string */
    private $name;

    /**
     * @var string
     *
     * @psalm-var class-string
     */
    private $className;

    public static function ofClass(ReflectionClass $class): self
    {
        $className = $class->getName();

        return new self(
            (string) $class->getDocComment(),
            false,
            self::extractAnnotationsFromReflector($class),
            $class->getStartLine(),
            $class->getEndLine(),
            $class->getFileName(),
            $className,
            $className
        );
    }

    /**
     * @psalm-param class-string $classNameInHierarchy
     */
    public static function ofMethod(ReflectionMethod $method, string $classNameInHierarchy): self
    {
        return new self(
            (string) $method->getDocComment(),
            true,
            self::extractAnnotationsFromReflector($method),
            $method->getStartLine(),
            $method->getEndLine(),
            $method->getFileName(),
            $method->getName(),
            $classNameInHierarchy
        );
    }

    /**
     * Note: we do not preserve an instance of the reflection object, since it cannot be safely (de-)serialized.
     *
     * @param array<string, array<int, string>> $symbolAnnotations
     *
     * @psalm-param class-string $className
     */
    private function __construct(string $docComment, bool $isMethod, array $symbolAnnotations, int $startLine, int $endLine, string $fileName, string $name, string $className)
    {
        $this->docComment        = $docComment;
        $this->isMethod          = $isMethod;
        $this->symbolAnnotations = $symbolAnnotations;
        $this->startLine         = $startLine;
        $this->endLine           = $endLine;
        $this->fileName          = $fileName;
        $this->name              = $name;
        $this->className         = $className;
    }

    /**
     * @psalm-return array{
     *   __OFFSET: array<string, int>&array{__FILE: string},
     *   setting?: array<string, string>,
     *   extension_versions?: array<string, array{version: string, operator: string}>
     * }&array<
     *   string,
     *   string|array{version: string, operator: string}|array{constraint: string}|array<int|string, string>
     * >
     *
     * @throws Warning if the requirements version constraint is not well-formed
     */
    public function requirements(): array
    {
        if ($this->parsedRequirements !== null) {
            return $this->parsedRequirements;
        }

        $offset            = $this->startLine;
        $requires          = [];
        $recordedSettings  = [];
        $extensionVersions = [];
        $recordedOffsets   = [
            '__FILE' => realpath($this->fileName),
        ];

        // Trim docblock markers, split it into lines and rewind offset to start of docblock
        $lines = preg_replace(['#^/\*{2}#', '#\*/$#'], '', preg_split('/\r\n|\r|\n/', $this->docComment));
        $offset -= count($lines);

        foreach ($lines as $line) {
            if (preg_match(self::REGEX_REQUIRES_OS, $line, $matches)) {
                $requires[$matches['name']]        = $matches['value'];
                $recordedOffsets[$matches['name']] = $offset;
            }

            if (preg_match(self::REGEX_REQUIRES_VERSION, $line, $matches)) {
                $requires[$matches['name']] = [
                    'version'  => $matches['version'],
                    'operator' => $matches['operator'],
                ];
                $recordedOffsets[$matches['name']] = $offset;
            }

            if (preg_match(self::REGEX_REQUIRES_VERSION_CONSTRAINT, $line, $matches)) {
                if (!empty($requires[$matches['name']])) {
                    $offset++;

                    continue;
                }

                try {
                    $versionConstraintParser = new VersionConstraintParser;

                    $requires[$matches['name'] . '_constraint'] = [
                        'constraint' => $versionConstraintParser->parse(trim($matches['constraint'])),
                    ];
                    $recordedOffsets[$matches['name'] . '_constraint'] = $offset;
                } catch (\PharIo\Version\Exception $e) {
                    /* @TODO this catch is currently not valid, see https://github.com/phar-io/version/issues/16 */
                    throw new Warning($e->getMessage(), $e->getCode(), $e);
                }
            }

            if (preg_match(self::REGEX_REQUIRES_SETTING, $line, $matches)) {
                $recordedSettings[$matches['setting']]               = $matches['value'];
                $recordedOffsets['__SETTING_' . $matches['setting']] = $offset;
            }

            if (preg_match(self::REGEX_REQUIRES, $line, $matches)) {
                $name = $matches['name'] . 's';

                if (!isset($requires[$name])) {
                    $requires[$name] = [];
                }

                $requires[$name][]                                           = $matches['value'];
                $recordedOffsets[$matches['name'] . '_' . $matches['value']] = $offset;

                if ($name === 'extensions' && !empty($matches['version'])) {
                    $extensionVersions[$matches['value']] = [
                        'version'  => $matches['version'],
                        'operator' => $matches['operator'],
                    ];
                }
            }

            $offset++;
        }

        return $this->parsedRequirements = array_merge(
            $requires,
            ['__OFFSET' => $recordedOffsets],
            array_filter([
                'setting'            => $recordedSettings,
                'extension_versions' => $extensionVersions,
            ])
        );
    }

    /**
     * @return array|bool
     *
     * @psalm-return false|array{
     *   class: class-string,
     *   code: int|string|null,
     *   message: string,
     *   message_regex: string
     * }
     */
    public function expectedException()
    {
        $docComment = (string) substr($this->docComment, 3, -2);

        if (1 !== preg_match(self::REGEX_EXPECTED_EXCEPTION, $docComment, $matches)) {
            return false;
        }

        /** @psalm-var class-string $class */
        $class         = $matches[1];
        $annotations   = $this->symbolAnnotations();
        $code          = null;
        $message       = '';
        $messageRegExp = '';

        if (isset($matches[2])) {
            $message = trim($matches[2]);
        } elseif (isset($annotations['expectedExceptionMessage'])) {
            $message = $this->parseAnnotationContent($annotations['expectedExceptionMessage'][0]);
        }

        if (isset($annotations['expectedExceptionMessageRegExp'])) {
            $messageRegExp = $this->parseAnnotationContent($annotations['expectedExceptionMessageRegExp'][0]);
        }

        if (isset($matches[3])) {
            $code = $matches[3];
        } elseif (isset($annotations['expectedExceptionCode'])) {
            $code = $this->parseAnnotationContent($annotations['expectedExceptionCode'][0]);
        }

        if (is_numeric($code)) {
            $code = (int) $code;
        } elseif (is_string($code) && defined($code)) {
            $code = (int) constant($code);
        }

        return [
            'class'         => $class,
            'code'          => $code,
            'message'       => $message,
            'message_regex' => $messageRegExp,
        ];
    }

    /**
     * Returns the provided data for a method.
     *
     * @throws Exception
     */
    public function getProvidedData(): ?array
    {
        /** @noinspection SuspiciousBinaryOperationInspection */
        $data = $this->getDataFromDataProviderAnnotation($this->docComment) ?? $this->getDataFromTestWithAnnotation($this->docComment);

        if ($data === null) {
            return null;
        }

        if ($data === []) {
            throw new SkippedTestError;
        }

        foreach ($data as $key => $value) {
            if (!is_array($value)) {
                throw new InvalidDataSetException(
                    sprintf(
                        'Data set %s is invalid.',
                        is_int($key) ? '#' . $key : '"' . $key . '"'
                    )
                );
            }
        }

        return $data;
    }

    /**
     * @psalm-return array<string, array{line: int, value: string}>
     */
    public function getInlineAnnotations(): array
    {
        $code        = file($this->fileName);
        $lineNumber  = $this->startLine;
        $startLine   = $this->startLine - 1;
        $endLine     = $this->endLine - 1;
        $codeLines   = array_slice($code, $startLine, $endLine - $startLine + 1);
        $annotations = [];

        foreach ($codeLines as $line) {
            if (preg_match('#/\*\*?\s*@(?P<name>[A-Za-z_-]+)(?:[ \t]+(?P<value>.*?))?[ \t]*\r?\*/$#m', $line, $matches)) {
                $annotations[strtolower($matches['name'])] = [
                    'line'  => $lineNumber,
                    'value' => $matches['value'],
                ];
            }

            $lineNumber++;
        }

        return $annotations;
    }

    public function symbolAnnotations(): array
    {
        return $this->symbolAnnotations;
    }

    public function isHookToBeExecutedBeforeClass(): bool
    {
        return $this->isMethod &&
            false !== strpos($this->docComment, '@beforeClass');
    }

    public function isHookToBeExecutedAfterClass(): bool
    {
        return $this->isMethod &&
            false !== strpos($this->docComment, '@afterClass');
    }

    public function isToBeExecutedBeforeTest(): bool
    {
        return 1 === preg_match('/@before\b/', $this->docComment);
    }

    public function isToBeExecutedAfterTest(): bool
    {
        return 1 === preg_match('/@after\b/', $this->docComment);
    }

    /**
     * Parse annotation content to use constant/class constant values.
     *
     * Constants are specified using a starting '@'. For example: @ClassName::CONST_NAME
     *
     * If the constant is not found the string is used as is to ensure maximum BC.
     */
    private function parseAnnotationContent(string $message): string
    {
        if (defined($message) &&
            (strpos($message, '::') !== false && substr_count($message, '::') + 1 === 2)) {
            return constant($message);
        }

        return $message;
    }

    private function getDataFromDataProviderAnnotation(string $docComment): ?array
    {
        $methodName = null;
        $className  = $this->className;

        if ($this->isMethod) {
            $methodName = $this->name;
        }

        if (!preg_match_all(self::REGEX_DATA_PROVIDER, $docComment, $matches)) {
            return null;
        }

        $result = [];

        foreach ($matches[1] as $match) {
            $dataProviderMethodNameNamespace = explode('\\', $match);
            $leaf                            = explode('::', array_pop($dataProviderMethodNameNamespace));
            $dataProviderMethodName          = array_pop($leaf);

            if (empty($dataProviderMethodNameNamespace)) {
                $dataProviderMethodNameNamespace = '';
            } else {
                $dataProviderMethodNameNamespace = implode('\\', $dataProviderMethodNameNamespace) . '\\';
            }

            if (empty($leaf)) {
                $dataProviderClassName = $className;
            } else {
                /** @psalm-var class-string $dataProviderClassName */
                $dataProviderClassName = $dataProviderMethodNameNamespace . array_pop($leaf);
            }

            try {
                $dataProviderClass = new ReflectionClass($dataProviderClassName);

                $dataProviderMethod = $dataProviderClass->getMethod(
                    $dataProviderMethodName
                );
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
                // @codeCoverageIgnoreEnd
            }

            if ($dataProviderMethod->isStatic()) {
                $object = null;
            } else {
                $object = $dataProviderClass->newInstance();
            }

            if ($dataProviderMethod->getNumberOfParameters() === 0) {
                $data = $dataProviderMethod->invoke($object);
            } else {
                $data = $dataProviderMethod->invoke($object, $methodName);
            }

            if ($data instanceof Traversable) {
                $origData = $data;
                $data     = [];

                foreach ($origData as $key => $value) {
                    if (is_int($key)) {
                        $data[] = $value;
                    } elseif (array_key_exists($key, $data)) {
                        throw new InvalidDataProviderException(
                            sprintf(
                                'The key "%s" has already been defined in the data provider "%s".',
                                $key,
                                $match
                            )
                        );
                    } else {
                        $data[$key] = $value;
                    }
                }
            }

            if (is_array($data)) {
                $result = array_merge($result, $data);
            }
        }

        return $result;
    }

    /**
     * @throws Exception
     */
    private function getDataFromTestWithAnnotation(string $docComment): ?array
    {
        $docComment = $this->cleanUpMultiLineAnnotation($docComment);

        if (!preg_match(self::REGEX_TEST_WITH, $docComment, $matches, PREG_OFFSET_CAPTURE)) {
            return null;
        }

        $offset            = strlen($matches[0][0]) + $matches[0][1];
        $annotationContent = substr($docComment, $offset);
        $data              = [];

        foreach (explode("\n", $annotationContent) as $candidateRow) {
            $candidateRow = trim($candidateRow);

            if ($candidateRow[0] !== '[') {
                break;
            }

            $dataSet = json_decode($candidateRow, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception(
                    'The data set for the @testWith annotation cannot be parsed: ' . json_last_error_msg()
                );
            }

            $data[] = $dataSet;
        }

        if (!$data) {
            throw new Exception('The data set for the @testWith annotation cannot be parsed.');
        }

        return $data;
    }

    private function cleanUpMultiLineAnnotation(string $docComment): string
    {
        //removing initial '   * ' for docComment
        $docComment = str_replace("\r\n", "\n", $docComment);
        $docComment = preg_replace('/' . '\n' . '\s*' . '\*' . '\s?' . '/', "\n", $docComment);
        $docComment = (string) substr($docComment, 0, -1);

        return rtrim($docComment, "\n");
    }

    /** @return array<string, array<int, string>> */
    private static function parseDocBlock(string $docBlock): array
    {
        // Strip away the docblock header and footer to ease parsing of one line annotations
        $docBlock    = (string) substr($docBlock, 3, -2);
        $annotations = [];

        if (preg_match_all('/@(?P<name>[A-Za-z_-]+)(?:[ \t]+(?P<value>.*?))?[ \t]*\r?$/m', $docBlock, $matches)) {
            $numMatches = count($matches[0]);

            for ($i = 0; $i < $numMatches; $i++) {
                $annotations[$matches['name'][$i]][] = (string) $matches['value'][$i];
            }
        }

        return $annotations;
    }

    /** @param ReflectionClass|ReflectionFunctionAbstract $reflector */
    private static function extractAnnotationsFromReflector(Reflector $reflector): array
    {
        $annotations = [];

        if ($reflector instanceof ReflectionClass) {
            $annotations = array_merge(
                $annotations,
                ...array_map(
                    static function (ReflectionClass $trait): array
                    {
                        return self::parseDocBlock((string) $trait->getDocComment());
                    },
                    array_values($reflector->getTraits())
                )
            );
        }

        return array_merge(
            $annotations,
            self::parseDocBlock((string) $reflector->getDocComment())
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use const PATH_SEPARATOR;
use const PHP_VERSION;
use function assert;
use function constant;
use function count;
use function define;
use function defined;
use function dirname;
use function explode;
use function file_exists;
use function file_get_contents;
use function getenv;
use function implode;
use function in_array;
use function ini_get;
use function ini_set;
use function is_numeric;
use function libxml_clear_errors;
use function libxml_get_errors;
use function libxml_use_internal_errors;
use function preg_match;
use function putenv;
use function realpath;
use function sprintf;
use function stream_resolve_include_path;
use function strlen;
use function strpos;
use function strtolower;
use function strtoupper;
use function substr;
use function trim;
use function version_compare;
use DOMDocument;
use DOMElement;
use DOMNodeList;
use DOMXPath;
use LibXMLError;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\TestSuiteSorter;
use PHPUnit\TextUI\ResultPrinter;
use PHPUnit\Util\TestDox\CliTestDoxPrinter;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Configuration
{
    /**
     * @var self[]
     */
    private static $instances = [];

    /**
     * @var DOMDocument
     */
    private $document;

    /**
     * @var DOMXPath
     */
    private $xpath;

    /**
     * @var string
     */
    private $filename;

    /**
     * @var LibXMLError[]
     */
    private $errors = [];

    /**
     * Returns a PHPUnit configuration object.
     *
     * @throws Exception
     */
    public static function getInstance(string $filename): self
    {
        $realPath = realpath($filename);

        if ($realPath === false) {
            throw new Exception(
                sprintf(
                    'Could not read "%s".',
                    $filename
                )
            );
        }

        if (!isset(self::$instances[$realPath])) {
            self::$instances[$realPath] = new self($realPath);
        }

        return self::$instances[$realPath];
    }

    /**
     * Loads a PHPUnit configuration file.
     *
     * @throws Exception
     */
    private function __construct(string $filename)
    {
        $this->filename = $filename;
        $this->document = Xml::loadFile($filename, false, true, true);
        $this->xpath    = new DOMXPath($this->document);

        $this->validateConfigurationAgainstSchema();
    }

    /**
     * @codeCoverageIgnore
     */
    private function __clone()
    {
    }

    public function hasValidationErrors(): bool
    {
        return count($this->errors) > 0;
    }

    public function getValidationErrors(): array
    {
        $result = [];

        foreach ($this->errors as $error) {
            if (!isset($result[$error->line])) {
                $result[$error->line] = [];
            }
            $result[$error->line][] = trim($error->message);
        }

        return $result;
    }

    /**
     * Returns the real path to the configuration file.
     */
    public function getFilename(): string
    {
        return $this->filename;
    }

    public function getExtensionConfiguration(): array
    {
        $result = [];

        foreach ($this->xpath->query('extensions/extension') as $extension) {
            $result[] = $this->getElementConfigurationParameters($extension);
        }

        return $result;
    }

    /**
     * Returns the configuration for SUT filtering.
     */
    public function getFilterConfiguration(): array
    {
        $addUncoveredFilesFromWhitelist     = true;
        $processUncoveredFilesFromWhitelist = false;
        $includeDirectory                   = [];
        $includeFile                        = [];
        $excludeDirectory                   = [];
        $excludeFile                        = [];

        $tmp = $this->xpath->query('filter/whitelist');

        if ($tmp->length === 1) {
            if ($tmp->item(0)->hasAttribute('addUncoveredFilesFromWhitelist')) {
                $addUncoveredFilesFromWhitelist = $this->getBoolean(
                    (string) $tmp->item(0)->getAttribute(
                        'addUncoveredFilesFromWhitelist'
                    ),
                    true
                );
            }

            if ($tmp->item(0)->hasAttribute('processUncoveredFilesFromWhitelist')) {
                $processUncoveredFilesFromWhitelist = $this->getBoolean(
                    (string) $tmp->item(0)->getAttribute(
                        'processUncoveredFilesFromWhitelist'
                    ),
                    false
                );
            }

            $includeDirectory = $this->readFilterDirectories(
                'filter/whitelist/directory'
            );

            $includeFile = $this->readFilterFiles(
                'filter/whitelist/file'
            );

            $excludeDirectory = $this->readFilterDirectories(
                'filter/whitelist/exclude/directory'
            );

            $excludeFile = $this->readFilterFiles(
                'filter/whitelist/exclude/file'
            );
        }

        return [
            'whitelist' => [
                'addUncoveredFilesFromWhitelist'     => $addUncoveredFilesFromWhitelist,
                'processUncoveredFilesFromWhitelist' => $processUncoveredFilesFromWhitelist,
                'include'                            => [
                    'directory' => $includeDirectory,
                    'file'      => $includeFile,
                ],
                'exclude'                            => [
                    'directory' => $excludeDirectory,
                    'file'      => $excludeFile,
                ],
            ],
        ];
    }

    /**
     * Returns the configuration for groups.
     */
    public function getGroupConfiguration(): array
    {
        return $this->parseGroupConfiguration('groups');
    }

    /**
     * Returns the configuration for testdox groups.
     */
    public function getTestdoxGroupConfiguration(): array
    {
        return $this->parseGroupConfiguration('testdoxGroups');
    }

    /**
     * Returns the configuration for listeners.
     */
    public function getListenerConfiguration(): array
    {
        $result = [];

        foreach ($this->xpath->query('listeners/listener') as $listener) {
            $result[] = $this->getElementConfigurationParameters($listener);
        }

        return $result;
    }

    /**
     * Returns the logging configuration.
     */
    public function getLoggingConfiguration(): array
    {
        $result = [];

        foreach ($this->xpath->query('logging/log') as $log) {
            assert($log instanceof DOMElement);

            $type   = (string) $log->getAttribute('type');
            $target = (string) $log->getAttribute('target');

            if (!$target) {
                continue;
            }

            $target = $this->toAbsolutePath($target);

            if ($type === 'coverage-html') {
                if ($log->hasAttribute('lowUpperBound')) {
                    $result['lowUpperBound'] = $this->getInteger(
                        (string) $log->getAttribute('lowUpperBound'),
                        50
                    );
                }

                if ($log->hasAttribute('highLowerBound')) {
                    $result['highLowerBound'] = $this->getInteger(
                        (string) $log->getAttribute('highLowerBound'),
                        90
                    );
                }
            } elseif ($type === 'coverage-crap4j') {
                if ($log->hasAttribute('threshold')) {
                    $result['crap4jThreshold'] = $this->getInteger(
                        (string) $log->getAttribute('threshold'),
                        30
                    );
                }
            } elseif ($type === 'coverage-text') {
                if ($log->hasAttribute('showUncoveredFiles')) {
                    $result['coverageTextShowUncoveredFiles'] = $this->getBoolean(
                        (string) $log->getAttribute('showUncoveredFiles'),
                        false
                    );
                }

                if ($log->hasAttribute('showOnlySummary')) {
                    $result['coverageTextShowOnlySummary'] = $this->getBoolean(
                        (string) $log->getAttribute('showOnlySummary'),
                        false
                    );
                }
            }

            $result[$type] = $target;
        }

        return $result;
    }

    /**
     * Returns the PHP configuration.
     */
    public function getPHPConfiguration(): array
    {
        $result = [
            'include_path' => [],
            'ini'          => [],
            'const'        => [],
            'var'          => [],
            'env'          => [],
            'post'         => [],
            'get'          => [],
            'cookie'       => [],
            'server'       => [],
            'files'        => [],
            'request'      => [],
        ];

        foreach ($this->xpath->query('php/includePath') as $includePath) {
            $path = (string) $includePath->textContent;

            if ($path) {
                $result['include_path'][] = $this->toAbsolutePath($path);
            }
        }

        foreach ($this->xpath->query('php/ini') as $ini) {
            assert($ini instanceof DOMElement);

            $name  = (string) $ini->getAttribute('name');
            $value = (string) $ini->getAttribute('value');

            $result['ini'][$name]['value'] = $value;
        }

        foreach ($this->xpath->query('php/const') as $const) {
            assert($const instanceof DOMElement);

            $name  = (string) $const->getAttribute('name');
            $value = (string) $const->getAttribute('value');

            $result['const'][$name]['value'] = $this->getBoolean($value, $value);
        }

        foreach (['var', 'env', 'post', 'get', 'cookie', 'server', 'files', 'request'] as $array) {
            foreach ($this->xpath->query('php/' . $array) as $var) {
                assert($var instanceof DOMElement);

                $name     = (string) $var->getAttribute('name');
                $value    = (string) $var->getAttribute('value');
                $verbatim = false;

                if ($var->hasAttribute('verbatim')) {
                    $verbatim                          = $this->getBoolean($var->getAttribute('verbatim'), false);
                    $result[$array][$name]['verbatim'] = $verbatim;
                }

                if ($var->hasAttribute('force')) {
                    $force                          = $this->getBoolean($var->getAttribute('force'), false);
                    $result[$array][$name]['force'] = $force;
                }

                if (!$verbatim) {
                    $value = $this->getBoolean($value, $value);
                }

                $result[$array][$name]['value'] = $value;
            }
        }

        return $result;
    }

    /**
     * Handles the PHP configuration.
     */
    public function handlePHPConfiguration(): void
    {
        $configuration = $this->getPHPConfiguration();

        if (!empty($configuration['include_path'])) {
            ini_set(
                'include_path',
                implode(PATH_SEPARATOR, $configuration['include_path']) .
                PATH_SEPARATOR .
                ini_get('include_path')
            );
        }

        foreach ($configuration['ini'] as $name => $data) {
            $value = $data['value'];

            if (defined($value)) {
                $value = (string) constant($value);
            }

            ini_set($name, $value);
        }

        foreach ($configuration['const'] as $name => $data) {
            $value = $data['value'];

            if (!defined($name)) {
                define($name, $value);
            }
        }

        foreach ($configuration['var'] as $name => $data) {
            $GLOBALS[$name] = $data['value'];
        }

        foreach ($configuration['server'] as $name => $data) {
            $_SERVER[$name] = $data['value'];
        }

        foreach (['post', 'get', 'cookie', 'files', 'request'] as $array) {
            $target = &$GLOBALS['_' . strtoupper($array)];

            foreach ($configuration[$array] as $name => $data) {
                $target[$name] = $data['value'];
            }
        }

        foreach ($configuration['env'] as $name => $data) {
            $value = $data['value'];
            $force = $data['force'] ?? false;

            if ($force || getenv($name) === false) {
                putenv("{$name}={$value}");
            }

            $value = getenv($name);

            if (!isset($_ENV[$name])) {
                $_ENV[$name] = $value;
            }

            if ($force) {
                $_ENV[$name] = $value;
            }
        }
    }

    /**
     * Returns the PHPUnit configuration.
     */
    public function getPHPUnitConfiguration(): array
    {
        $result = [];
        $root   = $this->document->documentElement;

        if ($root->hasAttribute('cacheTokens')) {
            $result['cacheTokens'] = $this->getBoolean(
                (string) $root->getAttribute('cacheTokens'),
                false
            );
        }

        if ($root->hasAttribute('columns')) {
            $columns = (string) $root->getAttribute('columns');

            if ($columns === 'max') {
                $result['columns'] = 'max';
            } else {
                $result['columns'] = $this->getInteger($columns, 80);
            }
        }

        if ($root->hasAttribute('colors')) {
            /* only allow boolean for compatibility with previous versions
              'always' only allowed from command line */
            if ($this->getBoolean($root->getAttribute('colors'), false)) {
                $result['colors'] = ResultPrinter::COLOR_AUTO;
            } else {
                $result['colors'] = ResultPrinter::COLOR_NEVER;
            }
        }

        /*
         * @see https://github.com/sebastianbergmann/phpunit/issues/657
         */
        if ($root->hasAttribute('stderr')) {
            $result['stderr'] = $this->getBoolean(
                (string) $root->getAttribute('stderr'),
                false
            );
        }

        if ($root->hasAttribute('backupGlobals')) {
            $result['backupGlobals'] = $this->getBoolean(
                (string) $root->getAttribute('backupGlobals'),
                false
            );
        }

        if ($root->hasAttribute('backupStaticAttributes')) {
            $result['backupStaticAttributes'] = $this->getBoolean(
                (string) $root->getAttribute('backupStaticAttributes'),
                false
            );
        }

        if ($root->getAttribute('bootstrap')) {
            $result['bootstrap'] = $this->toAbsolutePath(
                (string) $root->getAttribute('bootstrap')
            );
        }

        if ($root->hasAttribute('convertDeprecationsToExceptions')) {
            $result['convertDeprecationsToExceptions'] = $this->getBoolean(
                (string) $root->getAttribute('convertDeprecationsToExceptions'),
                false
            );
        }

        if ($root->hasAttribute('convertErrorsToExceptions')) {
            $result['convertErrorsToExceptions'] = $this->getBoolean(
                (string) $root->getAttribute('convertErrorsToExceptions'),
                true
            );
        }

        if ($root->hasAttribute('convertNoticesToExceptions')) {
            $result['convertNoticesToExceptions'] = $this->getBoolean(
                (string) $root->getAttribute('convertNoticesToExceptions'),
                true
            );
        }

        if ($root->hasAttribute('convertWarningsToExceptions')) {
            $result['convertWarningsToExceptions'] = $this->getBoolean(
                (string) $root->getAttribute('convertWarningsToExceptions'),
                true
            );
        }

        if ($root->hasAttribute('forceCoversAnnotation')) {
            $result['forceCoversAnnotation'] = $this->getBoolean(
                (string) $root->getAttribute('forceCoversAnnotation'),
                false
            );
        }

        if ($root->hasAttribute('disableCodeCoverageIgnore')) {
            $result['disableCodeCoverageIgnore'] = $this->getBoolean(
                (string) $root->getAttribute('disableCodeCoverageIgnore'),
                false
            );
        }

        if ($root->hasAttribute('processIsolation')) {
            $result['processIsolation'] = $this->getBoolean(
                (string) $root->getAttribute('processIsolation'),
                false
            );
        }

        if ($root->hasAttribute('stopOnDefect')) {
            $result['stopOnDefect'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnDefect'),
                false
            );
        }

        if ($root->hasAttribute('stopOnError')) {
            $result['stopOnError'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnError'),
                false
            );
        }

        if ($root->hasAttribute('stopOnFailure')) {
            $result['stopOnFailure'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnFailure'),
                false
            );
        }

        if ($root->hasAttribute('stopOnWarning')) {
            $result['stopOnWarning'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnWarning'),
                false
            );
        }

        if ($root->hasAttribute('stopOnIncomplete')) {
            $result['stopOnIncomplete'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnIncomplete'),
                false
            );
        }

        if ($root->hasAttribute('stopOnRisky')) {
            $result['stopOnRisky'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnRisky'),
                false
            );
        }

        if ($root->hasAttribute('stopOnSkipped')) {
            $result['stopOnSkipped'] = $this->getBoolean(
                (string) $root->getAttribute('stopOnSkipped'),
                false
            );
        }

        if ($root->hasAttribute('failOnWarning')) {
            $result['failOnWarning'] = $this->getBoolean(
                (string) $root->getAttribute('failOnWarning'),
                false
            );
        }

        if ($root->hasAttribute('failOnRisky')) {
            $result['failOnRisky'] = $this->getBoolean(
                (string) $root->getAttribute('failOnRisky'),
                false
            );
        }

        if ($root->hasAttribute('testSuiteLoaderClass')) {
            $result['testSuiteLoaderClass'] = (string) $root->getAttribute(
                'testSuiteLoaderClass'
            );
        }

        if ($root->hasAttribute('defaultTestSuite')) {
            $result['defaultTestSuite'] = (string) $root->getAttribute(
                'defaultTestSuite'
            );
        }

        if ($root->getAttribute('testSuiteLoaderFile')) {
            $result['testSuiteLoaderFile'] = $this->toAbsolutePath(
                (string) $root->getAttribute('testSuiteLoaderFile')
            );
        }

        if ($root->hasAttribute('printerClass')) {
            $result['printerClass'] = (string) $root->getAttribute(
                'printerClass'
            );
        }

        if ($root->getAttribute('printerFile')) {
            $result['printerFile'] = $this->toAbsolutePath(
                (string) $root->getAttribute('printerFile')
            );
        }

        if ($root->hasAttribute('beStrictAboutChangesToGlobalState')) {
            $result['beStrictAboutChangesToGlobalState'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutChangesToGlobalState'),
                false
            );
        }

        if ($root->hasAttribute('beStrictAboutOutputDuringTests')) {
            $result['disallowTestOutput'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutOutputDuringTests'),
                false
            );
        }

        if ($root->hasAttribute('beStrictAboutResourceUsageDuringSmallTests')) {
            $result['beStrictAboutResourceUsageDuringSmallTests'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutResourceUsageDuringSmallTests'),
                false
            );
        }

        if ($root->hasAttribute('beStrictAboutTestsThatDoNotTestAnything')) {
            $result['reportUselessTests'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutTestsThatDoNotTestAnything'),
                true
            );
        }

        if ($root->hasAttribute('beStrictAboutTodoAnnotatedTests')) {
            $result['disallowTodoAnnotatedTests'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutTodoAnnotatedTests'),
                false
            );
        }

        if ($root->hasAttribute('beStrictAboutCoversAnnotation')) {
            $result['strictCoverage'] = $this->getBoolean(
                (string) $root->getAttribute('beStrictAboutCoversAnnotation'),
                false
            );
        }

        if ($root->hasAttribute('defaultTimeLimit')) {
            $result['defaultTimeLimit'] = $this->getInteger(
                (string) $root->getAttribute('defaultTimeLimit'),
                1
            );
        }

        if ($root->hasAttribute('enforceTimeLimit')) {
            $result['enforceTimeLimit'] = $this->getBoolean(
                (string) $root->getAttribute('enforceTimeLimit'),
                false
            );
        }

        if ($root->hasAttribute('ignoreDeprecatedCodeUnitsFromCodeCoverage')) {
            $result['ignoreDeprecatedCodeUnitsFromCodeCoverage'] = $this->getBoolean(
                (string) $root->getAttribute('ignoreDeprecatedCodeUnitsFromCodeCoverage'),
                false
            );
        }

        if ($root->hasAttribute('timeoutForSmallTests')) {
            $result['timeoutForSmallTests'] = $this->getInteger(
                (string) $root->getAttribute('timeoutForSmallTests'),
                1
            );
        }

        if ($root->hasAttribute('timeoutForMediumTests')) {
            $result['timeoutForMediumTests'] = $this->getInteger(
                (string) $root->getAttribute('timeoutForMediumTests'),
                10
            );
        }

        if ($root->hasAttribute('timeoutForLargeTests')) {
            $result['timeoutForLargeTests'] = $this->getInteger(
                (string) $root->getAttribute('timeoutForLargeTests'),
                60
            );
        }

        if ($root->hasAttribute('reverseDefectList')) {
            $result['reverseDefectList'] = $this->getBoolean(
                (string) $root->getAttribute('reverseDefectList'),
                false
            );
        }

        if ($root->hasAttribute('verbose')) {
            $result['verbose'] = $this->getBoolean(
                (string) $root->getAttribute('verbose'),
                false
            );
        }

        if ($root->hasAttribute('testdox')) {
            $testdox = $this->getBoolean(
                (string) $root->getAttribute('testdox'),
                false
            );

            if ($testdox) {
                if (isset($result['printerClass'])) {
                    $result['conflictBetweenPrinterClassAndTestdox'] = true;
                } else {
                    $result['printerClass'] = CliTestDoxPrinter::class;
                }
            }
        }

        if ($root->hasAttribute('registerMockObjectsFromTestArgumentsRecursively')) {
            $result['registerMockObjectsFromTestArgumentsRecursively'] = $this->getBoolean(
                (string) $root->getAttribute('registerMockObjectsFromTestArgumentsRecursively'),
                false
            );
        }

        if ($root->hasAttribute('extensionsDirectory')) {
            $result['extensionsDirectory'] = $this->toAbsolutePath(
                (string) $root->getAttribute(
                    'extensionsDirectory'
                )
            );
        }

        if ($root->hasAttribute('cacheResult')) {
            $result['cacheResult'] = $this->getBoolean(
                (string) $root->getAttribute('cacheResult'),
                true
            );
        }

        if ($root->hasAttribute('cacheResultFile')) {
            $result['cacheResultFile'] = $this->toAbsolutePath(
                (string) $root->getAttribute('cacheResultFile')
            );
        }

        if ($root->hasAttribute('executionOrder')) {
            foreach (explode(',', $root->getAttribute('executionOrder')) as $order) {
                switch ($order) {
                    case 'default':
                        $result['executionOrder']        = TestSuiteSorter::ORDER_DEFAULT;
                        $result['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFAULT;
                        $result['resolveDependencies']   = false;

                        break;

                    case 'defects':
                        $result['executionOrderDefects'] = TestSuiteSorter::ORDER_DEFECTS_FIRST;

                        break;

                    case 'depends':
                        $result['resolveDependencies'] = true;

                        break;

                    case 'duration':
                        $result['executionOrder'] = TestSuiteSorter::ORDER_DURATION;

                        break;

                    case 'no-depends':
                        $result['resolveDependencies'] = false;

                        break;

                    case 'random':
                        $result['executionOrder'] = TestSuiteSorter::ORDER_RANDOMIZED;

                        break;

                    case 'reverse':
                        $result['executionOrder'] = TestSuiteSorter::ORDER_REVERSED;

                        break;

                    case 'size':
                        $result['executionOrder'] = TestSuiteSorter::ORDER_SIZE;

                        break;
                }
            }
        }

        if ($root->hasAttribute('resolveDependencies')) {
            $result['resolveDependencies'] = $this->getBoolean(
                (string) $root->getAttribute('resolveDependencies'),
                false
            );
        }

        if ($root->hasAttribute('noInteraction')) {
            $result['noInteraction'] = $this->getBoolean(
                (string) $root->getAttribute('noInteraction'),
                false
            );
        }

        return $result;
    }

    /**
     * Returns the test suite configuration.
     *
     * @throws Exception
     */
    public function getTestSuiteConfiguration(string $testSuiteFilter = ''): TestSuite
    {
        $testSuiteNodes = $this->xpath->query('testsuites/testsuite');

        if ($testSuiteNodes->length === 0) {
            $testSuiteNodes = $this->xpath->query('testsuite');
        }

        if ($testSuiteNodes->length === 1) {
            return $this->getTestSuite($testSuiteNodes->item(0), $testSuiteFilter);
        }

        $suite = new TestSuite;

        foreach ($testSuiteNodes as $testSuiteNode) {
            $suite->addTestSuite(
                $this->getTestSuite($testSuiteNode, $testSuiteFilter)
            );
        }

        return $suite;
    }

    /**
     * Returns the test suite names from the configuration.
     */
    public function getTestSuiteNames(): array
    {
        $names = [];

        foreach ($this->xpath->query('*/testsuite') as $node) {
            /* @var DOMElement $node */
            $names[] = $node->getAttribute('name');
        }

        return $names;
    }

    private function validateConfigurationAgainstSchema(): void
    {
        $original    = libxml_use_internal_errors(true);
        $xsdFilename = __DIR__ . '/../../phpunit.xsd';

        if (defined('__PHPUNIT_PHAR_ROOT__')) {
            $xsdFilename = __PHPUNIT_PHAR_ROOT__ . '/phpunit.xsd';
        }

        $this->document->schemaValidateSource(file_get_contents($xsdFilename));
        $this->errors = libxml_get_errors();
        libxml_clear_errors();
        libxml_use_internal_errors($original);
    }

    /**
     * Collects and returns the configuration arguments from the PHPUnit
     * XML configuration.
     */
    private function getConfigurationArguments(DOMNodeList $nodes): array
    {
        $arguments = [];

        if ($nodes->length === 0) {
            return $arguments;
        }

        foreach ($nodes as $node) {
            if (!$node instanceof DOMElement) {
                continue;
            }

            if ($node->tagName !== 'arguments') {
                continue;
            }

            foreach ($node->childNodes as $argument) {
                if (!$argument instanceof DOMElement) {
                    continue;
                }

                if ($argument->tagName === 'file' || $argument->tagName === 'directory') {
                    $arguments[] = $this->toAbsolutePath((string) $argument->textContent);
                } else {
                    $arguments[] = Xml::xmlToVariable($argument);
                }
            }
        }

        return $arguments;
    }

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    private function getTestSuite(DOMElement $testSuiteNode, string $testSuiteFilter = ''): TestSuite
    {
        if ($testSuiteNode->hasAttribute('name')) {
            $suite = new TestSuite(
                (string) $testSuiteNode->getAttribute('name')
            );
        } else {
            $suite = new TestSuite;
        }

        $exclude = [];

        foreach ($testSuiteNode->getElementsByTagName('exclude') as $excludeNode) {
            $excludeFile = (string) $excludeNode->textContent;

            if ($excludeFile) {
                $exclude[] = $this->toAbsolutePath($excludeFile);
            }
        }

        $fileIteratorFacade = new FileIteratorFacade;
        $testSuiteFilter    = $testSuiteFilter ? explode(',', $testSuiteFilter) : [];

        foreach ($testSuiteNode->getElementsByTagName('directory') as $directoryNode) {
            assert($directoryNode instanceof DOMElement);

            if (!empty($testSuiteFilter) && !in_array($directoryNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) {
                continue;
            }

            $directory = (string) $directoryNode->textContent;

            if (empty($directory)) {
                continue;
            }

            if (!$this->satisfiesPhpVersion($directoryNode)) {
                continue;
            }

            $files = $fileIteratorFacade->getFilesAsArray(
                $this->toAbsolutePath($directory),
                $directoryNode->hasAttribute('suffix') ? (string) $directoryNode->getAttribute('suffix') : 'Test.php',
                $directoryNode->hasAttribute('prefix') ? (string) $directoryNode->getAttribute('prefix') : '',
                $exclude
            );

            $suite->addTestFiles($files);
        }

        foreach ($testSuiteNode->getElementsByTagName('file') as $fileNode) {
            assert($fileNode instanceof DOMElement);

            if (!empty($testSuiteFilter) && !in_array($fileNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) {
                continue;
            }

            $file = (string) $fileNode->textContent;

            if (empty($file)) {
                continue;
            }

            $file = $fileIteratorFacade->getFilesAsArray(
                $this->toAbsolutePath($file)
            );

            if (!isset($file[0])) {
                continue;
            }

            $file = $file[0];

            if (!$this->satisfiesPhpVersion($fileNode)) {
                continue;
            }

            $suite->addTestFile($file);
        }

        return $suite;
    }

    private function satisfiesPhpVersion(DOMElement $node): bool
    {
        $phpVersion         = PHP_VERSION;
        $phpVersionOperator = '>=';

        if ($node->hasAttribute('phpVersion')) {
            $phpVersion = (string) $node->getAttribute('phpVersion');
        }

        if ($node->hasAttribute('phpVersionOperator')) {
            $phpVersionOperator = (string) $node->getAttribute('phpVersionOperator');
        }

        return version_compare(PHP_VERSION, $phpVersion, (new VersionComparisonOperator($phpVersionOperator))->asString());
    }

    /**
     * if $value is 'false' or 'true', this returns the value that $value represents.
     * Otherwise, returns $default, which may be a string in rare cases.
     * See PHPUnit\Util\ConfigurationTest::testPHPConfigurationIsReadCorrectly.
     *
     * @param bool|string $default
     *
     * @return bool|string
     */
    private function getBoolean(string $value, $default)
    {
        if (strtolower($value) === 'false') {
            return false;
        }

        if (strtolower($value) === 'true') {
            return true;
        }

        return $default;
    }

    private function getInteger(string $value, int $default): int
    {
        if (is_numeric($value)) {
            return (int) $value;
        }

        return $default;
    }

    private function readFilterDirectories(string $query): array
    {
        $directories = [];

        foreach ($this->xpath->query($query) as $directoryNode) {
            assert($directoryNode instanceof DOMElement);

            $directoryPath = (string) $directoryNode->textContent;

            if (!$directoryPath) {
                continue;
            }

            $directories[] = [
                'path'   => $this->toAbsolutePath($directoryPath),
                'prefix' => $directoryNode->hasAttribute('prefix') ? (string) $directoryNode->getAttribute('prefix') : '',
                'suffix' => $directoryNode->hasAttribute('suffix') ? (string) $directoryNode->getAttribute('suffix') : '.php',
                'group'  => $directoryNode->hasAttribute('group') ? (string) $directoryNode->getAttribute('group') : 'DEFAULT',
            ];
        }

        return $directories;
    }

    /**
     * @return string[]
     */
    private function readFilterFiles(string $query): array
    {
        $files = [];

        foreach ($this->xpath->query($query) as $file) {
            $filePath = (string) $file->textContent;

            if ($filePath) {
                $files[] = $this->toAbsolutePath($filePath);
            }
        }

        return $files;
    }

    private function toAbsolutePath(string $path, bool $useIncludePath = false): string
    {
        $path = trim($path);

        if (strpos($path, '/') === 0) {
            return $path;
        }

        // Matches the following on Windows:
        //  - \\NetworkComputer\Path
        //  - \\.\D:
        //  - \\.\c:
        //  - C:\Windows
        //  - C:\windows
        //  - C:/windows
        //  - c:/windows
        if (defined('PHP_WINDOWS_VERSION_BUILD') &&
            ($path[0] === '\\' || (strlen($path) >= 3 && preg_match('#^[A-Z]\:[/\\\]#i', substr($path, 0, 3))))) {
            return $path;
        }

        if (strpos($path, '://') !== false) {
            return $path;
        }

        $file = dirname($this->filename) . DIRECTORY_SEPARATOR . $path;

        if ($useIncludePath && !file_exists($file)) {
            $includePathFile = stream_resolve_include_path($path);

            if ($includePathFile) {
                $file = $includePathFile;
            }
        }

        return $file;
    }

    private function parseGroupConfiguration(string $root): array
    {
        $groups = [
            'include' => [],
            'exclude' => [],
        ];

        foreach ($this->xpath->query($root . '/include/group') as $group) {
            $groups['include'][] = (string) $group->textContent;
        }

        foreach ($this->xpath->query($root . '/exclude/group') as $group) {
            $groups['exclude'][] = (string) $group->textContent;
        }

        return $groups;
    }

    private function getElementConfigurationParameters(DOMElement $element): array
    {
        $class     = (string) $element->getAttribute('class');
        $file      = '';
        $arguments = $this->getConfigurationArguments($element->childNodes);

        if ($element->getAttribute('file')) {
            $file = $this->toAbsolutePath(
                (string) $element->getAttribute('file'),
                true
            );
        }

        return [
            'class'     => $class,
            'file'      => $file,
            'arguments' => $arguments,
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\PHP;

use const PHP_MAJOR_VERSION;
use function tmpfile;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 *
 * @see https://bugs.php.net/bug.php?id=51800
 */
final class WindowsPhpProcess extends DefaultPhpProcess
{
    public function getCommand(array $settings, string $file = null): string
    {
        if (PHP_MAJOR_VERSION < 8) {
            return '"' . parent::getCommand($settings, $file) . '"';
        }

        return parent::getCommand($settings, $file);
    }

    /**
     * @throws Exception
     */
    protected function getHandles(): array
    {
        if (false === $stdout_handle = tmpfile()) {
            throw new Exception(
                'A temporary file could not be created; verify that your TEMP environment variable is writable'
            );
        }

        return [
            1 => $stdout_handle,
        ];
    }

    protected function useTemporaryFile(): bool
    {
        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\PHP;

use const DIRECTORY_SEPARATOR;
use const PHP_SAPI;
use function array_keys;
use function array_merge;
use function assert;
use function escapeshellarg;
use function ini_get_all;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use function str_replace;
use function strpos;
use function strrpos;
use function substr;
use function trim;
use function unserialize;
use __PHP_Incomplete_Class;
use ErrorException;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\SyntheticError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestResult;
use SebastianBergmann\Environment\Runtime;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
abstract class AbstractPhpProcess
{
    /**
     * @var Runtime
     */
    protected $runtime;

    /**
     * @var bool
     */
    protected $stderrRedirection = false;

    /**
     * @var string
     */
    protected $stdin = '';

    /**
     * @var string
     */
    protected $args = '';

    /**
     * @var array<string, string>
     */
    protected $env = [];

    /**
     * @var int
     */
    protected $timeout = 0;

    public static function factory(): self
    {
        if (DIRECTORY_SEPARATOR === '\\') {
            return new WindowsPhpProcess;
        }

        return new DefaultPhpProcess;
    }

    public function __construct()
    {
        $this->runtime = new Runtime;
    }

    /**
     * Defines if should use STDERR redirection or not.
     *
     * Then $stderrRedirection is TRUE, STDERR is redirected to STDOUT.
     */
    public function setUseStderrRedirection(bool $stderrRedirection): void
    {
        $this->stderrRedirection = $stderrRedirection;
    }

    /**
     * Returns TRUE if uses STDERR redirection or FALSE if not.
     */
    public function useStderrRedirection(): bool
    {
        return $this->stderrRedirection;
    }

    /**
     * Sets the input string to be sent via STDIN.
     */
    public function setStdin(string $stdin): void
    {
        $this->stdin = $stdin;
    }

    /**
     * Returns the input string to be sent via STDIN.
     */
    public function getStdin(): string
    {
        return $this->stdin;
    }

    /**
     * Sets the string of arguments to pass to the php job.
     */
    public function setArgs(string $args): void
    {
        $this->args = $args;
    }

    /**
     * Returns the string of arguments to pass to the php job.
     */
    public function getArgs(): string
    {
        return $this->args;
    }

    /**
     * Sets the array of environment variables to start the child process with.
     *
     * @param array<string, string> $env
     */
    public function setEnv(array $env): void
    {
        $this->env = $env;
    }

    /**
     * Returns the array of environment variables to start the child process with.
     */
    public function getEnv(): array
    {
        return $this->env;
    }

    /**
     * Sets the amount of seconds to wait before timing out.
     */
    public function setTimeout(int $timeout): void
    {
        $this->timeout = $timeout;
    }

    /**
     * Returns the amount of seconds to wait before timing out.
     */
    public function getTimeout(): int
    {
        return $this->timeout;
    }

    /**
     * Runs a single test in a separate PHP process.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function runTestJob(string $job, Test $test, TestResult $result): void
    {
        $result->startTest($test);

        $_result = $this->runJob($job);

        $this->processChildResult(
            $test,
            $result,
            $_result['stdout'],
            $_result['stderr']
        );
    }

    /**
     * Returns the command based into the configurations.
     */
    public function getCommand(array $settings, string $file = null): string
    {
        $command = $this->runtime->getBinary();

        if ($this->runtime->hasPCOV()) {
            $settings = array_merge(
                $settings,
                $this->runtime->getCurrentSettings(
                    array_keys(ini_get_all('pcov'))
                )
            );
        } elseif ($this->runtime->hasXdebug()) {
            $settings = array_merge(
                $settings,
                $this->runtime->getCurrentSettings(
                    array_keys(ini_get_all('xdebug'))
                )
            );
        }

        $command .= $this->settingsToParameters($settings);

        if (PHP_SAPI === 'phpdbg') {
            $command .= ' -qrr';

            if (!$file) {
                $command .= 's=';
            }
        }

        if ($file) {
            $command .= ' ' . escapeshellarg($file);
        }

        if ($this->args) {
            if (!$file) {
                $command .= ' --';
            }
            $command .= ' ' . $this->args;
        }

        if ($this->stderrRedirection) {
            $command .= ' 2>&1';
        }

        return $command;
    }

    /**
     * Runs a single job (PHP code) using a separate PHP process.
     */
    abstract public function runJob(string $job, array $settings = []): array;

    protected function settingsToParameters(array $settings): string
    {
        $buffer = '';

        foreach ($settings as $setting) {
            $buffer .= ' -d ' . escapeshellarg($setting);
        }

        return $buffer;
    }

    /**
     * Processes the TestResult object from an isolated process.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function processChildResult(Test $test, TestResult $result, string $stdout, string $stderr): void
    {
        $time = 0;

        if (!empty($stderr)) {
            $result->addError(
                $test,
                new Exception(trim($stderr)),
                $time
            );
        } else {
            set_error_handler(
                /**
                 * @throws ErrorException
                 */
                static function ($errno, $errstr, $errfile, $errline): void
                {
                    throw new ErrorException($errstr, $errno, $errno, $errfile, $errline);
                }
            );

            try {
                if (strpos($stdout, "#!/usr/bin/env php\n") === 0) {
                    $stdout = substr($stdout, 19);
                }

                $childResult = unserialize(str_replace("#!/usr/bin/env php\n", '', $stdout));
                restore_error_handler();

                if ($childResult === false) {
                    $result->addFailure(
                        $test,
                        new AssertionFailedError('Test was run in child process and ended unexpectedly'),
                        $time
                    );
                }
            } catch (ErrorException $e) {
                restore_error_handler();
                $childResult = false;

                $result->addError(
                    $test,
                    new Exception(trim($stdout), 0, $e),
                    $time
                );
            }

            if ($childResult !== false) {
                if (!empty($childResult['output'])) {
                    $output = $childResult['output'];
                }

                /* @var TestCase $test */

                $test->setResult($childResult['testResult']);
                $test->addToAssertionCount($childResult['numAssertions']);

                $childResult = $childResult['result'];
                assert($childResult instanceof TestResult);

                if ($result->getCollectCodeCoverageInformation()) {
                    $result->getCodeCoverage()->merge(
                        $childResult->getCodeCoverage()
                    );
                }

                $time           = $childResult->time();
                $notImplemented = $childResult->notImplemented();
                $risky          = $childResult->risky();
                $skipped        = $childResult->skipped();
                $errors         = $childResult->errors();
                $warnings       = $childResult->warnings();
                $failures       = $childResult->failures();

                if (!empty($notImplemented)) {
                    $result->addError(
                        $test,
                        $this->getException($notImplemented[0]),
                        $time
                    );
                } elseif (!empty($risky)) {
                    $result->addError(
                        $test,
                        $this->getException($risky[0]),
                        $time
                    );
                } elseif (!empty($skipped)) {
                    $result->addError(
                        $test,
                        $this->getException($skipped[0]),
                        $time
                    );
                } elseif (!empty($errors)) {
                    $result->addError(
                        $test,
                        $this->getException($errors[0]),
                        $time
                    );
                } elseif (!empty($warnings)) {
                    $result->addWarning(
                        $test,
                        $this->getException($warnings[0]),
                        $time
                    );
                } elseif (!empty($failures)) {
                    $result->addFailure(
                        $test,
                        $this->getException($failures[0]),
                        $time
                    );
                }
            }
        }

        $result->endTest($test, $time);

        if (!empty($output)) {
            print $output;
        }
    }

    /**
     * Gets the thrown exception from a PHPUnit\Framework\TestFailure.
     *
     * @see https://github.com/sebastianbergmann/phpunit/issues/74
     */
    private function getException(TestFailure $error): Exception
    {
        $exception = $error->thrownException();

        if ($exception instanceof __PHP_Incomplete_Class) {
            $exceptionArray = [];

            foreach ((array) $exception as $key => $value) {
                $key                  = substr($key, strrpos($key, "\0") + 1);
                $exceptionArray[$key] = $value;
            }

            $exception = new SyntheticError(
                sprintf(
                    '%s: %s',
                    $exceptionArray['_PHP_Incomplete_Class_Name'],
                    $exceptionArray['message']
                ),
                $exceptionArray['code'],
                $exceptionArray['file'],
                $exceptionArray['line'],
                $exceptionArray['trace']
            );
        }

        return $exception;
    }
}
<?php
use PHPUnit\Framework\TestCase;
use SebastianBergmann\CodeCoverage\CodeCoverage;

if (!defined('STDOUT')) {
    // php://stdout does not obey output buffering. Any output would break
    // unserialization of child process results in the parent process.
    define('STDOUT', fopen('php://temp', 'w+b'));
    define('STDERR', fopen('php://stderr', 'wb'));
}

{iniSettings}
ini_set('display_errors', 'stderr');
set_include_path('{include_path}');

$composerAutoload = {composerAutoload};
$phar             = {phar};

ob_start();

if ($composerAutoload) {
    require_once $composerAutoload;
    define('PHPUNIT_COMPOSER_INSTALL', $composerAutoload);
} else if ($phar) {
    require $phar;
}

function __phpunit_run_isolated_test()
{
    if (!class_exists('{className}')) {
        require_once '{filename}';
    }

    $result = new PHPUnit\Framework\TestResult;

    if ({collectCodeCoverageInformation}) {
        $result->setCodeCoverage(
            new CodeCoverage(
                null,
                unserialize('{codeCoverageFilter}')
            )
        );
    }

    $result->beStrictAboutTestsThatDoNotTestAnything({isStrictAboutTestsThatDoNotTestAnything});
    $result->beStrictAboutOutputDuringTests({isStrictAboutOutputDuringTests});
    $result->enforceTimeLimit({enforcesTimeLimit});
    $result->beStrictAboutTodoAnnotatedTests({isStrictAboutTodoAnnotatedTests});
    $result->beStrictAboutResourceUsageDuringSmallTests({isStrictAboutResourceUsageDuringSmallTests});

    $test = new {className}('{methodName}', unserialize('{data}'), '{dataName}');
    \assert($test instanceof TestCase);

    $test->setDependencyInput(unserialize('{dependencyInput}'));
    $test->setInIsolation(true);

    ob_end_clean();
    $test->run($result);
    $output = '';
    if (!$test->hasExpectationOnOutput()) {
        $output = $test->getActualOutput();
    }

    ini_set('xdebug.scream', '0');
    @rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */
    if ($stdout = @stream_get_contents(STDOUT)) {
        $output = $stdout . $output;
        $streamMetaData = stream_get_meta_data(STDOUT);
        if (!empty($streamMetaData['stream_type']) && 'STDIO' === $streamMetaData['stream_type']) {
            @ftruncate(STDOUT, 0);
            @rewind(STDOUT);
        }
    }

    print serialize(
      [
        'testResult'    => $test->getResult(),
        'numAssertions' => $test->getNumAssertions(),
        'result'        => $result,
        'output'        => $output
      ]
    );
}

$configurationFilePath = '{configurationFilePath}';

if ('' !== $configurationFilePath) {
    $configuration = PHPUnit\Util\Configuration::getInstance($configurationFilePath);
    $configuration->handlePHPConfiguration();
    unset($configuration);
}

function __phpunit_error_handler($errno, $errstr, $errfile, $errline)
{
   return true;
}

set_error_handler('__phpunit_error_handler');

{constants}
{included_files}
{globals}

restore_error_handler();

if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
    require_once $GLOBALS['__PHPUNIT_BOOTSTRAP'];
    unset($GLOBALS['__PHPUNIT_BOOTSTRAP']);
}

__phpunit_run_isolated_test();
<?php
use SebastianBergmann\CodeCoverage\CodeCoverage;

$composerAutoload = {composerAutoload};
$phar             = {phar};

ob_start();

$GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'][] = '{job}';

if ($composerAutoload) {
    require_once $composerAutoload;
    define('PHPUNIT_COMPOSER_INSTALL', $composerAutoload);
} else if ($phar) {
    require $phar;
}

{globals}
$coverage = null;

if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
    require_once $GLOBALS['__PHPUNIT_BOOTSTRAP'];
}

if (class_exists('SebastianBergmann\CodeCoverage\CodeCoverage')) {
    $coverage =	new CodeCoverage(null);
    $coverage->start(__FILE__);
}

register_shutdown_function(function() use ($coverage) {
    $output = null;
    if ($coverage) {
        $output = $coverage->stop();
    }
    file_put_contents('{coverageFile}', serialize($output));
});

ob_end_clean();

require '{job}';
<?php
use SebastianBergmann\CodeCoverage\CodeCoverage;

if (!defined('STDOUT')) {
    // php://stdout does not obey output buffering. Any output would break
    // unserialization of child process results in the parent process.
    define('STDOUT', fopen('php://temp', 'w+b'));
    define('STDERR', fopen('php://stderr', 'wb'));
}

{iniSettings}
ini_set('display_errors', 'stderr');
set_include_path('{include_path}');

$composerAutoload = {composerAutoload};
$phar             = {phar};

ob_start();

if ($composerAutoload) {
    require_once $composerAutoload;
    define('PHPUNIT_COMPOSER_INSTALL', $composerAutoload);
} else if ($phar) {
    require $phar;
}

function __phpunit_run_isolated_test()
{
    if (!class_exists('{className}')) {
        require_once '{filename}';
    }

    $result = new PHPUnit\Framework\TestResult;

    if ({collectCodeCoverageInformation}) {
        $result->setCodeCoverage(
            new CodeCoverage(
                null,
                unserialize('{codeCoverageFilter}')
            )
        );
    }

    $result->beStrictAboutTestsThatDoNotTestAnything({isStrictAboutTestsThatDoNotTestAnything});
    $result->beStrictAboutOutputDuringTests({isStrictAboutOutputDuringTests});
    $result->enforceTimeLimit({enforcesTimeLimit});
    $result->beStrictAboutTodoAnnotatedTests({isStrictAboutTodoAnnotatedTests});
    $result->beStrictAboutResourceUsageDuringSmallTests({isStrictAboutResourceUsageDuringSmallTests});

    $test = new {className}('{name}', unserialize('{data}'), '{dataName}');
    $test->setDependencyInput(unserialize('{dependencyInput}'));
    $test->setInIsolation(TRUE);

    ob_end_clean();
    $test->run($result);
    $output = '';
    if (!$test->hasExpectationOnOutput()) {
        $output = $test->getActualOutput();
    }

    ini_set('xdebug.scream', '0');
    @rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */
    if ($stdout = @stream_get_contents(STDOUT)) {
        $output = $stdout . $output;
        $streamMetaData = stream_get_meta_data(STDOUT);
        if (!empty($streamMetaData['stream_type']) && 'STDIO' === $streamMetaData['stream_type']) {
            @ftruncate(STDOUT, 0);
            @rewind(STDOUT);
        }
    }

    print serialize(
      [
        'testResult'    => $test->getResult(),
        'numAssertions' => $test->getNumAssertions(),
        'result'        => $result,
        'output'        => $output
      ]
    );
}

$configurationFilePath = '{configurationFilePath}';

if ('' !== $configurationFilePath) {
    $configuration = PHPUnit\Util\Configuration::getInstance($configurationFilePath);
    $configuration->handlePHPConfiguration();
    unset($configuration);
}

function __phpunit_error_handler($errno, $errstr, $errfile, $errline)
{
   return true;
}

set_error_handler('__phpunit_error_handler');

{constants}
{included_files}
{globals}

restore_error_handler();

if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
    require_once $GLOBALS['__PHPUNIT_BOOTSTRAP'];
    unset($GLOBALS['__PHPUNIT_BOOTSTRAP']);
}

__phpunit_run_isolated_test();
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\PHP;

use function array_merge;
use function fclose;
use function file_put_contents;
use function fread;
use function fwrite;
use function is_array;
use function is_resource;
use function proc_close;
use function proc_open;
use function proc_terminate;
use function rewind;
use function sprintf;
use function stream_get_contents;
use function stream_select;
use function sys_get_temp_dir;
use function tempnam;
use function unlink;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class DefaultPhpProcess extends AbstractPhpProcess
{
    /**
     * @var string
     */
    protected $tempFile;

    /**
     * Runs a single job (PHP code) using a separate PHP process.
     *
     * @throws Exception
     */
    public function runJob(string $job, array $settings = []): array
    {
        if ($this->stdin || $this->useTemporaryFile()) {
            if (!($this->tempFile = tempnam(sys_get_temp_dir(), 'PHPUnit')) ||
                file_put_contents($this->tempFile, $job) === false) {
                throw new Exception(
                    'Unable to write temporary file'
                );
            }

            $job = $this->stdin;
        }

        return $this->runProcess($job, $settings);
    }

    /**
     * Returns an array of file handles to be used in place of pipes.
     */
    protected function getHandles(): array
    {
        return [];
    }

    /**
     * Handles creating the child process and returning the STDOUT and STDERR.
     *
     * @throws Exception
     */
    protected function runProcess(string $job, array $settings): array
    {
        $handles = $this->getHandles();

        $env = null;

        if ($this->env) {
            $env = $_SERVER ?? [];
            unset($env['argv'], $env['argc']);
            $env = array_merge($env, $this->env);

            foreach ($env as $envKey => $envVar) {
                if (is_array($envVar)) {
                    unset($env[$envKey]);
                }
            }
        }

        $pipeSpec = [
            0 => $handles[0] ?? ['pipe', 'r'],
            1 => $handles[1] ?? ['pipe', 'w'],
            2 => $handles[2] ?? ['pipe', 'w'],
        ];

        $process = proc_open(
            $this->getCommand($settings, $this->tempFile),
            $pipeSpec,
            $pipes,
            null,
            $env
        );

        if (!is_resource($process)) {
            throw new Exception(
                'Unable to spawn worker process'
            );
        }

        if ($job) {
            $this->process($pipes[0], $job);
        }

        fclose($pipes[0]);

        $stderr = $stdout = '';

        if ($this->timeout) {
            unset($pipes[0]);

            while (true) {
                $r = $pipes;
                $w = null;
                $e = null;

                $n = @stream_select($r, $w, $e, $this->timeout);

                if ($n === false) {
                    break;
                }

                if ($n === 0) {
                    proc_terminate($process, 9);

                    throw new Exception(
                        sprintf(
                            'Job execution aborted after %d seconds',
                            $this->timeout
                        )
                    );
                }

                if ($n > 0) {
                    foreach ($r as $pipe) {
                        $pipeOffset = 0;

                        foreach ($pipes as $i => $origPipe) {
                            if ($pipe === $origPipe) {
                                $pipeOffset = $i;

                                break;
                            }
                        }

                        if (!$pipeOffset) {
                            break;
                        }

                        $line = fread($pipe, 8192);

                        if ($line === '' || $line === false) {
                            fclose($pipes[$pipeOffset]);

                            unset($pipes[$pipeOffset]);
                        } elseif ($pipeOffset === 1) {
                            $stdout .= $line;
                        } else {
                            $stderr .= $line;
                        }
                    }

                    if (empty($pipes)) {
                        break;
                    }
                }
            }
        } else {
            if (isset($pipes[1])) {
                $stdout = stream_get_contents($pipes[1]);

                fclose($pipes[1]);
            }

            if (isset($pipes[2])) {
                $stderr = stream_get_contents($pipes[2]);

                fclose($pipes[2]);
            }
        }

        if (isset($handles[1])) {
            rewind($handles[1]);

            $stdout = stream_get_contents($handles[1]);

            fclose($handles[1]);
        }

        if (isset($handles[2])) {
            rewind($handles[2]);

            $stderr = stream_get_contents($handles[2]);

            fclose($handles[2]);
        }

        proc_close($process);

        $this->cleanup();

        return ['stdout' => $stdout, 'stderr' => $stderr];
    }

    protected function process($pipe, string $job): void
    {
        fwrite($pipe, $job);
    }

    protected function cleanup(): void
    {
        if ($this->tempFile) {
            unlink($this->tempFile);
        }
    }

    protected function useTemporaryFile(): bool
    {
        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function in_array;
use function sprintf;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 *
 * @psalm-immutable
 */
final class VersionComparisonOperator
{
    /**
     * @psalm-var '<'|'lt'|'<='|'le'|'>'|'gt'|'>='|'ge'|'=='|'='|'eq'|'!='|'<>'|'ne'
     */
    private $operator;

    public function __construct(string $operator)
    {
        $this->ensureOperatorIsValid($operator);

        $this->operator = $operator;
    }

    /**
     * @return '!='|'<'|'<='|'<>'|'='|'=='|'>'|'>='|'eq'|'ge'|'gt'|'le'|'lt'|'ne'
     */
    public function asString(): string
    {
        return $this->operator;
    }

    /**
     * @throws Exception
     *
     * @psalm-assert '<'|'lt'|'<='|'le'|'>'|'gt'|'>='|'ge'|'=='|'='|'eq'|'!='|'<>'|'ne' $operator
     */
    private function ensureOperatorIsValid(string $operator): void
    {
        if (!in_array($operator, ['<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne'], true)) {
            throw new Exception(
                sprintf(
                    '"%s" is not a valid version_compare() operator',
                    $operator
                )
            );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const PHP_OS;
use const PHP_VERSION;
use function addcslashes;
use function array_flip;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function array_unique;
use function array_unshift;
use function class_exists;
use function class_implements;
use function class_parents;
use function count;
use function explode;
use function extension_loaded;
use function function_exists;
use function get_class;
use function ini_get;
use function interface_exists;
use function is_array;
use function is_int;
use function method_exists;
use function phpversion;
use function preg_match;
use function preg_replace;
use function range;
use function sprintf;
use function str_replace;
use function strncmp;
use function strpos;
use function trait_exists;
use function version_compare;
use PHPUnit\Framework\CodeCoverageException;
use PHPUnit\Framework\InvalidCoversTargetException;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Warning;
use PHPUnit\Runner\Version;
use PHPUnit\Util\Annotation\Registry;
use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionMethod;
use SebastianBergmann\Environment\OperatingSystem;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Test
{
    /**
     * @var int
     */
    public const UNKNOWN = -1;

    /**
     * @var int
     */
    public const SMALL = 0;

    /**
     * @var int
     */
    public const MEDIUM = 1;

    /**
     * @var int
     */
    public const LARGE = 2;

    /**
     * @var array
     */
    private static $hookMethods = [];

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public static function describe(\PHPUnit\Framework\Test $test): array
    {
        if ($test instanceof TestCase) {
            return [get_class($test), $test->getName()];
        }

        if ($test instanceof SelfDescribing) {
            return ['', $test->toString()];
        }

        return ['', get_class($test)];
    }

    public static function describeAsString(\PHPUnit\Framework\Test $test): string
    {
        if ($test instanceof SelfDescribing) {
            return $test->toString();
        }

        return get_class($test);
    }

    /**
     * @throws CodeCoverageException
     *
     * @return array|bool
     *
     * @psalm-param class-string $className
     */
    public static function getLinesToBeCovered(string $className, string $methodName)
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        if (!self::shouldCoversAnnotationBeUsed($annotations)) {
            return false;
        }

        return self::getLinesToBeCoveredOrUsed($className, $methodName, 'covers');
    }

    /**
     * Returns lines of code specified with the @uses annotation.
     *
     * @throws CodeCoverageException
     *
     * @psalm-param class-string $className
     */
    public static function getLinesToBeUsed(string $className, string $methodName): array
    {
        return self::getLinesToBeCoveredOrUsed($className, $methodName, 'uses');
    }

    public static function requiresCodeCoverageDataCollection(TestCase $test): bool
    {
        $annotations = $test->getAnnotations();

        // If there is no @covers annotation but a @coversNothing annotation on
        // the test method then code coverage data does not need to be collected
        if (isset($annotations['method']['coversNothing'])) {
            return false;
        }

        // If there is at least one @covers annotation then
        // code coverage data needs to be collected
        if (isset($annotations['method']['covers'])) {
            return true;
        }

        // If there is no @covers annotation but a @coversNothing annotation
        // then code coverage data does not need to be collected
        if (isset($annotations['class']['coversNothing'])) {
            return false;
        }

        // If there is no @coversNothing annotation then
        // code coverage data may be collected
        return true;
    }

    /**
     * @throws Exception
     *
     * @psalm-param class-string $className
     */
    public static function getRequirements(string $className, string $methodName): array
    {
        return self::mergeArraysRecursively(
            Registry::getInstance()->forClassName($className)->requirements(),
            Registry::getInstance()->forMethod($className, $methodName)->requirements()
        );
    }

    /**
     * Returns the missing requirements for a test.
     *
     * @throws Exception
     * @throws Warning
     *
     * @psalm-param class-string $className
     */
    public static function getMissingRequirements(string $className, string $methodName): array
    {
        $required = self::getRequirements($className, $methodName);
        $missing  = [];
        $hint     = null;

        if (!empty($required['PHP'])) {
            $operator = new VersionComparisonOperator(empty($required['PHP']['operator']) ? '>=' : $required['PHP']['operator']);

            if (!version_compare(PHP_VERSION, $required['PHP']['version'], $operator->asString())) {
                $missing[] = sprintf('PHP %s %s is required.', $operator->asString(), $required['PHP']['version']);
                $hint      = 'PHP';
            }
        } elseif (!empty($required['PHP_constraint'])) {
            $version = new \PharIo\Version\Version(self::sanitizeVersionNumber(PHP_VERSION));

            if (!$required['PHP_constraint']['constraint']->complies($version)) {
                $missing[] = sprintf(
                    'PHP version does not match the required constraint %s.',
                    $required['PHP_constraint']['constraint']->asString()
                );

                $hint = 'PHP_constraint';
            }
        }

        if (!empty($required['PHPUnit'])) {
            $phpunitVersion = Version::id();

            $operator = new VersionComparisonOperator(empty($required['PHPUnit']['operator']) ? '>=' : $required['PHPUnit']['operator']);

            if (!version_compare($phpunitVersion, $required['PHPUnit']['version'], $operator->asString())) {
                $missing[] = sprintf('PHPUnit %s %s is required.', $operator->asString(), $required['PHPUnit']['version']);
                $hint      = $hint ?? 'PHPUnit';
            }
        } elseif (!empty($required['PHPUnit_constraint'])) {
            $phpunitVersion = new \PharIo\Version\Version(self::sanitizeVersionNumber(Version::id()));

            if (!$required['PHPUnit_constraint']['constraint']->complies($phpunitVersion)) {
                $missing[] = sprintf(
                    'PHPUnit version does not match the required constraint %s.',
                    $required['PHPUnit_constraint']['constraint']->asString()
                );

                $hint = $hint ?? 'PHPUnit_constraint';
            }
        }

        if (!empty($required['OSFAMILY']) && $required['OSFAMILY'] !== (new OperatingSystem)->getFamily()) {
            $missing[] = sprintf('Operating system %s is required.', $required['OSFAMILY']);
            $hint      = $hint ?? 'OSFAMILY';
        }

        if (!empty($required['OS'])) {
            $requiredOsPattern = sprintf('/%s/i', addcslashes($required['OS'], '/'));

            if (!preg_match($requiredOsPattern, PHP_OS)) {
                $missing[] = sprintf('Operating system matching %s is required.', $requiredOsPattern);
                $hint      = $hint ?? 'OS';
            }
        }

        if (!empty($required['functions'])) {
            foreach ($required['functions'] as $function) {
                $pieces = explode('::', $function);

                if (count($pieces) === 2 && class_exists($pieces[0]) && method_exists($pieces[0], $pieces[1])) {
                    continue;
                }

                if (function_exists($function)) {
                    continue;
                }

                $missing[] = sprintf('Function %s is required.', $function);
                $hint      = $hint ?? 'function_' . $function;
            }
        }

        if (!empty($required['setting'])) {
            foreach ($required['setting'] as $setting => $value) {
                if (ini_get($setting) !== $value) {
                    $missing[] = sprintf('Setting "%s" must be "%s".', $setting, $value);
                    $hint      = $hint ?? '__SETTING_' . $setting;
                }
            }
        }

        if (!empty($required['extensions'])) {
            foreach ($required['extensions'] as $extension) {
                if (isset($required['extension_versions'][$extension])) {
                    continue;
                }

                if (!extension_loaded($extension)) {
                    $missing[] = sprintf('Extension %s is required.', $extension);
                    $hint      = $hint ?? 'extension_' . $extension;
                }
            }
        }

        if (!empty($required['extension_versions'])) {
            foreach ($required['extension_versions'] as $extension => $req) {
                $actualVersion = phpversion($extension);

                $operator = new VersionComparisonOperator(empty($req['operator']) ? '>=' : $req['operator']);

                if ($actualVersion === false || !version_compare($actualVersion, $req['version'], $operator->asString())) {
                    $missing[] = sprintf('Extension %s %s %s is required.', $extension, $operator->asString(), $req['version']);
                    $hint      = $hint ?? 'extension_' . $extension;
                }
            }
        }

        if ($hint && isset($required['__OFFSET'])) {
            array_unshift($missing, '__OFFSET_FILE=' . $required['__OFFSET']['__FILE']);
            array_unshift($missing, '__OFFSET_LINE=' . ($required['__OFFSET'][$hint] ?? 1));
        }

        return $missing;
    }

    /**
     * Returns the expected exception for a test.
     *
     * @return array|false
     *
     * @deprecated
     *
     * @codeCoverageIgnore
     *
     * @psalm-param class-string $className
     */
    public static function getExpectedException(string $className, string $methodName)
    {
        return Registry::getInstance()->forMethod($className, $methodName)->expectedException();
    }

    /**
     * Returns the provided data for a method.
     *
     * @throws Exception
     *
     * @psalm-param class-string $className
     */
    public static function getProvidedData(string $className, string $methodName): ?array
    {
        return Registry::getInstance()->forMethod($className, $methodName)->getProvidedData();
    }

    /**
     * @psalm-param class-string $className
     */
    public static function parseTestMethodAnnotations(string $className, ?string $methodName = ''): array
    {
        $registry = Registry::getInstance();

        if ($methodName !== null) {
            try {
                return [
                    'method' => $registry->forMethod($className, $methodName)->symbolAnnotations(),
                    'class'  => $registry->forClassName($className)->symbolAnnotations(),
                ];
            } catch (Exception $methodNotFound) {
                // ignored
            }
        }

        return [
            'method' => null,
            'class'  => $registry->forClassName($className)->symbolAnnotations(),
        ];
    }

    /**
     * @psalm-param class-string $className
     */
    public static function getInlineAnnotations(string $className, string $methodName): array
    {
        return Registry::getInstance()->forMethod($className, $methodName)->getInlineAnnotations();
    }

    /** @psalm-param class-string $className */
    public static function getBackupSettings(string $className, string $methodName): array
    {
        return [
            'backupGlobals'          => self::getBooleanAnnotationSetting(
                $className,
                $methodName,
                'backupGlobals'
            ),
            'backupStaticAttributes' => self::getBooleanAnnotationSetting(
                $className,
                $methodName,
                'backupStaticAttributes'
            ),
        ];
    }

    /** @psalm-param class-string $className */
    public static function getDependencies(string $className, string $methodName): array
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        $dependencies = $annotations['class']['depends'] ?? [];

        if (isset($annotations['method']['depends'])) {
            $dependencies = array_merge(
                $dependencies,
                $annotations['method']['depends']
            );
        }

        return array_unique($dependencies);
    }

    /** @psalm-param class-string $className */
    public static function getGroups(string $className, ?string $methodName = ''): array
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        $groups = [];

        if (isset($annotations['method']['author'])) {
            $groups[] = $annotations['method']['author'];
        } elseif (isset($annotations['class']['author'])) {
            $groups[] = $annotations['class']['author'];
        }

        if (isset($annotations['class']['group'])) {
            $groups[] = $annotations['class']['group'];
        }

        if (isset($annotations['method']['group'])) {
            $groups[] = $annotations['method']['group'];
        }

        if (isset($annotations['class']['ticket'])) {
            $groups[] = $annotations['class']['ticket'];
        }

        if (isset($annotations['method']['ticket'])) {
            $groups[] = $annotations['method']['ticket'];
        }

        foreach (['method', 'class'] as $element) {
            foreach (['small', 'medium', 'large'] as $size) {
                if (isset($annotations[$element][$size])) {
                    $groups[] = [$size];

                    break 2;
                }
            }
        }

        return array_unique(array_merge([], ...$groups));
    }

    /** @psalm-param class-string $className */
    public static function getSize(string $className, ?string $methodName): int
    {
        $groups = array_flip(self::getGroups($className, $methodName));

        if (isset($groups['large'])) {
            return self::LARGE;
        }

        if (isset($groups['medium'])) {
            return self::MEDIUM;
        }

        if (isset($groups['small'])) {
            return self::SMALL;
        }

        return self::UNKNOWN;
    }

    /** @psalm-param class-string $className */
    public static function getProcessIsolationSettings(string $className, string $methodName): bool
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        return isset($annotations['class']['runTestsInSeparateProcesses']) || isset($annotations['method']['runInSeparateProcess']);
    }

    /** @psalm-param class-string $className */
    public static function getClassProcessIsolationSettings(string $className, string $methodName): bool
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        return isset($annotations['class']['runClassInSeparateProcess']);
    }

    /** @psalm-param class-string $className */
    public static function getPreserveGlobalStateSettings(string $className, string $methodName): ?bool
    {
        return self::getBooleanAnnotationSetting(
            $className,
            $methodName,
            'preserveGlobalState'
        );
    }

    /** @psalm-param class-string $className */
    public static function getHookMethods(string $className): array
    {
        if (!class_exists($className, false)) {
            return self::emptyHookMethodsArray();
        }

        if (!isset(self::$hookMethods[$className])) {
            self::$hookMethods[$className] = self::emptyHookMethodsArray();

            try {
                foreach ((new Reflection)->methodsInTestClass(new ReflectionClass($className)) as $method) {
                    $docBlock = Registry::getInstance()->forMethod($className, $method->getName());

                    if ($method->isStatic()) {
                        if ($docBlock->isHookToBeExecutedBeforeClass()) {
                            array_unshift(
                                self::$hookMethods[$className]['beforeClass'],
                                $method->getName()
                            );
                        }

                        if ($docBlock->isHookToBeExecutedAfterClass()) {
                            self::$hookMethods[$className]['afterClass'][] = $method->getName();
                        }
                    }

                    if ($docBlock->isToBeExecutedBeforeTest()) {
                        array_unshift(
                            self::$hookMethods[$className]['before'],
                            $method->getName()
                        );
                    }

                    if ($docBlock->isToBeExecutedAfterTest()) {
                        self::$hookMethods[$className]['after'][] = $method->getName();
                    }
                }
            } catch (ReflectionException $e) {
            }
        }

        return self::$hookMethods[$className];
    }

    public static function isTestMethod(ReflectionMethod $method): bool
    {
        if (!$method->isPublic()) {
            return false;
        }

        if (strpos($method->getName(), 'test') === 0) {
            return true;
        }

        return array_key_exists(
            'test',
            Registry::getInstance()->forMethod(
                $method->getDeclaringClass()->getName(),
                $method->getName()
            )
            ->symbolAnnotations()
        );
    }

    /**
     * @throws CodeCoverageException
     *
     * @psalm-param class-string $className
     */
    private static function getLinesToBeCoveredOrUsed(string $className, string $methodName, string $mode): array
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        $classShortcut = null;

        if (!empty($annotations['class'][$mode . 'DefaultClass'])) {
            if (count($annotations['class'][$mode . 'DefaultClass']) > 1) {
                throw new CodeCoverageException(
                    sprintf(
                        'More than one @%sClass annotation in class or interface "%s".',
                        $mode,
                        $className
                    )
                );
            }

            $classShortcut = $annotations['class'][$mode . 'DefaultClass'][0];
        }

        $list = $annotations['class'][$mode] ?? [];

        if (isset($annotations['method'][$mode])) {
            $list = array_merge($list, $annotations['method'][$mode]);
        }

        $codeList = [];

        foreach (array_unique($list) as $element) {
            if ($classShortcut && strncmp($element, '::', 2) === 0) {
                $element = $classShortcut . $element;
            }

            $element = preg_replace('/[\s()]+$/', '', $element);
            $element = explode(' ', $element);
            $element = $element[0];

            if ($mode === 'covers' && interface_exists($element)) {
                throw new InvalidCoversTargetException(
                    sprintf(
                        'Trying to @cover interface "%s".',
                        $element
                    )
                );
            }

            $codeList[] = self::resolveElementToReflectionObjects($element);
        }

        return self::resolveReflectionObjectsToLines(array_merge([], ...$codeList));
    }

    private static function emptyHookMethodsArray(): array
    {
        return [
            'beforeClass' => ['setUpBeforeClass'],
            'before'      => ['setUp'],
            'after'       => ['tearDown'],
            'afterClass'  => ['tearDownAfterClass'],
        ];
    }

    /** @psalm-param class-string $className */
    private static function getBooleanAnnotationSetting(string $className, ?string $methodName, string $settingName): ?bool
    {
        $annotations = self::parseTestMethodAnnotations(
            $className,
            $methodName
        );

        if (isset($annotations['method'][$settingName])) {
            if ($annotations['method'][$settingName][0] === 'enabled') {
                return true;
            }

            if ($annotations['method'][$settingName][0] === 'disabled') {
                return false;
            }
        }

        if (isset($annotations['class'][$settingName])) {
            if ($annotations['class'][$settingName][0] === 'enabled') {
                return true;
            }

            if ($annotations['class'][$settingName][0] === 'disabled') {
                return false;
            }
        }

        return null;
    }

    /**
     * @throws InvalidCoversTargetException
     */
    private static function resolveElementToReflectionObjects(string $element): array
    {
        $codeToCoverList = [];

        if (function_exists($element) && strpos($element, '\\') !== false) {
            try {
                $codeToCoverList[] = new ReflectionFunction($element);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd
        } elseif (strpos($element, '::') !== false) {
            [$className, $methodName] = explode('::', $element);

            if (isset($methodName[0]) && $methodName[0] === '<') {
                $classes = [$className];

                foreach ($classes as $className) {
                    if (!class_exists($className) &&
                        !interface_exists($className) &&
                        !trait_exists($className)) {
                        throw new InvalidCoversTargetException(
                            sprintf(
                                'Trying to @cover or @use not existing class or ' .
                                'interface "%s".',
                                $className
                            )
                        );
                    }

                    try {
                        $methods = (new ReflectionClass($className))->getMethods();
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new Exception(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    $inverse    = isset($methodName[1]) && $methodName[1] === '!';
                    $visibility = 'isPublic';

                    if (strpos($methodName, 'protected')) {
                        $visibility = 'isProtected';
                    } elseif (strpos($methodName, 'private')) {
                        $visibility = 'isPrivate';
                    }

                    foreach ($methods as $method) {
                        if ($inverse && !$method->{$visibility}()) {
                            $codeToCoverList[] = $method;
                        } elseif (!$inverse && $method->{$visibility}()) {
                            $codeToCoverList[] = $method;
                        }
                    }
                }
            } else {
                $classes = [$className];

                foreach ($classes as $className) {
                    if ($className === '' && function_exists($methodName)) {
                        try {
                            $codeToCoverList[] = new ReflectionFunction(
                                $methodName
                            );
                            // @codeCoverageIgnoreStart
                        } catch (ReflectionException $e) {
                            throw new Exception(
                                $e->getMessage(),
                                $e->getCode(),
                                $e
                            );
                        }
                        // @codeCoverageIgnoreEnd
                    } else {
                        if (!((class_exists($className) || interface_exists($className) || trait_exists($className)) &&
                            method_exists($className, $methodName))) {
                            throw new InvalidCoversTargetException(
                                sprintf(
                                    'Trying to @cover or @use not existing method "%s::%s".',
                                    $className,
                                    $methodName
                                )
                            );
                        }

                        try {
                            $codeToCoverList[] = new ReflectionMethod(
                                $className,
                                $methodName
                            );
                            // @codeCoverageIgnoreStart
                        } catch (ReflectionException $e) {
                            throw new Exception(
                                $e->getMessage(),
                                $e->getCode(),
                                $e
                            );
                        }
                        // @codeCoverageIgnoreEnd
                    }
                }
            }
        } else {
            $extended = false;

            if (strpos($element, '<extended>') !== false) {
                $element  = str_replace('<extended>', '', $element);
                $extended = true;
            }

            $classes = [$element];

            if ($extended) {
                $classes = array_merge(
                    $classes,
                    class_implements($element),
                    class_parents($element)
                );
            }

            foreach ($classes as $className) {
                if (!class_exists($className) &&
                    !interface_exists($className) &&
                    !trait_exists($className)) {
                    throw new InvalidCoversTargetException(
                        sprintf(
                            'Trying to @cover or @use not existing class or ' .
                            'interface "%s".',
                            $className
                        )
                    );
                }

                try {
                    $codeToCoverList[] = new ReflectionClass($className);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd
            }
        }

        return $codeToCoverList;
    }

    private static function resolveReflectionObjectsToLines(array $reflectors): array
    {
        $result = [];

        foreach ($reflectors as $reflector) {
            if ($reflector instanceof ReflectionClass) {
                foreach ($reflector->getTraits() as $trait) {
                    $reflectors[] = $trait;
                }
            }
        }

        foreach ($reflectors as $reflector) {
            $filename = $reflector->getFileName();

            if (!isset($result[$filename])) {
                $result[$filename] = [];
            }

            $result[$filename] = array_merge(
                $result[$filename],
                range($reflector->getStartLine(), $reflector->getEndLine())
            );
        }

        foreach ($result as $filename => $lineNumbers) {
            $result[$filename] = array_keys(array_flip($lineNumbers));
        }

        return $result;
    }

    /**
     * Trims any extensions from version string that follows after
     * the <major>.<minor>[.<patch>] format.
     */
    private static function sanitizeVersionNumber(string $version)
    {
        return preg_replace(
            '/^(\d+\.\d+(?:.\d+)?).*$/',
            '$1',
            $version
        );
    }

    private static function shouldCoversAnnotationBeUsed(array $annotations): bool
    {
        if (isset($annotations['method']['coversNothing'])) {
            return false;
        }

        if (isset($annotations['method']['covers'])) {
            return true;
        }

        if (isset($annotations['class']['coversNothing'])) {
            return false;
        }

        return true;
    }

    /**
     * Merge two arrays together.
     *
     * If an integer key exists in both arrays and preserveNumericKeys is false, the value
     * from the second array will be appended to the first array. If both values are arrays, they
     * are merged together, else the value of the second array overwrites the one of the first array.
     *
     * This implementation is copied from https://github.com/zendframework/zend-stdlib/blob/76b653c5e99b40eccf5966e3122c90615134ae46/src/ArrayUtils.php
     *
     * Zend Framework (http://framework.zend.com/)
     *
     * @see      http://github.com/zendframework/zf2 for the canonical source repository
     *
     * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
     * @license   http://framework.zend.com/license/new-bsd New BSD License
     */
    private static function mergeArraysRecursively(array $a, array $b): array
    {
        foreach ($b as $key => $value) {
            if (array_key_exists($key, $a)) {
                if (is_int($key)) {
                    $a[] = $value;
                } elseif (is_array($value) && is_array($a[$key])) {
                    $a[$key] = self::mergeArraysRecursively($a[$key], $value);
                } else {
                    $a[$key] = $value;
                }
            } else {
                $a[$key] = $value;
            }
        }

        return $a;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function array_keys;
use function array_shift;
use function count;
use function defined;
use function get_defined_constants;
use function get_included_files;
use function in_array;
use function ini_get_all;
use function is_array;
use function is_file;
use function is_scalar;
use function preg_match;
use function serialize;
use function sprintf;
use function strpos;
use function strtr;
use function substr;
use function var_export;
use Closure;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class GlobalState
{
    /**
     * @var string[]
     */
    private const SUPER_GLOBAL_ARRAYS = [
        '_ENV',
        '_POST',
        '_GET',
        '_COOKIE',
        '_SERVER',
        '_FILES',
        '_REQUEST',
    ];

    /**
     * @throws Exception
     */
    public static function getIncludedFilesAsString(): string
    {
        return self::processIncludedFilesAsString(get_included_files());
    }

    /**
     * @param string[] $files
     *
     * @throws Exception
     */
    public static function processIncludedFilesAsString(array $files): string
    {
        $blacklist = new Blacklist;
        $prefix    = false;
        $result    = '';

        if (defined('__PHPUNIT_PHAR__')) {
            $prefix = 'phar://' . __PHPUNIT_PHAR__ . '/';
        }

        // Do not process bootstrap script
        array_shift($files);

        // If bootstrap script was a Composer bin proxy, skip the second entry as well
        if (substr(strtr($files[0], '\\', '/'), -24) === '/phpunit/phpunit/phpunit') {
            array_shift($files);
        }

        for ($i = count($files) - 1; $i >= 0; $i--) {
            $file = $files[$i];

            if (!empty($GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST']) &&
                in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) {
                continue;
            }

            if ($prefix !== false && strpos($file, $prefix) === 0) {
                continue;
            }

            // Skip virtual file system protocols
            if (preg_match('/^(vfs|phpvfs[a-z0-9]+):/', $file)) {
                continue;
            }

            if (!$blacklist->isBlacklisted($file) && is_file($file)) {
                $result = 'require_once \'' . $file . "';\n" . $result;
            }
        }

        return $result;
    }

    public static function getIniSettingsAsString(): string
    {
        $result = '';

        foreach (ini_get_all(null, false) as $key => $value) {
            $result .= sprintf(
                '@ini_set(%s, %s);' . "\n",
                self::exportVariable($key),
                self::exportVariable((string) $value)
            );
        }

        return $result;
    }

    public static function getConstantsAsString(): string
    {
        $constants = get_defined_constants(true);
        $result    = '';

        if (isset($constants['user'])) {
            foreach ($constants['user'] as $name => $value) {
                $result .= sprintf(
                    'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
                    $name,
                    $name,
                    self::exportVariable($value)
                );
            }
        }

        return $result;
    }

    public static function getGlobalsAsString(): string
    {
        $result = '';

        foreach (self::SUPER_GLOBAL_ARRAYS as $superGlobalArray) {
            if (isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray])) {
                foreach (array_keys($GLOBALS[$superGlobalArray]) as $key) {
                    if ($GLOBALS[$superGlobalArray][$key] instanceof Closure) {
                        continue;
                    }

                    $result .= sprintf(
                        '$GLOBALS[\'%s\'][\'%s\'] = %s;' . "\n",
                        $superGlobalArray,
                        $key,
                        self::exportVariable($GLOBALS[$superGlobalArray][$key])
                    );
                }
            }
        }

        $blacklist   = self::SUPER_GLOBAL_ARRAYS;
        $blacklist[] = 'GLOBALS';

        foreach (array_keys($GLOBALS) as $key) {
            if (!$GLOBALS[$key] instanceof Closure && !in_array($key, $blacklist, true)) {
                $result .= sprintf(
                    '$GLOBALS[\'%s\'] = %s;' . "\n",
                    $key,
                    self::exportVariable($GLOBALS[$key])
                );
            }
        }

        return $result;
    }

    private static function exportVariable($variable): string
    {
        if (is_scalar($variable) || $variable === null ||
            (is_array($variable) && self::arrayOnlyContainsScalars($variable))) {
            return var_export($variable, true);
        }

        return 'unserialize(' . var_export(serialize($variable), true) . ')';
    }

    private static function arrayOnlyContainsScalars(array $array): bool
    {
        $result = true;

        foreach ($array as $element) {
            if (is_array($element)) {
                $result = self::arrayOnlyContainsScalars($element);
            } elseif (!is_scalar($element) && $element !== null) {
                $result = false;
            }

            if (!$result) {
                break;
            }
        }

        return $result;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use function array_keys;
use function array_map;
use function array_values;
use function count;
use function explode;
use function implode;
use function min;
use function preg_replace;
use function preg_replace_callback;
use function sprintf;
use function strtr;
use function trim;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Color
{
    /**
     * @var array<string,string>
     */
    private const WHITESPACE_MAP = [
        ' '  => '·',
        "\t" => '⇥',
    ];

    /**
     * @var array<string,string>
     */
    private const WHITESPACE_EOL_MAP = [
        ' '  => '·',
        "\t" => '⇥',
        "\n" => '↵',
        "\r" => '⟵',
    ];

    /**
     * @var array<string,string>
     */
    private static $ansiCodes = [
        'reset'      => '0',
        'bold'       => '1',
        'dim'        => '2',
        'dim-reset'  => '22',
        'underlined' => '4',
        'fg-default' => '39',
        'fg-black'   => '30',
        'fg-red'     => '31',
        'fg-green'   => '32',
        'fg-yellow'  => '33',
        'fg-blue'    => '34',
        'fg-magenta' => '35',
        'fg-cyan'    => '36',
        'fg-white'   => '37',
        'bg-default' => '49',
        'bg-black'   => '40',
        'bg-red'     => '41',
        'bg-green'   => '42',
        'bg-yellow'  => '43',
        'bg-blue'    => '44',
        'bg-magenta' => '45',
        'bg-cyan'    => '46',
        'bg-white'   => '47',
    ];

    public static function colorize(string $color, string $buffer): string
    {
        if (trim($buffer) === '') {
            return $buffer;
        }

        $codes  = array_map('\trim', explode(',', $color));
        $styles = [];

        foreach ($codes as $code) {
            if (isset(self::$ansiCodes[$code])) {
                $styles[] = self::$ansiCodes[$code] ?? '';
            }
        }

        if (empty($styles)) {
            return $buffer;
        }

        return self::optimizeColor(sprintf("\x1b[%sm", implode(';', $styles)) . $buffer . "\x1b[0m");
    }

    public static function colorizePath(string $path, ?string $prevPath = null, bool $colorizeFilename = false): string
    {
        if ($prevPath === null) {
            $prevPath = '';
        }

        $path     = explode(DIRECTORY_SEPARATOR, $path);
        $prevPath = explode(DIRECTORY_SEPARATOR, $prevPath);

        for ($i = 0; $i < min(count($path), count($prevPath)); $i++) {
            if ($path[$i] == $prevPath[$i]) {
                $path[$i] = self::dim($path[$i]);
            }
        }

        if ($colorizeFilename) {
            $last        = count($path) - 1;
            $path[$last] = preg_replace_callback(
                '/([\-_\.]+|phpt$)/',
                static function ($matches)
                {
                    return self::dim($matches[0]);
                },
                $path[$last]
            );
        }

        return self::optimizeColor(implode(self::dim(DIRECTORY_SEPARATOR), $path));
    }

    public static function dim(string $buffer): string
    {
        if (trim($buffer) === '') {
            return $buffer;
        }

        return "\e[2m{$buffer}\e[22m";
    }

    public static function visualizeWhitespace(string $buffer, bool $visualizeEOL = false): string
    {
        $replaceMap = $visualizeEOL ? self::WHITESPACE_EOL_MAP : self::WHITESPACE_MAP;

        return preg_replace_callback('/\s+/', static function ($matches) use ($replaceMap)
        {
            return self::dim(strtr($matches[0], $replaceMap));
        }, $buffer);
    }

    private static function optimizeColor(string $buffer): string
    {
        $patterns = [
            "/\e\\[22m\e\\[2m/"                   => '',
            "/\e\\[([^m]*)m\e\\[([1-9][0-9;]*)m/" => "\e[$1;$2m",
            "/(\e\\[[^m]*m)+(\e\\[0m)/"           => '$2',
        ];

        return preg_replace(array_keys($patterns), array_values($patterns), $buffer);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use function get_class;
use function in_array;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Framework\WarningTestCase;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Util\Printer;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
abstract class ResultPrinter extends Printer implements TestListener
{
    /**
     * @var NamePrettifier
     */
    protected $prettifier;

    /**
     * @var string
     */
    protected $testClass = '';

    /**
     * @var int
     */
    protected $testStatus;

    /**
     * @var array
     */
    protected $tests = [];

    /**
     * @var int
     */
    protected $successful = 0;

    /**
     * @var int
     */
    protected $warned = 0;

    /**
     * @var int
     */
    protected $failed = 0;

    /**
     * @var int
     */
    protected $risky = 0;

    /**
     * @var int
     */
    protected $skipped = 0;

    /**
     * @var int
     */
    protected $incomplete = 0;

    /**
     * @var null|string
     */
    protected $currentTestClassPrettified;

    /**
     * @var null|string
     */
    protected $currentTestMethodPrettified;

    /**
     * @var array
     */
    private $groups;

    /**
     * @var array
     */
    private $excludeGroups;

    /**
     * @param resource $out
     *
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct($out = null, array $groups = [], array $excludeGroups = [])
    {
        parent::__construct($out);

        $this->groups        = $groups;
        $this->excludeGroups = $excludeGroups;

        $this->prettifier = new NamePrettifier;
        $this->startRun();
    }

    /**
     * Flush buffer and close output.
     */
    public function flush(): void
    {
        $this->doEndClass();
        $this->endRun();

        parent::flush();
    }

    /**
     * An error occurred.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_ERROR;
        $this->failed++;
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_WARNING;
        $this->warned++;
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_FAILURE;
        $this->failed++;
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_INCOMPLETE;
        $this->incomplete++;
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_RISKY;
        $this->risky++;
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->testStatus = BaseTestRunner::STATUS_SKIPPED;
        $this->skipped++;
    }

    /**
     * A testsuite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
    }

    /**
     * A testsuite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
    }

    /**
     * A test started.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function startTest(Test $test): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $class = get_class($test);

        if ($this->testClass !== $class) {
            if ($this->testClass !== '') {
                $this->doEndClass();
            }

            $this->currentTestClassPrettified = $this->prettifier->prettifyTestClass($class);
            $this->testClass                  = $class;
            $this->tests                      = [];

            $this->startClass($class);
        }

        if ($test instanceof TestCase) {
            $this->currentTestMethodPrettified = $this->prettifier->prettifyTestCase($test);
        }

        $this->testStatus = BaseTestRunner::STATUS_PASSED;
    }

    /**
     * A test ended.
     */
    public function endTest(Test $test, float $time): void
    {
        if (!$this->isOfInterest($test)) {
            return;
        }

        $this->tests[] = [$this->currentTestMethodPrettified, $this->testStatus];

        $this->currentTestClassPrettified  = null;
        $this->currentTestMethodPrettified = null;
    }

    protected function doEndClass(): void
    {
        foreach ($this->tests as $test) {
            $this->onTest($test[0], $test[1] === BaseTestRunner::STATUS_PASSED);
        }

        $this->endClass($this->testClass);
    }

    /**
     * Handler for 'start run' event.
     */
    protected function startRun(): void
    {
    }

    /**
     * Handler for 'start class' event.
     */
    protected function startClass(string $name): void
    {
    }

    /**
     * Handler for 'on test' event.
     */
    protected function onTest($name, bool $success = true): void
    {
    }

    /**
     * Handler for 'end class' event.
     */
    protected function endClass(string $name): void
    {
    }

    /**
     * Handler for 'end run' event.
     */
    protected function endRun(): void
    {
    }

    private function isOfInterest(Test $test): bool
    {
        if (!$test instanceof TestCase) {
            return false;
        }

        if ($test instanceof WarningTestCase) {
            return false;
        }

        if (!empty($this->groups)) {
            foreach ($test->getGroups() as $group) {
                if (in_array($group, $this->groups, true)) {
                    return true;
                }
            }

            return false;
        }

        if (!empty($this->excludeGroups)) {
            foreach ($test->getGroups() as $group) {
                if (in_array($group, $this->excludeGroups, true)) {
                    return false;
                }
            }

            return true;
        }

        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use function sprintf;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class HtmlResultPrinter extends ResultPrinter
{
    /**
     * @var string
     */
    private const PAGE_HEADER = <<<'EOT'
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Test Documentation</title>
        <style>
            body {
                text-rendering: optimizeLegibility;
                font-variant-ligatures: common-ligatures;
                font-kerning: normal;
                margin-left: 2em;
                background-color: #ffffff;
                color: #000000;
            }

            body > ul > li {
                font-family: Source Serif Pro, PT Sans, Trebuchet MS, Helvetica, Arial;
                font-size: 2em;
            }

            h2 {
                font-family: Tahoma, Helvetica, Arial;
                font-size: 3em;
            }

            ul {
                list-style: none;
                margin-bottom: 1em;
            }
        </style>
    </head>
    <body>
EOT;

    /**
     * @var string
     */
    private const CLASS_HEADER = <<<'EOT'

        <h2 id="%s">%s</h2>
        <ul>

EOT;

    /**
     * @var string
     */
    private const CLASS_FOOTER = <<<'EOT'
        </ul>
EOT;

    /**
     * @var string
     */
    private const PAGE_FOOTER = <<<'EOT'

    </body>
</html>
EOT;

    /**
     * Handler for 'start run' event.
     */
    protected function startRun(): void
    {
        $this->write(self::PAGE_HEADER);
    }

    /**
     * Handler for 'start class' event.
     */
    protected function startClass(string $name): void
    {
        $this->write(
            sprintf(
                self::CLASS_HEADER,
                $name,
                $this->currentTestClassPrettified
            )
        );
    }

    /**
     * Handler for 'on test' event.
     */
    protected function onTest($name, bool $success = true): void
    {
        $this->write(
            sprintf(
                "            <li style=\"color: %s;\">%s %s</li>\n",
                $success ? '#555753' : '#ef2929',
                $success ? '✓' : '❌',
                $name
            )
        );
    }

    /**
     * Handler for 'end class' event.
     */
    protected function endClass(string $name): void
    {
        $this->write(self::CLASS_FOOTER);
    }

    /**
     * Handler for 'end run' event.
     */
    protected function endRun(): void
    {
        $this->write(self::PAGE_FOOTER);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TextResultPrinter extends ResultPrinter
{
    /**
     * Handler for 'start class' event.
     */
    protected function startClass(string $name): void
    {
        $this->write($this->currentTestClassPrettified . "\n");
    }

    /**
     * Handler for 'on test' event.
     */
    protected function onTest($name, bool $success = true): void
    {
        if ($success) {
            $this->write(' [x] ');
        } else {
            $this->write(' [ ] ');
        }

        $this->write($name . "\n");
    }

    /**
     * Handler for 'end class' event.
     */
    protected function endClass(string $name): void
    {
        $this->write("\n");
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use function array_filter;
use function get_class;
use function implode;
use DOMDocument;
use DOMElement;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Printer;
use ReflectionClass;
use ReflectionException;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class XmlResultPrinter extends Printer implements TestListener
{
    /**
     * @var DOMDocument
     */
    private $document;

    /**
     * @var DOMElement
     */
    private $root;

    /**
     * @var NamePrettifier
     */
    private $prettifier;

    /**
     * @var null|Throwable
     */
    private $exception;

    /**
     * @param resource|string $out
     *
     * @throws Exception
     */
    public function __construct($out = null)
    {
        $this->document               = new DOMDocument('1.0', 'UTF-8');
        $this->document->formatOutput = true;

        $this->root = $this->document->createElement('tests');
        $this->document->appendChild($this->root);

        $this->prettifier = new NamePrettifier;

        parent::__construct($out);
    }

    /**
     * Flush buffer and close output.
     */
    public function flush(): void
    {
        $this->write($this->document->saveXML());

        parent::flush();
    }

    /**
     * An error occurred.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        $this->exception = $t;
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        $this->exception = $e;
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
    }

    /**
     * A test suite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
    }

    /**
     * A test suite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
    }

    /**
     * A test started.
     */
    public function startTest(Test $test): void
    {
        $this->exception = null;
    }

    /**
     * A test ended.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function endTest(Test $test, float $time): void
    {
        if (!$test instanceof TestCase) {
            return;
        }

        $groups = array_filter(
            $test->getGroups(),
            static function ($group)
            {
                return !($group === 'small' || $group === 'medium' || $group === 'large');
            }
        );

        $testNode = $this->document->createElement('test');

        $testNode->setAttribute('className', get_class($test));
        $testNode->setAttribute('methodName', $test->getName());
        $testNode->setAttribute('prettifiedClassName', $this->prettifier->prettifyTestClass(get_class($test)));
        $testNode->setAttribute('prettifiedMethodName', $this->prettifier->prettifyTestCase($test));
        $testNode->setAttribute('status', (string) $test->getStatus());
        $testNode->setAttribute('time', (string) $time);
        $testNode->setAttribute('size', (string) $test->getSize());
        $testNode->setAttribute('groups', implode(',', $groups));

        foreach ($groups as $group) {
            $groupNode = $this->document->createElement('group');

            $groupNode->setAttribute('name', $group);

            $testNode->appendChild($groupNode);
        }

        $annotations = $test->getAnnotations();

        foreach (['class', 'method'] as $type) {
            foreach ($annotations[$type] as $annotation => $values) {
                if ($annotation !== 'covers' && $annotation !== 'uses') {
                    continue;
                }

                foreach ($values as $value) {
                    $coversNode = $this->document->createElement($annotation);

                    $coversNode->setAttribute('target', $value);

                    $testNode->appendChild($coversNode);
                }
            }
        }

        foreach ($test->doubledTypes() as $doubledType) {
            $testDoubleNode = $this->document->createElement('testDouble');

            $testDoubleNode->setAttribute('type', $doubledType);

            $testNode->appendChild($testDoubleNode);
        }

        $inlineAnnotations = \PHPUnit\Util\Test::getInlineAnnotations(get_class($test), $test->getName(false));

        if (isset($inlineAnnotations['given'], $inlineAnnotations['when'], $inlineAnnotations['then'])) {
            $testNode->setAttribute('given', $inlineAnnotations['given']['value']);
            $testNode->setAttribute('givenStartLine', (string) $inlineAnnotations['given']['line']);
            $testNode->setAttribute('when', $inlineAnnotations['when']['value']);
            $testNode->setAttribute('whenStartLine', (string) $inlineAnnotations['when']['line']);
            $testNode->setAttribute('then', $inlineAnnotations['then']['value']);
            $testNode->setAttribute('thenStartLine', (string) $inlineAnnotations['then']['line']);
        }

        if ($this->exception !== null) {
            if ($this->exception instanceof Exception) {
                $steps = $this->exception->getSerializableTrace();
            } else {
                $steps = $this->exception->getTrace();
            }

            try {
                $file = (new ReflectionClass($test))->getFileName();
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            foreach ($steps as $step) {
                if (isset($step['file']) && $step['file'] === $file) {
                    $testNode->setAttribute('exceptionLine', (string) $step['line']);

                    break;
                }
            }

            $testNode->setAttribute('exceptionMessage', $this->exception->getMessage());
        }

        $this->root->appendChild($testNode);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use const PHP_EOL;
use function array_map;
use function ceil;
use function count;
use function explode;
use function get_class;
use function implode;
use function preg_match;
use function sprintf;
use function strlen;
use function strpos;
use function trim;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestResult;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\Color;
use SebastianBergmann\Timer\Timer;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class CliTestDoxPrinter extends TestDoxPrinter
{
    /**
     * The default Testdox left margin for messages is a vertical line.
     */
    private const PREFIX_SIMPLE = [
        'default' => '│',
        'start'   => '│',
        'message' => '│',
        'diff'    => '│',
        'trace'   => '│',
        'last'    => '│',
    ];

    /**
     * Colored Testdox use box-drawing for a more textured map of the message.
     */
    private const PREFIX_DECORATED = [
        'default' => '│',
        'start'   => '┐',
        'message' => '├',
        'diff'    => '┊',
        'trace'   => '╵',
        'last'    => '┴',
    ];

    private const SPINNER_ICONS = [
        " \e[36m◐\e[0m running tests",
        " \e[36m◓\e[0m running tests",
        " \e[36m◑\e[0m running tests",
        " \e[36m◒\e[0m running tests",
    ];

    private const STATUS_STYLES = [
        BaseTestRunner::STATUS_PASSED     => [
            'symbol' => '✔',
            'color'  => 'fg-green',
        ],
        BaseTestRunner::STATUS_ERROR      => [
            'symbol'  => '✘',
            'color'   => 'fg-yellow',
            'message' => 'bg-yellow,fg-black',
        ],
        BaseTestRunner::STATUS_FAILURE    => [
            'symbol'  => '✘',
            'color'   => 'fg-red',
            'message' => 'bg-red,fg-white',
        ],
        BaseTestRunner::STATUS_SKIPPED    => [
            'symbol'  => '↩',
            'color'   => 'fg-cyan',
            'message' => 'fg-cyan',
        ],
        BaseTestRunner::STATUS_RISKY      => [
            'symbol'  => '☢',
            'color'   => 'fg-yellow',
            'message' => 'fg-yellow',
        ],
        BaseTestRunner::STATUS_INCOMPLETE => [
            'symbol'  => '∅',
            'color'   => 'fg-yellow',
            'message' => 'fg-yellow',
        ],
        BaseTestRunner::STATUS_WARNING    => [
            'symbol'  => '⚠',
            'color'   => 'fg-yellow',
            'message' => 'fg-yellow',
        ],
        BaseTestRunner::STATUS_UNKNOWN    => [
            'symbol'  => '?',
            'color'   => 'fg-blue',
            'message' => 'fg-white,bg-blue',
        ],
    ];

    /**
     * @var int[]
     */
    private $nonSuccessfulTestResults = [];

    /**
     * @throws \SebastianBergmann\Timer\RuntimeException
     */
    public function printResult(TestResult $result): void
    {
        $this->printHeader($result);

        $this->printNonSuccessfulTestsSummary($result->count());

        $this->printFooter($result);
    }

    /**
     * @throws \SebastianBergmann\Timer\RuntimeException
     */
    protected function printHeader(TestResult $result): void
    {
        $this->write("\n" . Timer::resourceUsage() . "\n\n");
    }

    protected function formatClassName(Test $test): string
    {
        if ($test instanceof TestCase) {
            return $this->prettifier->prettifyTestClass(get_class($test));
        }

        return get_class($test);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function registerTestResult(Test $test, ?Throwable $t, int $status, float $time, bool $verbose): void
    {
        if ($status !== BaseTestRunner::STATUS_PASSED) {
            $this->nonSuccessfulTestResults[] = $this->testIndex;
        }

        parent::registerTestResult($test, $t, $status, $time, $verbose);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function formatTestName(Test $test): string
    {
        if ($test instanceof TestCase) {
            return $this->prettifier->prettifyTestCase($test);
        }

        return parent::formatTestName($test);
    }

    protected function writeTestResult(array $prevResult, array $result): void
    {
        // spacer line for new suite headers and after verbose messages
        if ($prevResult['testName'] !== '' &&
            (!empty($prevResult['message']) || $prevResult['className'] !== $result['className'])) {
            $this->write(PHP_EOL);
        }

        // suite header
        if ($prevResult['className'] !== $result['className']) {
            $this->write($this->colorizeTextBox('underlined', $result['className']) . PHP_EOL);
        }

        // test result line
        if ($this->colors && $result['className'] === PhptTestCase::class) {
            $testName = Color::colorizePath($result['testName'], $prevResult['testName'], true);
        } else {
            $testName = $result['testMethod'];
        }

        $style = self::STATUS_STYLES[$result['status']];
        $line  = sprintf(
            ' %s %s%s' . PHP_EOL,
            $this->colorizeTextBox($style['color'], $style['symbol']),
            $testName,
            $this->verbose ? ' ' . $this->formatRuntime($result['time'], $style['color']) : ''
        );

        $this->write($line);

        // additional information when verbose
        $this->write($result['message']);
    }

    protected function formatThrowable(Throwable $t, ?int $status = null): string
    {
        return trim(\PHPUnit\Framework\TestFailure::exceptionToString($t));
    }

    protected function colorizeMessageAndDiff(string $style, string $buffer): array
    {
        $lines      = $buffer ? array_map('\rtrim', explode(PHP_EOL, $buffer)) : [];
        $message    = [];
        $diff       = [];
        $insideDiff = false;

        foreach ($lines as $line) {
            if ($line === '--- Expected') {
                $insideDiff = true;
            }

            if (!$insideDiff) {
                $message[] = $line;
            } else {
                if (strpos($line, '-') === 0) {
                    $line = Color::colorize('fg-red', Color::visualizeWhitespace($line, true));
                } elseif (strpos($line, '+') === 0) {
                    $line = Color::colorize('fg-green', Color::visualizeWhitespace($line, true));
                } elseif ($line === '@@ @@') {
                    $line = Color::colorize('fg-cyan', $line);
                }
                $diff[] = $line;
            }
        }
        $diff = implode(PHP_EOL, $diff);

        if (!empty($message)) {
            $message = $this->colorizeTextBox($style, implode(PHP_EOL, $message));
        }

        return [$message, $diff];
    }

    protected function formatStacktrace(Throwable $t): string
    {
        $trace = \PHPUnit\Util\Filter::getFilteredStacktrace($t);

        if (!$this->colors) {
            return $trace;
        }

        $lines    = [];
        $prevPath = '';

        foreach (explode(PHP_EOL, $trace) as $line) {
            if (preg_match('/^(.*):(\d+)$/', $line, $matches)) {
                $lines[] = Color::colorizePath($matches[1], $prevPath) .
                    Color::dim(':') .
                    Color::colorize('fg-blue', $matches[2]) .
                    "\n";
                $prevPath = $matches[1];
            } else {
                $lines[]  = $line;
                $prevPath = '';
            }
        }

        return implode('', $lines);
    }

    protected function formatTestResultMessage(Throwable $t, array $result, ?string $prefix = null): string
    {
        $message = $this->formatThrowable($t, $result['status']);
        $diff    = '';

        if (!($this->verbose || $result['verbose'])) {
            return '';
        }

        if ($message && $this->colors) {
            $style            = self::STATUS_STYLES[$result['status']]['message'] ?? '';
            [$message, $diff] = $this->colorizeMessageAndDiff($style, $message);
        }

        if ($prefix === null || !$this->colors) {
            $prefix = self::PREFIX_SIMPLE;
        }

        if ($this->colors) {
            $color  = self::STATUS_STYLES[$result['status']]['color'] ?? '';
            $prefix = array_map(static function ($p) use ($color)
            {
                return Color::colorize($color, $p);
            }, self::PREFIX_DECORATED);
        }

        $trace = $this->formatStacktrace($t);
        $out   = $this->prefixLines($prefix['start'], PHP_EOL) . PHP_EOL;

        if ($message) {
            $out .= $this->prefixLines($prefix['message'], $message . PHP_EOL) . PHP_EOL;
        }

        if ($diff) {
            $out .= $this->prefixLines($prefix['diff'], $diff . PHP_EOL) . PHP_EOL;
        }

        if ($trace) {
            if ($message || $diff) {
                $out .= $this->prefixLines($prefix['default'], PHP_EOL) . PHP_EOL;
            }
            $out .= $this->prefixLines($prefix['trace'], $trace . PHP_EOL) . PHP_EOL;
        }
        $out .= $this->prefixLines($prefix['last'], PHP_EOL) . PHP_EOL;

        return $out;
    }

    protected function drawSpinner(): void
    {
        if ($this->colors) {
            $id = $this->spinState % count(self::SPINNER_ICONS);
            $this->write(self::SPINNER_ICONS[$id]);
        }
    }

    protected function undrawSpinner(): void
    {
        if ($this->colors) {
            $id = $this->spinState % count(self::SPINNER_ICONS);
            $this->write("\e[1K\e[" . strlen(self::SPINNER_ICONS[$id]) . 'D');
        }
    }

    private function formatRuntime(float $time, string $color = ''): string
    {
        if (!$this->colors) {
            return sprintf('[%.2f ms]', $time * 1000);
        }

        if ($time > 1) {
            $color = 'fg-magenta';
        }

        return Color::colorize($color, ' ' . (int) ceil($time * 1000) . ' ' . Color::dim('ms'));
    }

    private function printNonSuccessfulTestsSummary(int $numberOfExecutedTests): void
    {
        if (empty($this->nonSuccessfulTestResults)) {
            return;
        }

        if ((count($this->nonSuccessfulTestResults) / $numberOfExecutedTests) >= 0.7) {
            return;
        }

        $this->write("Summary of non-successful tests:\n\n");

        $prevResult = $this->getEmptyTestResult();

        foreach ($this->nonSuccessfulTestResults as $testIndex) {
            $result = $this->testResults[$testIndex];
            $this->writeTestResult($prevResult, $result);
            $prevResult = $result;
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use function array_key_exists;
use function array_keys;
use function array_map;
use function array_pop;
use function array_values;
use function explode;
use function get_class;
use function gettype;
use function implode;
use function in_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_numeric;
use function is_object;
use function is_scalar;
use function is_string;
use function ord;
use function preg_quote;
use function preg_replace;
use function range;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function strtoupper;
use function substr;
use function trim;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Color;
use PHPUnit\Util\Exception as UtilException;
use PHPUnit\Util\Test;
use ReflectionException;
use ReflectionMethod;
use ReflectionObject;
use SebastianBergmann\Exporter\Exporter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class NamePrettifier
{
    /**
     * @var string[]
     */
    private $strings = [];

    /**
     * @var bool
     */
    private $useColor;

    public function __construct($useColor = false)
    {
        $this->useColor = $useColor;
    }

    /**
     * Prettifies the name of a test class.
     *
     * @psalm-param class-string $className
     */
    public function prettifyTestClass(string $className): string
    {
        try {
            $annotations = Test::parseTestMethodAnnotations($className);

            if (isset($annotations['class']['testdox'][0])) {
                return $annotations['class']['testdox'][0];
            }
        } catch (UtilException $e) {
            // ignore, determine className by parsing the provided name
        }

        $parts     = explode('\\', $className);
        $className = array_pop($parts);

        if (substr($className, -1 * strlen('Test')) === 'Test') {
            $className = substr($className, 0, strlen($className) - strlen('Test'));
        }

        if (strpos($className, 'Tests') === 0) {
            $className = substr($className, strlen('Tests'));
        } elseif (strpos($className, 'Test') === 0) {
            $className = substr($className, strlen('Test'));
        }

        if (empty($className)) {
            $className = 'UnnamedTests';
        }

        if (!empty($parts)) {
            $parts[]            = $className;
            $fullyQualifiedName = implode('\\', $parts);
        } else {
            $fullyQualifiedName = $className;
        }

        $result = preg_replace('/(?<=[[:lower:]])(?=[[:upper:]])/u', ' ', $className);

        if ($fullyQualifiedName !== $className) {
            return $result . ' (' . $fullyQualifiedName . ')';
        }

        return $result;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function prettifyTestCase(TestCase $test): string
    {
        $annotations                = $test->getAnnotations();
        $annotationWithPlaceholders = false;

        $callback = static function (string $variable): string
        {
            return sprintf('/%s(?=\b)/', preg_quote($variable, '/'));
        };

        if (isset($annotations['method']['testdox'][0])) {
            $result = $annotations['method']['testdox'][0];

            if (strpos($result, '$') !== false) {
                $annotation   = $annotations['method']['testdox'][0];
                $providedData = $this->mapTestMethodParameterNamesToProvidedDataValues($test);
                $variables    = array_map($callback, array_keys($providedData));

                $result = trim(preg_replace($variables, $providedData, $annotation));

                $annotationWithPlaceholders = true;
            }
        } else {
            $result = $this->prettifyTestMethod($test->getName(false));
        }

        if (!$annotationWithPlaceholders && $test->usesDataProvider()) {
            $result .= $this->prettifyDataSet($test);
        }

        return $result;
    }

    public function prettifyDataSet(TestCase $test): string
    {
        if (!$this->useColor) {
            return $test->getDataSetAsString(false);
        }

        if (is_int($test->dataName())) {
            $data = Color::dim(' with data set ') . Color::colorize('fg-cyan', (string) $test->dataName());
        } else {
            $data = Color::dim(' with ') . Color::colorize('fg-cyan', Color::visualizeWhitespace((string) $test->dataName()));
        }

        return $data;
    }

    /**
     * Prettifies the name of a test method.
     */
    public function prettifyTestMethod(string $name): string
    {
        $buffer = '';

        if ($name === '') {
            return $buffer;
        }

        $string = (string) preg_replace('#\d+$#', '', $name, -1, $count);

        if (in_array($string, $this->strings, true)) {
            $name = $string;
        } elseif ($count === 0) {
            $this->strings[] = $string;
        }

        if (strpos($name, 'test_') === 0) {
            $name = substr($name, 5);
        } elseif (strpos($name, 'test') === 0) {
            $name = substr($name, 4);
        }

        if ($name === '') {
            return $buffer;
        }

        $name[0] = strtoupper($name[0]);

        if (strpos($name, '_') !== false) {
            return trim(str_replace('_', ' ', $name));
        }

        $wasNumeric = false;

        foreach (range(0, strlen($name) - 1) as $i) {
            if ($i > 0 && ord($name[$i]) >= 65 && ord($name[$i]) <= 90) {
                $buffer .= ' ' . strtolower($name[$i]);
            } else {
                $isNumeric = is_numeric($name[$i]);

                if (!$wasNumeric && $isNumeric) {
                    $buffer .= ' ';
                    $wasNumeric = true;
                }

                if ($wasNumeric && !$isNumeric) {
                    $wasNumeric = false;
                }

                $buffer .= $name[$i];
            }
        }

        return $buffer;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test): array
    {
        try {
            $reflector = new ReflectionMethod(get_class($test), $test->getName(false));
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new UtilException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $providedData       = [];
        $providedDataValues = array_values($test->getProvidedData());
        $i                  = 0;

        $providedData['$_dataName'] = $test->dataName();

        foreach ($reflector->getParameters() as $parameter) {
            if (!array_key_exists($i, $providedDataValues) && $parameter->isDefaultValueAvailable()) {
                try {
                    $providedDataValues[$i] = $parameter->getDefaultValue();
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new UtilException(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd
            }

            $value = $providedDataValues[$i++] ?? null;

            if (is_object($value)) {
                $reflector = new ReflectionObject($value);

                if ($reflector->hasMethod('__toString')) {
                    $value = (string) $value;
                } else {
                    $value = get_class($value);
                }
            }

            if (!is_scalar($value)) {
                $value = gettype($value);
            }

            if (is_bool($value) || is_int($value) || is_float($value)) {
                $value = (new Exporter)->export($value);
            }

            if (is_string($value) && $value === '') {
                if ($this->useColor) {
                    $value = Color::colorize('dim,underlined', 'empty');
                } else {
                    $value = "''";
                }
            }

            $providedData['$' . $parameter->getName()] = $value;
        }

        if ($this->useColor) {
            $providedData = array_map(static function ($value)
            {
                return Color::colorize('fg-cyan', Color::visualizeWhitespace((string) $value, true));
            }, $providedData);
        }

        return $providedData;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\TestDox;

use const PHP_EOL;
use function array_map;
use function get_class;
use function implode;
use function preg_split;
use function trim;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Runner\TestSuiteSorter;
use PHPUnit\TextUI\ResultPrinter;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class TestDoxPrinter extends ResultPrinter
{
    /**
     * @var NamePrettifier
     */
    protected $prettifier;

    /**
     * @var int The number of test results received from the TestRunner
     */
    protected $testIndex = 0;

    /**
     * @var int The number of test results already sent to the output
     */
    protected $testFlushIndex = 0;

    /**
     * @var array<int, array> Buffer for test results
     */
    protected $testResults = [];

    /**
     * @var array<string, int> Lookup table for testname to testResults[index]
     */
    protected $testNameResultIndex = [];

    /**
     * @var bool
     */
    protected $enableOutputBuffer = false;

    /**
     * @var array array<string>
     */
    protected $originalExecutionOrder = [];

    /**
     * @var int
     */
    protected $spinState = 0;

    /**
     * @var bool
     */
    protected $showProgress = true;

    /**
     * @param null|resource|string $out
     *
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct($out = null, bool $verbose = false, string $colors = self::COLOR_DEFAULT, bool $debug = false, $numberOfColumns = 80, bool $reverse = false)
    {
        parent::__construct($out, $verbose, $colors, $debug, $numberOfColumns, $reverse);

        $this->prettifier = new NamePrettifier($this->colors);
    }

    public function setOriginalExecutionOrder(array $order): void
    {
        $this->originalExecutionOrder = $order;
        $this->enableOutputBuffer     = !empty($order);
    }

    public function setShowProgressAnimation(bool $showProgress): void
    {
        $this->showProgress = $showProgress;
    }

    public function printResult(TestResult $result): void
    {
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function endTest(Test $test, float $time): void
    {
        if (!$test instanceof TestCase && !$test instanceof PhptTestCase && !$test instanceof TestSuite) {
            return;
        }

        if ($this->testHasPassed()) {
            $this->registerTestResult($test, null, BaseTestRunner::STATUS_PASSED, $time, false);
        }

        if ($test instanceof TestCase || $test instanceof PhptTestCase) {
            $this->testIndex++;
        }

        parent::endTest($test, $time);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        $this->registerTestResult($test, $t, BaseTestRunner::STATUS_ERROR, $time, true);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        $this->registerTestResult($test, $e, BaseTestRunner::STATUS_WARNING, $time, true);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        $this->registerTestResult($test, $e, BaseTestRunner::STATUS_FAILURE, $time, true);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        $this->registerTestResult($test, $t, BaseTestRunner::STATUS_INCOMPLETE, $time, false);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        $this->registerTestResult($test, $t, BaseTestRunner::STATUS_RISKY, $time, false);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        $this->registerTestResult($test, $t, BaseTestRunner::STATUS_SKIPPED, $time, false);
    }

    public function writeProgress(string $progress): void
    {
        $this->flushOutputBuffer();
    }

    public function flush(): void
    {
        $this->flushOutputBuffer(true);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function registerTestResult(Test $test, ?Throwable $t, int $status, float $time, bool $verbose): void
    {
        $testName = TestSuiteSorter::getTestSorterUID($test);

        $result = [
            'className'  => $this->formatClassName($test),
            'testName'   => $testName,
            'testMethod' => $this->formatTestName($test),
            'message'    => '',
            'status'     => $status,
            'time'       => $time,
            'verbose'    => $verbose,
        ];

        if ($t !== null) {
            $result['message'] = $this->formatTestResultMessage($t, $result);
        }

        $this->testResults[$this->testIndex]  = $result;
        $this->testNameResultIndex[$testName] = $this->testIndex;
    }

    protected function formatTestName(Test $test): string
    {
        return $test->getName();
    }

    protected function formatClassName(Test $test): string
    {
        return get_class($test);
    }

    protected function testHasPassed(): bool
    {
        if (!isset($this->testResults[$this->testIndex]['status'])) {
            return true;
        }

        if ($this->testResults[$this->testIndex]['status'] === BaseTestRunner::STATUS_PASSED) {
            return true;
        }

        return false;
    }

    protected function flushOutputBuffer(bool $forceFlush = false): void
    {
        if ($this->testFlushIndex === $this->testIndex) {
            return;
        }

        if ($this->testFlushIndex > 0) {
            if ($this->enableOutputBuffer) {
                $prevResult = $this->getTestResultByName($this->originalExecutionOrder[$this->testFlushIndex - 1]);
            } else {
                $prevResult = $this->testResults[$this->testFlushIndex - 1];
            }
        } else {
            $prevResult = $this->getEmptyTestResult();
        }

        if (!$this->enableOutputBuffer) {
            $this->writeTestResult($prevResult, $this->testResults[$this->testFlushIndex++]);
        } else {
            do {
                $flushed = false;

                if (!$forceFlush && isset($this->originalExecutionOrder[$this->testFlushIndex])) {
                    $result = $this->getTestResultByName($this->originalExecutionOrder[$this->testFlushIndex]);
                } else {
                    // This test(name) cannot found in original execution order,
                    // flush result to output stream right away
                    $result = $this->testResults[$this->testFlushIndex];
                }

                if (!empty($result)) {
                    $this->hideSpinner();
                    $this->writeTestResult($prevResult, $result);
                    $this->testFlushIndex++;
                    $prevResult = $result;
                    $flushed    = true;
                } else {
                    $this->showSpinner();
                }
            } while ($flushed && $this->testFlushIndex < $this->testIndex);
        }
    }

    protected function showSpinner(): void
    {
        if (!$this->showProgress) {
            return;
        }

        if ($this->spinState) {
            $this->undrawSpinner();
        }

        $this->spinState++;
        $this->drawSpinner();
    }

    protected function hideSpinner(): void
    {
        if (!$this->showProgress) {
            return;
        }

        if ($this->spinState) {
            $this->undrawSpinner();
        }

        $this->spinState = 0;
    }

    protected function drawSpinner(): void
    {
        // optional for CLI printers: show the user a 'buffering output' spinner
    }

    protected function undrawSpinner(): void
    {
        // remove the spinner from the current line
    }

    protected function writeTestResult(array $prevResult, array $result): void
    {
    }

    protected function getEmptyTestResult(): array
    {
        return [
            'className' => '',
            'testName'  => '',
            'message'   => '',
            'failed'    => '',
            'verbose'   => '',
        ];
    }

    protected function getTestResultByName(?string $testName): array
    {
        if (isset($this->testNameResultIndex[$testName])) {
            return $this->testResults[$this->testNameResultIndex[$testName]];
        }

        return [];
    }

    protected function formatThrowable(Throwable $t, ?int $status = null): string
    {
        $message = trim(\PHPUnit\Framework\TestFailure::exceptionToString($t));

        if ($message) {
            $message .= PHP_EOL . PHP_EOL . $this->formatStacktrace($t);
        } else {
            $message = $this->formatStacktrace($t);
        }

        return $message;
    }

    protected function formatStacktrace(Throwable $t): string
    {
        return \PHPUnit\Util\Filter::getFilteredStacktrace($t);
    }

    protected function formatTestResultMessage(Throwable $t, array $result, string $prefix = '│'): string
    {
        $message = $this->formatThrowable($t, $result['status']);

        if ($message === '') {
            return '';
        }

        if (!($this->verbose || $result['verbose'])) {
            return '';
        }

        return $this->prefixLines($prefix, $message);
    }

    protected function prefixLines(string $prefix, string $message): string
    {
        $message = trim($message);

        return implode(
            PHP_EOL,
            array_map(
                static function (string $text) use ($prefix)
                {
                    return '   ' . $prefix . ($text ? ' ' . $text : '');
                },
                preg_split('/\r\n|\r|\n/', $message)
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function array_unshift;
use function defined;
use function in_array;
use function is_file;
use function realpath;
use function sprintf;
use function strpos;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\SyntheticError;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Filter
{
    /**
     * @throws Exception
     */
    public static function getFilteredStacktrace(Throwable $t): string
    {
        $filteredStacktrace = '';

        if ($t instanceof SyntheticError) {
            $eTrace = $t->getSyntheticTrace();
            $eFile  = $t->getSyntheticFile();
            $eLine  = $t->getSyntheticLine();
        } elseif ($t instanceof Exception) {
            $eTrace = $t->getSerializableTrace();
            $eFile  = $t->getFile();
            $eLine  = $t->getLine();
        } else {
            if ($t->getPrevious()) {
                $t = $t->getPrevious();
            }

            $eTrace = $t->getTrace();
            $eFile  = $t->getFile();
            $eLine  = $t->getLine();
        }

        if (!self::frameExists($eTrace, $eFile, $eLine)) {
            array_unshift(
                $eTrace,
                ['file' => $eFile, 'line' => $eLine]
            );
        }

        $prefix    = defined('__PHPUNIT_PHAR_ROOT__') ? __PHPUNIT_PHAR_ROOT__ : false;
        $blacklist = new Blacklist;

        foreach ($eTrace as $frame) {
            if (self::shouldPrintFrame($frame, $prefix, $blacklist)) {
                $filteredStacktrace .= sprintf(
                    "%s:%s\n",
                    $frame['file'],
                    $frame['line'] ?? '?'
                );
            }
        }

        return $filteredStacktrace;
    }

    private static function shouldPrintFrame($frame, $prefix, Blacklist $blacklist): bool
    {
        if (!isset($frame['file'])) {
            return false;
        }

        $file              = $frame['file'];
        $fileIsNotPrefixed = $prefix === false || strpos($file, $prefix) !== 0;

        // @see https://github.com/sebastianbergmann/phpunit/issues/4033
        if (isset($GLOBALS['_SERVER']['SCRIPT_NAME'])) {
            $script = realpath($GLOBALS['_SERVER']['SCRIPT_NAME']);
        } else {
            $script = '';
        }

        return is_file($file) &&
               self::fileIsBlacklisted($file, $blacklist) &&
               $fileIsNotPrefixed &&
               $file !== $script;
    }

    private static function fileIsBlacklisted($file, Blacklist $blacklist): bool
    {
        return (empty($GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST']) ||
                !in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) &&
               !$blacklist->isBlacklisted($file);
    }

    private static function frameExists(array $trace, string $file, int $line): bool
    {
        foreach ($trace as $frame) {
            if (isset($frame['file'], $frame['line']) && $frame['file'] === $file && $frame['line'] === $line) {
                return true;
            }
        }

        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function get_class;
use function implode;
use function str_replace;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\PhptTestCase;
use RecursiveIteratorIterator;
use XMLWriter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class XmlTestListRenderer
{
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function render(TestSuite $suite): string
    {
        $writer = new XMLWriter;

        $writer->openMemory();
        $writer->setIndent(true);
        $writer->startDocument('1.0', 'UTF-8');
        $writer->startElement('tests');

        $currentTestCase = null;

        foreach (new RecursiveIteratorIterator($suite->getIterator()) as $test) {
            if ($test instanceof TestCase) {
                if (get_class($test) !== $currentTestCase) {
                    if ($currentTestCase !== null) {
                        $writer->endElement();
                    }

                    $writer->startElement('testCaseClass');
                    $writer->writeAttribute('name', get_class($test));

                    $currentTestCase = get_class($test);
                }

                $writer->startElement('testCaseMethod');
                $writer->writeAttribute('name', $test->getName(false));
                $writer->writeAttribute('groups', implode(',', $test->getGroups()));

                if (!empty($test->getDataSetAsString(false))) {
                    $writer->writeAttribute(
                        'dataSet',
                        str_replace(
                            ' with data set ',
                            '',
                            $test->getDataSetAsString(false)
                        )
                    );
                }

                $writer->endElement();
            } elseif ($test instanceof PhptTestCase) {
                if ($currentTestCase !== null) {
                    $writer->endElement();

                    $currentTestCase = null;
                }

                $writer->startElement('phptFile');
                $writer->writeAttribute('path', $test->getName());
                $writer->endElement();
            }
        }

        if ($currentTestCase !== null) {
            $writer->endElement();
        }

        $writer->endElement();
        $writer->endDocument();

        return $writer->outputMemory();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use RuntimeException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvalidDataSetException extends RuntimeException implements \PHPUnit\Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Log;

use function class_exists;
use function count;
use function explode;
use function get_class;
use function getmypid;
use function ini_get;
use function is_bool;
use function is_scalar;
use function method_exists;
use function print_r;
use function round;
use function str_replace;
use function stripos;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\TextUI\ResultPrinter;
use PHPUnit\Util\Exception;
use PHPUnit\Util\Filter;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\Comparator\ComparisonFailure;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TeamCity extends ResultPrinter
{
    /**
     * @var bool
     */
    private $isSummaryTestCountPrinted = false;

    /**
     * @var string
     */
    private $startedTestName;

    /**
     * @var false|int
     */
    private $flowId;

    /**
     * @throws \SebastianBergmann\Timer\RuntimeException
     */
    public function printResult(TestResult $result): void
    {
        $this->printHeader($result);
        $this->printFooter($result);
    }

    /**
     * An error occurred.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        $this->printEvent(
            'testFailed',
            [
                'name'     => $test->getName(),
                'message'  => self::getMessage($t),
                'details'  => self::getDetails($t),
                'duration' => self::toMilliseconds($time),
            ]
        );
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        $this->write(self::getMessage($e) . PHP_EOL);
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        $parameters = [
            'name'     => $test->getName(),
            'message'  => self::getMessage($e),
            'details'  => self::getDetails($e),
            'duration' => self::toMilliseconds($time),
        ];

        if ($e instanceof ExpectationFailedException) {
            $comparisonFailure = $e->getComparisonFailure();

            if ($comparisonFailure instanceof ComparisonFailure) {
                $expectedString = $comparisonFailure->getExpectedAsString();

                if ($expectedString === null || empty($expectedString)) {
                    $expectedString = self::getPrimitiveValueAsString($comparisonFailure->getExpected());
                }

                $actualString = $comparisonFailure->getActualAsString();

                if ($actualString === null || empty($actualString)) {
                    $actualString = self::getPrimitiveValueAsString($comparisonFailure->getActual());
                }

                if ($actualString !== null && $expectedString !== null) {
                    $parameters['type']     = 'comparisonFailure';
                    $parameters['actual']   = $actualString;
                    $parameters['expected'] = $expectedString;
                }
            }
        }

        $this->printEvent('testFailed', $parameters);
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        $this->printIgnoredTest($test->getName(), $t, $time);
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        $this->addError($test, $t, $time);
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        $testName = $test->getName();

        if ($this->startedTestName !== $testName) {
            $this->startTest($test);
            $this->printIgnoredTest($testName, $t, $time);
            $this->endTest($test, $time);
        } else {
            $this->printIgnoredTest($testName, $t, $time);
        }
    }

    public function printIgnoredTest($testName, Throwable $t, float $time): void
    {
        $this->printEvent(
            'testIgnored',
            [
                'name'     => $testName,
                'message'  => self::getMessage($t),
                'details'  => self::getDetails($t),
                'duration' => self::toMilliseconds($time),
            ]
        );
    }

    /**
     * A testsuite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
        if (stripos(ini_get('disable_functions'), 'getmypid') === false) {
            $this->flowId = getmypid();
        } else {
            $this->flowId = false;
        }

        if (!$this->isSummaryTestCountPrinted) {
            $this->isSummaryTestCountPrinted = true;

            $this->printEvent(
                'testCount',
                ['count' => count($suite)]
            );
        }

        $suiteName = $suite->getName();

        if (empty($suiteName)) {
            return;
        }

        $parameters = ['name' => $suiteName];

        if (class_exists($suiteName, false)) {
            $fileName                   = self::getFileName($suiteName);
            $parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}";
        } else {
            $split = explode('::', $suiteName);

            if (count($split) === 2 && class_exists($split[0]) && method_exists($split[0], $split[1])) {
                $fileName                   = self::getFileName($split[0]);
                $parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}";
                $parameters['name']         = $split[1];
            }
        }

        $this->printEvent('testSuiteStarted', $parameters);
    }

    /**
     * A testsuite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
        $suiteName = $suite->getName();

        if (empty($suiteName)) {
            return;
        }

        $parameters = ['name' => $suiteName];

        if (!class_exists($suiteName, false)) {
            $split = explode('::', $suiteName);

            if (count($split) === 2 && class_exists($split[0]) && method_exists($split[0], $split[1])) {
                $parameters['name'] = $split[1];
            }
        }

        $this->printEvent('testSuiteFinished', $parameters);
    }

    /**
     * A test started.
     */
    public function startTest(Test $test): void
    {
        $testName              = $test->getName();
        $this->startedTestName = $testName;
        $params                = ['name' => $testName];

        if ($test instanceof TestCase) {
            $className              = get_class($test);
            $fileName               = self::getFileName($className);
            $params['locationHint'] = "php_qn://{$fileName}::\\{$className}::{$testName}";
        }

        $this->printEvent('testStarted', $params);
    }

    /**
     * A test ended.
     */
    public function endTest(Test $test, float $time): void
    {
        parent::endTest($test, $time);

        $this->printEvent(
            'testFinished',
            [
                'name'     => $test->getName(),
                'duration' => self::toMilliseconds($time),
            ]
        );
    }

    protected function writeProgress(string $progress): void
    {
    }

    private function printEvent(string $eventName, array $params = []): void
    {
        $this->write("\n##teamcity[{$eventName}");

        if ($this->flowId) {
            $params['flowId'] = $this->flowId;
        }

        foreach ($params as $key => $value) {
            $escapedValue = self::escapeValue((string) $value);
            $this->write(" {$key}='{$escapedValue}'");
        }

        $this->write("]\n");
    }

    private static function getMessage(Throwable $t): string
    {
        $message = '';

        if ($t instanceof ExceptionWrapper) {
            if ($t->getClassName() !== '') {
                $message .= $t->getClassName();
            }

            if ($message !== '' && $t->getMessage() !== '') {
                $message .= ' : ';
            }
        }

        return $message . $t->getMessage();
    }

    private static function getDetails(Throwable $t): string
    {
        $stackTrace = Filter::getFilteredStacktrace($t);
        $previous   = $t instanceof ExceptionWrapper ? $t->getPreviousWrapped() : $t->getPrevious();

        while ($previous) {
            $stackTrace .= "\nCaused by\n" .
                TestFailure::exceptionToString($previous) . "\n" .
                Filter::getFilteredStacktrace($previous);

            $previous = $previous instanceof ExceptionWrapper ?
                $previous->getPreviousWrapped() : $previous->getPrevious();
        }

        return ' ' . str_replace("\n", "\n ", $stackTrace);
    }

    private static function getPrimitiveValueAsString($value): ?string
    {
        if ($value === null) {
            return 'null';
        }

        if (is_bool($value)) {
            return $value ? 'true' : 'false';
        }

        if (is_scalar($value)) {
            return print_r($value, true);
        }

        return null;
    }

    private static function escapeValue(string $text): string
    {
        return str_replace(
            ['|', "'", "\n", "\r", ']', '['],
            ['||', "|'", '|n', '|r', '|]', '|['],
            $text
        );
    }

    /**
     * @param string $className
     */
    private static function getFileName($className): string
    {
        try {
            return (new ReflectionClass($className))->getFileName();
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * @param float $time microseconds
     */
    private static function toMilliseconds(float $time): int
    {
        return (int) round($time * 1000);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Log;

use function class_exists;
use function get_class;
use function method_exists;
use function sprintf;
use function str_replace;
use DOMDocument;
use DOMElement;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Exception;
use PHPUnit\Util\Filter;
use PHPUnit\Util\Printer;
use PHPUnit\Util\Xml;
use ReflectionClass;
use ReflectionException;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class JUnit extends Printer implements TestListener
{
    /**
     * @var DOMDocument
     */
    private $document;

    /**
     * @var DOMElement
     */
    private $root;

    /**
     * @var bool
     */
    private $reportRiskyTests = false;

    /**
     * @var DOMElement[]
     */
    private $testSuites = [];

    /**
     * @var int[]
     */
    private $testSuiteTests = [0];

    /**
     * @var int[]
     */
    private $testSuiteAssertions = [0];

    /**
     * @var int[]
     */
    private $testSuiteErrors = [0];

    /**
     * @var int[]
     */
    private $testSuiteWarnings = [0];

    /**
     * @var int[]
     */
    private $testSuiteFailures = [0];

    /**
     * @var int[]
     */
    private $testSuiteSkipped = [0];

    /**
     * @var int[]
     */
    private $testSuiteTimes = [0];

    /**
     * @var int
     */
    private $testSuiteLevel = 0;

    /**
     * @var DOMElement
     */
    private $currentTestCase;

    /**
     * @param null|mixed $out
     */
    public function __construct($out = null, bool $reportRiskyTests = false)
    {
        $this->document               = new DOMDocument('1.0', 'UTF-8');
        $this->document->formatOutput = true;

        $this->root = $this->document->createElement('testsuites');
        $this->document->appendChild($this->root);

        parent::__construct($out);

        $this->reportRiskyTests = $reportRiskyTests;
    }

    /**
     * Flush buffer and close output.
     */
    public function flush(): void
    {
        $this->write($this->getXML());

        parent::flush();
    }

    /**
     * An error occurred.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        $this->doAddFault($test, $t, $time, 'error');
        $this->testSuiteErrors[$this->testSuiteLevel]++;
    }

    /**
     * A warning occurred.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        $this->doAddFault($test, $e, $time, 'warning');
        $this->testSuiteWarnings[$this->testSuiteLevel]++;
    }

    /**
     * A failure occurred.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        $this->doAddFault($test, $e, $time, 'failure');
        $this->testSuiteFailures[$this->testSuiteLevel]++;
    }

    /**
     * Incomplete test.
     */
    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        $this->doAddSkipped();
    }

    /**
     * Risky test.
     */
    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        if (!$this->reportRiskyTests || $this->currentTestCase === null) {
            return;
        }

        $error = $this->document->createElement(
            'error',
            Xml::prepareString(
                "Risky Test\n" .
                Filter::getFilteredStacktrace($t)
            )
        );

        $error->setAttribute('type', get_class($t));

        $this->currentTestCase->appendChild($error);

        $this->testSuiteErrors[$this->testSuiteLevel]++;
    }

    /**
     * Skipped test.
     */
    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        $this->doAddSkipped();
    }

    /**
     * A testsuite started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
        $testSuite = $this->document->createElement('testsuite');
        $testSuite->setAttribute('name', $suite->getName());

        if (class_exists($suite->getName(), false)) {
            try {
                $class = new ReflectionClass($suite->getName());

                $testSuite->setAttribute('file', $class->getFileName());
            } catch (ReflectionException $e) {
            }
        }

        if ($this->testSuiteLevel > 0) {
            $this->testSuites[$this->testSuiteLevel]->appendChild($testSuite);
        } else {
            $this->root->appendChild($testSuite);
        }

        $this->testSuiteLevel++;
        $this->testSuites[$this->testSuiteLevel]          = $testSuite;
        $this->testSuiteTests[$this->testSuiteLevel]      = 0;
        $this->testSuiteAssertions[$this->testSuiteLevel] = 0;
        $this->testSuiteErrors[$this->testSuiteLevel]     = 0;
        $this->testSuiteWarnings[$this->testSuiteLevel]   = 0;
        $this->testSuiteFailures[$this->testSuiteLevel]   = 0;
        $this->testSuiteSkipped[$this->testSuiteLevel]    = 0;
        $this->testSuiteTimes[$this->testSuiteLevel]      = 0;
    }

    /**
     * A testsuite ended.
     */
    public function endTestSuite(TestSuite $suite): void
    {
        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'tests',
            (string) $this->testSuiteTests[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'assertions',
            (string) $this->testSuiteAssertions[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'errors',
            (string) $this->testSuiteErrors[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'warnings',
            (string) $this->testSuiteWarnings[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'failures',
            (string) $this->testSuiteFailures[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'skipped',
            (string) $this->testSuiteSkipped[$this->testSuiteLevel]
        );

        $this->testSuites[$this->testSuiteLevel]->setAttribute(
            'time',
            sprintf('%F', $this->testSuiteTimes[$this->testSuiteLevel])
        );

        if ($this->testSuiteLevel > 1) {
            $this->testSuiteTests[$this->testSuiteLevel - 1] += $this->testSuiteTests[$this->testSuiteLevel];
            $this->testSuiteAssertions[$this->testSuiteLevel - 1] += $this->testSuiteAssertions[$this->testSuiteLevel];
            $this->testSuiteErrors[$this->testSuiteLevel - 1] += $this->testSuiteErrors[$this->testSuiteLevel];
            $this->testSuiteWarnings[$this->testSuiteLevel - 1] += $this->testSuiteWarnings[$this->testSuiteLevel];
            $this->testSuiteFailures[$this->testSuiteLevel - 1] += $this->testSuiteFailures[$this->testSuiteLevel];
            $this->testSuiteSkipped[$this->testSuiteLevel - 1] += $this->testSuiteSkipped[$this->testSuiteLevel];
            $this->testSuiteTimes[$this->testSuiteLevel - 1] += $this->testSuiteTimes[$this->testSuiteLevel];
        }

        $this->testSuiteLevel--;
    }

    /**
     * A test started.
     */
    public function startTest(Test $test): void
    {
        $usesDataprovider = false;

        if (method_exists($test, 'usesDataProvider')) {
            $usesDataprovider = $test->usesDataProvider();
        }

        $testCase = $this->document->createElement('testcase');
        $testCase->setAttribute('name', $test->getName());

        try {
            $class = new ReflectionClass($test);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $methodName = $test->getName(!$usesDataprovider);

        if ($class->hasMethod($methodName)) {
            try {
                $method = $class->getMethod($methodName);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            $testCase->setAttribute('class', $class->getName());
            $testCase->setAttribute('classname', str_replace('\\', '.', $class->getName()));
            $testCase->setAttribute('file', $class->getFileName());
            $testCase->setAttribute('line', (string) $method->getStartLine());
        }

        $this->currentTestCase = $testCase;
    }

    /**
     * A test ended.
     */
    public function endTest(Test $test, float $time): void
    {
        $numAssertions = 0;

        if (method_exists($test, 'getNumAssertions')) {
            $numAssertions = $test->getNumAssertions();
        }

        $this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;

        $this->currentTestCase->setAttribute(
            'assertions',
            (string) $numAssertions
        );

        $this->currentTestCase->setAttribute(
            'time',
            sprintf('%F', $time)
        );

        $this->testSuites[$this->testSuiteLevel]->appendChild(
            $this->currentTestCase
        );

        $this->testSuiteTests[$this->testSuiteLevel]++;
        $this->testSuiteTimes[$this->testSuiteLevel] += $time;

        $testOutput = '';

        if (method_exists($test, 'hasOutput') && method_exists($test, 'getActualOutput')) {
            $testOutput = $test->hasOutput() ? $test->getActualOutput() : '';
        }

        if (!empty($testOutput)) {
            $systemOut = $this->document->createElement(
                'system-out',
                Xml::prepareString($testOutput)
            );

            $this->currentTestCase->appendChild($systemOut);
        }

        $this->currentTestCase = null;
    }

    /**
     * Returns the XML as a string.
     */
    public function getXML(): string
    {
        return $this->document->saveXML();
    }

    private function doAddFault(Test $test, Throwable $t, float $time, $type): void
    {
        if ($this->currentTestCase === null) {
            return;
        }

        if ($test instanceof SelfDescribing) {
            $buffer = $test->toString() . "\n";
        } else {
            $buffer = '';
        }

        $buffer .= TestFailure::exceptionToString($t) . "\n" .
                   Filter::getFilteredStacktrace($t);

        $fault = $this->document->createElement(
            $type,
            Xml::prepareString($buffer)
        );

        if ($t instanceof ExceptionWrapper) {
            $fault->setAttribute('type', $t->getClassName());
        } else {
            $fault->setAttribute('type', get_class($t));
        }

        $this->currentTestCase->appendChild($fault);
    }

    private function doAddSkipped(): void
    {
        if ($this->currentTestCase === null) {
            return;
        }

        $skipped = $this->document->createElement('skipped');

        $this->currentTestCase->appendChild($skipped);

        $this->testSuiteSkipped[$this->testSuiteLevel]++;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const E_DEPRECATED;
use const E_NOTICE;
use const E_STRICT;
use const E_USER_DEPRECATED;
use const E_USER_NOTICE;
use const E_USER_WARNING;
use const E_WARNING;
use function error_reporting;
use function restore_error_handler;
use function set_error_handler;
use PHPUnit\Framework\Error\Deprecated;
use PHPUnit\Framework\Error\Error;
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ErrorHandler
{
    /**
     * @var bool
     */
    private $convertDeprecationsToExceptions;

    /**
     * @var bool
     */
    private $convertErrorsToExceptions;

    /**
     * @var bool
     */
    private $convertNoticesToExceptions;

    /**
     * @var bool
     */
    private $convertWarningsToExceptions;

    /**
     * @var bool
     */
    private $registered = false;

    public static function invokeIgnoringWarnings(callable $callable)
    {
        set_error_handler(
            static function ($errorNumber, $errorString)
            {
                if ($errorNumber === E_WARNING) {
                    return;
                }

                return false;
            }
        );

        $result = $callable();

        restore_error_handler();

        return $result;
    }

    public function __construct(bool $convertDeprecationsToExceptions, bool $convertErrorsToExceptions, bool $convertNoticesToExceptions, bool $convertWarningsToExceptions)
    {
        $this->convertDeprecationsToExceptions = $convertDeprecationsToExceptions;
        $this->convertErrorsToExceptions       = $convertErrorsToExceptions;
        $this->convertNoticesToExceptions      = $convertNoticesToExceptions;
        $this->convertWarningsToExceptions     = $convertWarningsToExceptions;
    }

    public function __invoke(int $errorNumber, string $errorString, string $errorFile, int $errorLine): bool
    {
        /*
         * Do not raise an exception when the error suppression operator (@) was used.
         *
         * @see https://github.com/sebastianbergmann/phpunit/issues/3739
         */
        if (!($errorNumber & error_reporting())) {
            return false;
        }

        switch ($errorNumber) {
            case E_NOTICE:
            case E_USER_NOTICE:
            case E_STRICT:
                if (!$this->convertNoticesToExceptions) {
                    return false;
                }

                throw new Notice($errorString, $errorNumber, $errorFile, $errorLine);

            case E_WARNING:
            case E_USER_WARNING:
                if (!$this->convertWarningsToExceptions) {
                    return false;
                }

                throw new Warning($errorString, $errorNumber, $errorFile, $errorLine);

            case E_DEPRECATED:
            case E_USER_DEPRECATED:
                if (!$this->convertDeprecationsToExceptions) {
                    return false;
                }

                throw new Deprecated($errorString, $errorNumber, $errorFile, $errorLine);

            default:
                if (!$this->convertErrorsToExceptions) {
                    return false;
                }

                throw new Error($errorString, $errorNumber, $errorFile, $errorLine);
        }
    }

    public function register(): void
    {
        if ($this->registered) {
            return;
        }

        $oldErrorHandler = set_error_handler($this);

        if ($oldErrorHandler !== null) {
            restore_error_handler();

            return;
        }

        $this->registered = true;
    }

    public function unregister(): void
    {
        if (!$this->registered) {
            return;
        }

        restore_error_handler();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use RuntimeException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Exception extends RuntimeException implements \PHPUnit\Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const ENT_SUBSTITUTE;
use const PHP_SAPI;
use function assert;
use function count;
use function dirname;
use function explode;
use function fclose;
use function fflush;
use function flush;
use function fopen;
use function fsockopen;
use function fwrite;
use function htmlspecialchars;
use function is_resource;
use function is_string;
use function sprintf;
use function str_replace;
use function strncmp;
use function strpos;
use PHPUnit\Framework\Exception;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class Printer
{
    /**
     * If true, flush output after every write.
     *
     * @var bool
     */
    protected $autoFlush = false;

    /**
     * @psalm-var resource|closed-resource
     */
    protected $out;

    /**
     * @var string
     */
    protected $outTarget;

    /**
     * Constructor.
     *
     * @param null|resource|string $out
     *
     * @throws Exception
     */
    public function __construct($out = null)
    {
        if ($out === null) {
            return;
        }

        if (is_string($out) === false) {
            $this->out = $out;

            return;
        }

        if (strpos($out, 'socket://') === 0) {
            $out = explode(':', str_replace('socket://', '', $out));

            if (count($out) !== 2) {
                throw new Exception;
            }

            $this->out = fsockopen($out[0], $out[1]);
        } else {
            if (strpos($out, 'php://') === false && !Filesystem::createDirectory(dirname($out))) {
                throw new Exception(sprintf('Directory "%s" was not created', dirname($out)));
            }

            $this->out = fopen($out, 'wt');
        }

        $this->outTarget = $out;
    }

    /**
     * Flush buffer and close output if it's not to a PHP stream.
     */
    public function flush(): void
    {
        if ($this->out && strncmp($this->outTarget, 'php://', 6) !== 0) {
            assert(is_resource($this->out));

            fclose($this->out);
        }
    }

    /**
     * Performs a safe, incremental flush.
     *
     * Do not confuse this function with the flush() function of this class,
     * since the flush() function may close the file being written to, rendering
     * the current object no longer usable.
     */
    public function incrementalFlush(): void
    {
        if ($this->out) {
            assert(is_resource($this->out));

            fflush($this->out);
        } else {
            flush();
        }
    }

    public function write(string $buffer): void
    {
        if ($this->out) {
            assert(is_resource($this->out));

            fwrite($this->out, $buffer);

            if ($this->autoFlush) {
                $this->incrementalFlush();
            }
        } else {
            if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') {
                $buffer = htmlspecialchars($buffer, ENT_SUBSTITUTE);
            }

            print $buffer;

            if ($this->autoFlush) {
                $this->incrementalFlush();
            }
        }
    }

    /**
     * Check auto-flush mode.
     */
    public function getAutoFlush(): bool
    {
        return $this->autoFlush;
    }

    /**
     * Set auto-flushing mode.
     *
     * If set, *incremental* flushes will be done after each write. This should
     * not be confused with the different effects of this class' flush() method.
     */
    public function setAutoFlush(bool $autoFlush): void
    {
        $this->autoFlush = $autoFlush;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const DIRECTORY_SEPARATOR;
use function addslashes;
use function array_map;
use function implode;
use function is_string;
use function realpath;
use function sprintf;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class XdebugFilterScriptGenerator
{
    public function generate(array $filterData): string
    {
        $items = $this->getWhitelistItems($filterData);

        $files = array_map(
            static function ($item)
            {
                return sprintf(
                    "        '%s'",
                    $item
                );
            },
            $items
        );

        $files = implode(",\n", $files);

        return <<<EOF
<?php declare(strict_types=1);
if (!\\function_exists('xdebug_set_filter')) {
    return;
}

\\xdebug_set_filter(
    \\XDEBUG_FILTER_CODE_COVERAGE,
    \\XDEBUG_PATH_WHITELIST,
    [
{$files}
    ]
);

EOF;
    }

    private function getWhitelistItems(array $filterData): array
    {
        $files = [];

        if (isset($filterData['include']['directory'])) {
            foreach ($filterData['include']['directory'] as $directory) {
                $path = realpath($directory['path']);

                if (is_string($path)) {
                    $files[] = sprintf(
                        addslashes('%s' . DIRECTORY_SEPARATOR),
                        $path
                    );
                }
            }
        }

        if (isset($filterData['include']['directory'])) {
            foreach ($filterData['include']['file'] as $file) {
                $files[] = $file;
            }
        }

        return $files;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use const PHP_EOL;
use function get_class;
use function sprintf;
use function str_replace;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\PhptTestCase;
use RecursiveIteratorIterator;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TextTestListRenderer
{
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function render(TestSuite $suite): string
    {
        $buffer = 'Available test(s):' . PHP_EOL;

        foreach (new RecursiveIteratorIterator($suite->getIterator()) as $test) {
            if ($test instanceof TestCase) {
                $name = sprintf(
                    '%s::%s',
                    get_class($test),
                    str_replace(' with data set ', '', $test->getName())
                );
            } elseif ($test instanceof PhptTestCase) {
                $name = $test->getName();
            } else {
                continue;
            }

            $buffer .= sprintf(
                ' - %s' . PHP_EOL,
                $name
            );
        }

        return $buffer;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use Throwable;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @deprecated
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface TestListener
{
    public function addError(Test $test, Throwable $t, float $time): void;

    public function addWarning(Test $test, Warning $e, float $time): void;

    public function addFailure(Test $test, AssertionFailedError $e, float $time): void;

    public function addIncompleteTest(Test $test, Throwable $t, float $time): void;

    public function addRiskyTest(Test $test, Throwable $t, float $time): void;

    public function addSkippedTest(Test $test, Throwable $t, float $time): void;

    public function startTestSuite(TestSuite $suite): void;

    public function endTestSuite(TestSuite $suite): void;

    public function startTest(Test $test): void;

    public function endTest(Test $test, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use const PHP_EOL;
use function class_exists;
use function count;
use function extension_loaded;
use function function_exists;
use function get_class;
use function sprintf;
use function xdebug_get_monitored_functions;
use function xdebug_is_debugger_active;
use function xdebug_start_function_monitor;
use function xdebug_stop_function_monitor;
use AssertionError;
use Countable;
use Error;
use PHPUnit\Framework\MockObject\Exception as MockObjectException;
use PHPUnit\Util\Blacklist;
use PHPUnit\Util\ErrorHandler;
use PHPUnit\Util\Printer;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException as OriginalCoveredCodeNotExecutedException;
use SebastianBergmann\CodeCoverage\Exception as OriginalCodeCoverageException;
use SebastianBergmann\CodeCoverage\MissingCoversAnnotationException as OriginalMissingCoversAnnotationException;
use SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException;
use SebastianBergmann\Invoker\Invoker;
use SebastianBergmann\Invoker\TimeoutException;
use SebastianBergmann\ResourceOperations\ResourceOperations;
use SebastianBergmann\Timer\Timer;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestResult implements Countable
{
    /**
     * @var array
     */
    private $passed = [];

    /**
     * @var TestFailure[]
     */
    private $errors = [];

    /**
     * @var TestFailure[]
     */
    private $failures = [];

    /**
     * @var TestFailure[]
     */
    private $warnings = [];

    /**
     * @var TestFailure[]
     */
    private $notImplemented = [];

    /**
     * @var TestFailure[]
     */
    private $risky = [];

    /**
     * @var TestFailure[]
     */
    private $skipped = [];

    /**
     * @deprecated Use the `TestHook` interfaces instead
     *
     * @var TestListener[]
     */
    private $listeners = [];

    /**
     * @var int
     */
    private $runTests = 0;

    /**
     * @var float
     */
    private $time = 0;

    /**
     * @var TestSuite
     */
    private $topTestSuite;

    /**
     * Code Coverage information.
     *
     * @var CodeCoverage
     */
    private $codeCoverage;

    /**
     * @var bool
     */
    private $convertDeprecationsToExceptions = false;

    /**
     * @var bool
     */
    private $convertErrorsToExceptions = true;

    /**
     * @var bool
     */
    private $convertNoticesToExceptions = true;

    /**
     * @var bool
     */
    private $convertWarningsToExceptions = true;

    /**
     * @var bool
     */
    private $stop = false;

    /**
     * @var bool
     */
    private $stopOnError = false;

    /**
     * @var bool
     */
    private $stopOnFailure = false;

    /**
     * @var bool
     */
    private $stopOnWarning = false;

    /**
     * @var bool
     */
    private $beStrictAboutTestsThatDoNotTestAnything = true;

    /**
     * @var bool
     */
    private $beStrictAboutOutputDuringTests = false;

    /**
     * @var bool
     */
    private $beStrictAboutTodoAnnotatedTests = false;

    /**
     * @var bool
     */
    private $beStrictAboutResourceUsageDuringSmallTests = false;

    /**
     * @var bool
     */
    private $enforceTimeLimit = false;

    /**
     * @var int
     */
    private $timeoutForSmallTests = 1;

    /**
     * @var int
     */
    private $timeoutForMediumTests = 10;

    /**
     * @var int
     */
    private $timeoutForLargeTests = 60;

    /**
     * @var bool
     */
    private $stopOnRisky = false;

    /**
     * @var bool
     */
    private $stopOnIncomplete = false;

    /**
     * @var bool
     */
    private $stopOnSkipped = false;

    /**
     * @var bool
     */
    private $lastTestFailed = false;

    /**
     * @var int
     */
    private $defaultTimeLimit = 0;

    /**
     * @var bool
     */
    private $stopOnDefect = false;

    /**
     * @var bool
     */
    private $registerMockObjectsFromTestArgumentsRecursively = false;

    /**
     * @deprecated Use the `TestHook` interfaces instead
     *
     * @codeCoverageIgnore
     *
     * Registers a TestListener.
     */
    public function addListener(TestListener $listener): void
    {
        $this->listeners[] = $listener;
    }

    /**
     * @deprecated Use the `TestHook` interfaces instead
     *
     * @codeCoverageIgnore
     *
     * Unregisters a TestListener.
     */
    public function removeListener(TestListener $listener): void
    {
        foreach ($this->listeners as $key => $_listener) {
            if ($listener === $_listener) {
                unset($this->listeners[$key]);
            }
        }
    }

    /**
     * @deprecated Use the `TestHook` interfaces instead
     *
     * @codeCoverageIgnore
     *
     * Flushes all flushable TestListeners.
     */
    public function flushListeners(): void
    {
        foreach ($this->listeners as $listener) {
            if ($listener instanceof Printer) {
                $listener->flush();
            }
        }
    }

    /**
     * Adds an error to the list of errors.
     */
    public function addError(Test $test, Throwable $t, float $time): void
    {
        if ($t instanceof RiskyTestError) {
            $this->risky[] = new TestFailure($test, $t);
            $notifyMethod  = 'addRiskyTest';

            if ($test instanceof TestCase) {
                $test->markAsRisky();
            }

            if ($this->stopOnRisky || $this->stopOnDefect) {
                $this->stop();
            }
        } elseif ($t instanceof IncompleteTest) {
            $this->notImplemented[] = new TestFailure($test, $t);
            $notifyMethod           = 'addIncompleteTest';

            if ($this->stopOnIncomplete) {
                $this->stop();
            }
        } elseif ($t instanceof SkippedTest) {
            $this->skipped[] = new TestFailure($test, $t);
            $notifyMethod    = 'addSkippedTest';

            if ($this->stopOnSkipped) {
                $this->stop();
            }
        } else {
            $this->errors[] = new TestFailure($test, $t);
            $notifyMethod   = 'addError';

            if ($this->stopOnError || $this->stopOnFailure) {
                $this->stop();
            }
        }

        // @see https://github.com/sebastianbergmann/phpunit/issues/1953
        if ($t instanceof Error) {
            $t = new ExceptionWrapper($t);
        }

        foreach ($this->listeners as $listener) {
            $listener->{$notifyMethod}($test, $t, $time);
        }

        $this->lastTestFailed = true;
        $this->time += $time;
    }

    /**
     * Adds a warning to the list of warnings.
     * The passed in exception caused the warning.
     */
    public function addWarning(Test $test, Warning $e, float $time): void
    {
        if ($this->stopOnWarning || $this->stopOnDefect) {
            $this->stop();
        }

        $this->warnings[] = new TestFailure($test, $e);

        foreach ($this->listeners as $listener) {
            $listener->addWarning($test, $e, $time);
        }

        $this->time += $time;
    }

    /**
     * Adds a failure to the list of failures.
     * The passed in exception caused the failure.
     */
    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        if ($e instanceof RiskyTestError || $e instanceof OutputError) {
            $this->risky[] = new TestFailure($test, $e);
            $notifyMethod  = 'addRiskyTest';

            if ($test instanceof TestCase) {
                $test->markAsRisky();
            }

            if ($this->stopOnRisky || $this->stopOnDefect) {
                $this->stop();
            }
        } elseif ($e instanceof IncompleteTest) {
            $this->notImplemented[] = new TestFailure($test, $e);
            $notifyMethod           = 'addIncompleteTest';

            if ($this->stopOnIncomplete) {
                $this->stop();
            }
        } elseif ($e instanceof SkippedTest) {
            $this->skipped[] = new TestFailure($test, $e);
            $notifyMethod    = 'addSkippedTest';

            if ($this->stopOnSkipped) {
                $this->stop();
            }
        } else {
            $this->failures[] = new TestFailure($test, $e);
            $notifyMethod     = 'addFailure';

            if ($this->stopOnFailure || $this->stopOnDefect) {
                $this->stop();
            }
        }

        foreach ($this->listeners as $listener) {
            $listener->{$notifyMethod}($test, $e, $time);
        }

        $this->lastTestFailed = true;
        $this->time += $time;
    }

    /**
     * Informs the result that a test suite will be started.
     */
    public function startTestSuite(TestSuite $suite): void
    {
        if ($this->topTestSuite === null) {
            $this->topTestSuite = $suite;
        }

        foreach ($this->listeners as $listener) {
            $listener->startTestSuite($suite);
        }
    }

    /**
     * Informs the result that a test suite was completed.
     */
    public function endTestSuite(TestSuite $suite): void
    {
        foreach ($this->listeners as $listener) {
            $listener->endTestSuite($suite);
        }
    }

    /**
     * Informs the result that a test will be started.
     */
    public function startTest(Test $test): void
    {
        $this->lastTestFailed = false;
        $this->runTests += count($test);

        foreach ($this->listeners as $listener) {
            $listener->startTest($test);
        }
    }

    /**
     * Informs the result that a test was completed.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function endTest(Test $test, float $time): void
    {
        foreach ($this->listeners as $listener) {
            $listener->endTest($test, $time);
        }

        if (!$this->lastTestFailed && $test instanceof TestCase) {
            $class = get_class($test);
            $key   = $class . '::' . $test->getName();

            $this->passed[$key] = [
                'result' => $test->getResult(),
                'size'   => TestUtil::getSize(
                    $class,
                    $test->getName(false)
                ),
            ];

            $this->time += $time;
        }
    }

    /**
     * Returns true if no risky test occurred.
     */
    public function allHarmless(): bool
    {
        return $this->riskyCount() == 0;
    }

    /**
     * Gets the number of risky tests.
     */
    public function riskyCount(): int
    {
        return count($this->risky);
    }

    /**
     * Returns true if no incomplete test occurred.
     */
    public function allCompletelyImplemented(): bool
    {
        return $this->notImplementedCount() == 0;
    }

    /**
     * Gets the number of incomplete tests.
     */
    public function notImplementedCount(): int
    {
        return count($this->notImplemented);
    }

    /**
     * Returns an array of TestFailure objects for the risky tests.
     *
     * @return TestFailure[]
     */
    public function risky(): array
    {
        return $this->risky;
    }

    /**
     * Returns an array of TestFailure objects for the incomplete tests.
     *
     * @return TestFailure[]
     */
    public function notImplemented(): array
    {
        return $this->notImplemented;
    }

    /**
     * Returns true if no test has been skipped.
     */
    public function noneSkipped(): bool
    {
        return $this->skippedCount() == 0;
    }

    /**
     * Gets the number of skipped tests.
     */
    public function skippedCount(): int
    {
        return count($this->skipped);
    }

    /**
     * Returns an array of TestFailure objects for the skipped tests.
     *
     * @return TestFailure[]
     */
    public function skipped(): array
    {
        return $this->skipped;
    }

    /**
     * Gets the number of detected errors.
     */
    public function errorCount(): int
    {
        return count($this->errors);
    }

    /**
     * Returns an array of TestFailure objects for the errors.
     *
     * @return TestFailure[]
     */
    public function errors(): array
    {
        return $this->errors;
    }

    /**
     * Gets the number of detected failures.
     */
    public function failureCount(): int
    {
        return count($this->failures);
    }

    /**
     * Returns an array of TestFailure objects for the failures.
     *
     * @return TestFailure[]
     */
    public function failures(): array
    {
        return $this->failures;
    }

    /**
     * Gets the number of detected warnings.
     */
    public function warningCount(): int
    {
        return count($this->warnings);
    }

    /**
     * Returns an array of TestFailure objects for the warnings.
     *
     * @return TestFailure[]
     */
    public function warnings(): array
    {
        return $this->warnings;
    }

    /**
     * Returns the names of the tests that have passed.
     */
    public function passed(): array
    {
        return $this->passed;
    }

    /**
     * Returns the (top) test suite.
     */
    public function topTestSuite(): TestSuite
    {
        return $this->topTestSuite;
    }

    /**
     * Returns whether code coverage information should be collected.
     */
    public function getCollectCodeCoverageInformation(): bool
    {
        return $this->codeCoverage !== null;
    }

    /**
     * Runs a TestCase.
     *
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     * @throws \SebastianBergmann\CodeCoverage\RuntimeException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws CodeCoverageException
     * @throws OriginalCoveredCodeNotExecutedException
     * @throws OriginalMissingCoversAnnotationException
     * @throws UnintentionallyCoveredCodeException
     */
    public function run(Test $test): void
    {
        Assert::resetCount();

        $size = TestUtil::UNKNOWN;

        if ($test instanceof TestCase) {
            $test->setRegisterMockObjectsFromTestArgumentsRecursively(
                $this->registerMockObjectsFromTestArgumentsRecursively
            );

            $isAnyCoverageRequired = TestUtil::requiresCodeCoverageDataCollection($test);
            $size                  = $test->getSize();
        }

        $error      = false;
        $failure    = false;
        $warning    = false;
        $incomplete = false;
        $risky      = false;
        $skipped    = false;

        $this->startTest($test);

        if ($this->convertDeprecationsToExceptions || $this->convertErrorsToExceptions || $this->convertNoticesToExceptions || $this->convertWarningsToExceptions) {
            $errorHandler = new ErrorHandler(
                $this->convertDeprecationsToExceptions,
                $this->convertErrorsToExceptions,
                $this->convertNoticesToExceptions,
                $this->convertWarningsToExceptions
            );

            $errorHandler->register();
        }

        $collectCodeCoverage = $this->codeCoverage !== null &&
                               !$test instanceof WarningTestCase &&
                               $isAnyCoverageRequired;

        if ($collectCodeCoverage) {
            $this->codeCoverage->start($test);
        }

        $monitorFunctions = $this->beStrictAboutResourceUsageDuringSmallTests &&
            !$test instanceof WarningTestCase &&
            $size === TestUtil::SMALL &&
            function_exists('xdebug_start_function_monitor');

        if ($monitorFunctions) {
            /* @noinspection ForgottenDebugOutputInspection */
            xdebug_start_function_monitor(ResourceOperations::getFunctions());
        }

        Timer::start();

        try {
            if (!$test instanceof WarningTestCase &&
                $this->shouldTimeLimitBeEnforced($size)) {
                switch ($size) {
                    case TestUtil::SMALL:
                        $_timeout = $this->timeoutForSmallTests;

                        break;

                    case TestUtil::MEDIUM:
                        $_timeout = $this->timeoutForMediumTests;

                        break;

                    case TestUtil::LARGE:
                        $_timeout = $this->timeoutForLargeTests;

                        break;

                    default:
                        $_timeout = $this->defaultTimeLimit;
                }

                $invoker = new Invoker;
                $invoker->invoke([$test, 'runBare'], [], $_timeout);
            } else {
                $test->runBare();
            }
        } catch (TimeoutException $e) {
            $this->addFailure(
                $test,
                new RiskyTestError(
                    $e->getMessage()
                ),
                $_timeout
            );

            $risky = true;
        } catch (MockObjectException $e) {
            $e = new Warning(
                $e->getMessage()
            );

            $warning = true;
        } catch (AssertionFailedError $e) {
            $failure = true;

            if ($e instanceof RiskyTestError) {
                $risky = true;
            } elseif ($e instanceof IncompleteTestError) {
                $incomplete = true;
            } elseif ($e instanceof SkippedTestError) {
                $skipped = true;
            }
        } catch (AssertionError $e) {
            $test->addToAssertionCount(1);

            $failure = true;
            $frame   = $e->getTrace()[0];

            $e = new AssertionFailedError(
                sprintf(
                    '%s in %s:%s',
                    $e->getMessage(),
                    $frame['file'] ?? $e->getFile(),
                    $frame['line'] ?? $e->getLine()
                ),
                0,
                $e
            );
        } catch (Warning $e) {
            $warning = true;
        } catch (Exception $e) {
            $error = true;
        } catch (Throwable $e) {
            $e     = new ExceptionWrapper($e);
            $error = true;
        }

        $time = Timer::stop();
        $test->addToAssertionCount(Assert::getCount());

        if ($monitorFunctions) {
            $blacklist = new Blacklist;

            /** @noinspection ForgottenDebugOutputInspection */
            $functions = xdebug_get_monitored_functions();

            /* @noinspection ForgottenDebugOutputInspection */
            xdebug_stop_function_monitor();

            foreach ($functions as $function) {
                if (!$blacklist->isBlacklisted($function['filename'])) {
                    $this->addFailure(
                        $test,
                        new RiskyTestError(
                            sprintf(
                                '%s() used in %s:%s',
                                $function['function'],
                                $function['filename'],
                                $function['lineno']
                            )
                        ),
                        $time
                    );
                }
            }
        }

        if ($this->beStrictAboutTestsThatDoNotTestAnything &&
            $test->getNumAssertions() == 0) {
            $risky = true;
        }

        if ($collectCodeCoverage) {
            $append           = !$risky && !$incomplete && !$skipped;
            $linesToBeCovered = [];
            $linesToBeUsed    = [];

            if ($append && $test instanceof TestCase) {
                try {
                    $linesToBeCovered = TestUtil::getLinesToBeCovered(
                        get_class($test),
                        $test->getName(false)
                    );

                    $linesToBeUsed = TestUtil::getLinesToBeUsed(
                        get_class($test),
                        $test->getName(false)
                    );
                } catch (InvalidCoversTargetException $cce) {
                    $this->addWarning(
                        $test,
                        new Warning(
                            $cce->getMessage()
                        ),
                        $time
                    );
                }
            }

            try {
                $this->codeCoverage->stop(
                    $append,
                    $linesToBeCovered,
                    $linesToBeUsed
                );
            } catch (UnintentionallyCoveredCodeException $cce) {
                $this->addFailure(
                    $test,
                    new UnintentionallyCoveredCodeError(
                        'This test executed code that is not listed as code to be covered or used:' .
                        PHP_EOL . $cce->getMessage()
                    ),
                    $time
                );
            } catch (OriginalCoveredCodeNotExecutedException $cce) {
                $this->addFailure(
                    $test,
                    new CoveredCodeNotExecutedException(
                        'This test did not execute all the code that is listed as code to be covered:' .
                        PHP_EOL . $cce->getMessage()
                    ),
                    $time
                );
            } catch (OriginalMissingCoversAnnotationException $cce) {
                if ($linesToBeCovered !== false) {
                    $this->addFailure(
                        $test,
                        new MissingCoversAnnotationException(
                            'This test does not have a @covers annotation but is expected to have one'
                        ),
                        $time
                    );
                }
            } catch (OriginalCodeCoverageException $cce) {
                $error = true;

                $e = $e ?? $cce;
            }
        }

        if (isset($errorHandler)) {
            $errorHandler->unregister();

            unset($errorHandler);
        }

        if ($error) {
            $this->addError($test, $e, $time);
        } elseif ($failure) {
            $this->addFailure($test, $e, $time);
        } elseif ($warning) {
            $this->addWarning($test, $e, $time);
        } elseif ($this->beStrictAboutTestsThatDoNotTestAnything &&
            !$test->doesNotPerformAssertions() &&
            $test->getNumAssertions() == 0) {
            try {
                $reflected = new ReflectionClass($test);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            $name = $test->getName(false);

            if ($name && $reflected->hasMethod($name)) {
                try {
                    $reflected = $reflected->getMethod($name);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd
            }

            $this->addFailure(
                $test,
                new RiskyTestError(
                    sprintf(
                        "This test did not perform any assertions\n\n%s:%d",
                        $reflected->getFileName(),
                        $reflected->getStartLine()
                    )
                ),
                $time
            );
        } elseif ($this->beStrictAboutTestsThatDoNotTestAnything &&
            $test->doesNotPerformAssertions() &&
            $test->getNumAssertions() > 0) {
            $this->addFailure(
                $test,
                new RiskyTestError(
                    sprintf(
                        'This test is annotated with "@doesNotPerformAssertions" but performed %d assertions',
                        $test->getNumAssertions()
                    )
                ),
                $time
            );
        } elseif ($this->beStrictAboutOutputDuringTests && $test->hasOutput()) {
            $this->addFailure(
                $test,
                new OutputError(
                    sprintf(
                        'This test printed output: %s',
                        $test->getActualOutput()
                    )
                ),
                $time
            );
        } elseif ($this->beStrictAboutTodoAnnotatedTests && $test instanceof TestCase) {
            $annotations = $test->getAnnotations();

            if (isset($annotations['method']['todo'])) {
                $this->addFailure(
                    $test,
                    new RiskyTestError(
                        'Test method is annotated with @todo'
                    ),
                    $time
                );
            }
        }

        $this->endTest($test, $time);
    }

    /**
     * Gets the number of run tests.
     */
    public function count(): int
    {
        return $this->runTests;
    }

    /**
     * Checks whether the test run should stop.
     */
    public function shouldStop(): bool
    {
        return $this->stop;
    }

    /**
     * Marks that the test run should stop.
     */
    public function stop(): void
    {
        $this->stop = true;
    }

    /**
     * Returns the code coverage object.
     */
    public function getCodeCoverage(): ?CodeCoverage
    {
        return $this->codeCoverage;
    }

    /**
     * Sets the code coverage object.
     */
    public function setCodeCoverage(CodeCoverage $codeCoverage): void
    {
        $this->codeCoverage = $codeCoverage;
    }

    /**
     * Enables or disables the deprecation-to-exception conversion.
     */
    public function convertDeprecationsToExceptions(bool $flag): void
    {
        $this->convertDeprecationsToExceptions = $flag;
    }

    /**
     * Returns the deprecation-to-exception conversion setting.
     */
    public function getConvertDeprecationsToExceptions(): bool
    {
        return $this->convertDeprecationsToExceptions;
    }

    /**
     * Enables or disables the error-to-exception conversion.
     */
    public function convertErrorsToExceptions(bool $flag): void
    {
        $this->convertErrorsToExceptions = $flag;
    }

    /**
     * Returns the error-to-exception conversion setting.
     */
    public function getConvertErrorsToExceptions(): bool
    {
        return $this->convertErrorsToExceptions;
    }

    /**
     * Enables or disables the notice-to-exception conversion.
     */
    public function convertNoticesToExceptions(bool $flag): void
    {
        $this->convertNoticesToExceptions = $flag;
    }

    /**
     * Returns the notice-to-exception conversion setting.
     */
    public function getConvertNoticesToExceptions(): bool
    {
        return $this->convertNoticesToExceptions;
    }

    /**
     * Enables or disables the warning-to-exception conversion.
     */
    public function convertWarningsToExceptions(bool $flag): void
    {
        $this->convertWarningsToExceptions = $flag;
    }

    /**
     * Returns the warning-to-exception conversion setting.
     */
    public function getConvertWarningsToExceptions(): bool
    {
        return $this->convertWarningsToExceptions;
    }

    /**
     * Enables or disables the stopping when an error occurs.
     */
    public function stopOnError(bool $flag): void
    {
        $this->stopOnError = $flag;
    }

    /**
     * Enables or disables the stopping when a failure occurs.
     */
    public function stopOnFailure(bool $flag): void
    {
        $this->stopOnFailure = $flag;
    }

    /**
     * Enables or disables the stopping when a warning occurs.
     */
    public function stopOnWarning(bool $flag): void
    {
        $this->stopOnWarning = $flag;
    }

    public function beStrictAboutTestsThatDoNotTestAnything(bool $flag): void
    {
        $this->beStrictAboutTestsThatDoNotTestAnything = $flag;
    }

    public function isStrictAboutTestsThatDoNotTestAnything(): bool
    {
        return $this->beStrictAboutTestsThatDoNotTestAnything;
    }

    public function beStrictAboutOutputDuringTests(bool $flag): void
    {
        $this->beStrictAboutOutputDuringTests = $flag;
    }

    public function isStrictAboutOutputDuringTests(): bool
    {
        return $this->beStrictAboutOutputDuringTests;
    }

    public function beStrictAboutResourceUsageDuringSmallTests(bool $flag): void
    {
        $this->beStrictAboutResourceUsageDuringSmallTests = $flag;
    }

    public function isStrictAboutResourceUsageDuringSmallTests(): bool
    {
        return $this->beStrictAboutResourceUsageDuringSmallTests;
    }

    public function enforceTimeLimit(bool $flag): void
    {
        $this->enforceTimeLimit = $flag;
    }

    public function enforcesTimeLimit(): bool
    {
        return $this->enforceTimeLimit;
    }

    public function beStrictAboutTodoAnnotatedTests(bool $flag): void
    {
        $this->beStrictAboutTodoAnnotatedTests = $flag;
    }

    public function isStrictAboutTodoAnnotatedTests(): bool
    {
        return $this->beStrictAboutTodoAnnotatedTests;
    }

    /**
     * Enables or disables the stopping for risky tests.
     */
    public function stopOnRisky(bool $flag): void
    {
        $this->stopOnRisky = $flag;
    }

    /**
     * Enables or disables the stopping for incomplete tests.
     */
    public function stopOnIncomplete(bool $flag): void
    {
        $this->stopOnIncomplete = $flag;
    }

    /**
     * Enables or disables the stopping for skipped tests.
     */
    public function stopOnSkipped(bool $flag): void
    {
        $this->stopOnSkipped = $flag;
    }

    /**
     * Enables or disables the stopping for defects: error, failure, warning.
     */
    public function stopOnDefect(bool $flag): void
    {
        $this->stopOnDefect = $flag;
    }

    /**
     * Returns the time spent running the tests.
     */
    public function time(): float
    {
        return $this->time;
    }

    /**
     * Returns whether the entire test was successful or not.
     */
    public function wasSuccessful(): bool
    {
        return $this->wasSuccessfulIgnoringWarnings() && empty($this->warnings);
    }

    public function wasSuccessfulIgnoringWarnings(): bool
    {
        return empty($this->errors) && empty($this->failures);
    }

    public function wasSuccessfulAndNoTestIsRiskyOrSkippedOrIncomplete(): bool
    {
        return $this->wasSuccessful() && $this->allHarmless() && $this->allCompletelyImplemented() && $this->noneSkipped();
    }

    /**
     * Sets the default timeout for tests.
     */
    public function setDefaultTimeLimit(int $timeout): void
    {
        $this->defaultTimeLimit = $timeout;
    }

    /**
     * Sets the timeout for small tests.
     */
    public function setTimeoutForSmallTests(int $timeout): void
    {
        $this->timeoutForSmallTests = $timeout;
    }

    /**
     * Sets the timeout for medium tests.
     */
    public function setTimeoutForMediumTests(int $timeout): void
    {
        $this->timeoutForMediumTests = $timeout;
    }

    /**
     * Sets the timeout for large tests.
     */
    public function setTimeoutForLargeTests(int $timeout): void
    {
        $this->timeoutForLargeTests = $timeout;
    }

    /**
     * Returns the set timeout for large tests.
     */
    public function getTimeoutForLargeTests(): int
    {
        return $this->timeoutForLargeTests;
    }

    public function setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): void
    {
        $this->registerMockObjectsFromTestArgumentsRecursively = $flag;
    }

    private function shouldTimeLimitBeEnforced(int $size): bool
    {
        if (!$this->enforceTimeLimit) {
            return false;
        }

        if (!(($this->defaultTimeLimit || $size !== TestUtil::UNKNOWN))) {
            return false;
        }

        if (!extension_loaded('pcntl')) {
            return false;
        }

        if (!class_exists(Invoker::class)) {
            return false;
        }

        if (extension_loaded('xdebug') && xdebug_is_debugger_active()) {
            return false;
        }

        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use Throwable;

/**
 * @deprecated The `TestListener` interface is deprecated
 */
trait TestListenerDefaultImplementation
{
    public function addError(Test $test, Throwable $t, float $time): void
    {
    }

    public function addWarning(Test $test, Warning $e, float $time): void
    {
    }

    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
    }

    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
    }

    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
    }

    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
    }

    public function startTestSuite(TestSuite $suite): void
    {
    }

    public function endTestSuite(TestSuite $suite): void
    {
    }

    public function startTest(Test $test): void
    {
    }

    public function endTest(Test $test, float $time): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function assert;
use function count;
use RecursiveIterator;

/**
 * @template-implements RecursiveIterator<int, Test>
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestSuiteIterator implements RecursiveIterator
{
    /**
     * @var int
     */
    private $position = 0;

    /**
     * @var Test[]
     */
    private $tests;

    public function __construct(TestSuite $testSuite)
    {
        $this->tests = $testSuite->tests();
    }

    public function rewind(): void
    {
        $this->position = 0;
    }

    public function valid(): bool
    {
        return $this->position < count($this->tests);
    }

    public function key(): int
    {
        return $this->position;
    }

    public function current(): Test
    {
        return $this->tests[$this->position];
    }

    public function next(): void
    {
        $this->position++;
    }

    /**
     * @throws NoChildTestSuiteException
     */
    public function getChildren(): self
    {
        if (!$this->hasChildren()) {
            throw new NoChildTestSuiteException(
                'The current item is not a TestSuite instance and therefore does not have any children.'
            );
        }

        $current = $this->current();

        assert($current instanceof TestSuite);

        return new self($current);
    }

    public function hasChildren(): bool
    {
        return $this->valid() && $this->current() instanceof TestSuite;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use const PHP_EOL;
use function array_keys;
use function array_merge;
use function array_slice;
use function basename;
use function call_user_func;
use function class_exists;
use function count;
use function dirname;
use function file_exists;
use function get_declared_classes;
use function implode;
use function is_bool;
use function is_object;
use function is_string;
use function method_exists;
use function preg_match;
use function preg_quote;
use function sprintf;
use function substr;
use Iterator;
use IteratorAggregate;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\FileLoader;
use PHPUnit\Util\Reflection;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;

/**
 * @template-implements IteratorAggregate<int, Test>
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class TestSuite implements IteratorAggregate, SelfDescribing, Test
{
    /**
     * Enable or disable the backup and restoration of the $GLOBALS array.
     *
     * @var bool
     */
    protected $backupGlobals;

    /**
     * Enable or disable the backup and restoration of static attributes.
     *
     * @var bool
     */
    protected $backupStaticAttributes;

    /**
     * @var bool
     */
    protected $runTestInSeparateProcess = false;

    /**
     * The name of the test suite.
     *
     * @var string
     */
    protected $name = '';

    /**
     * The test groups of the test suite.
     *
     * @var array
     */
    protected $groups = [];

    /**
     * The tests in the test suite.
     *
     * @var Test[]
     */
    protected $tests = [];

    /**
     * The number of tests in the test suite.
     *
     * @var int
     */
    protected $numTests = -1;

    /**
     * @var bool
     */
    protected $testCase = false;

    /**
     * @var string[]
     */
    protected $foundClasses = [];

    /**
     * Last count of tests in this suite.
     *
     * @var null|int
     */
    private $cachedNumTests;

    /**
     * @var bool
     */
    private $beStrictAboutChangesToGlobalState;

    /**
     * @var Factory
     */
    private $iteratorFilter;

    /**
     * @var int
     */
    private $declaredClassesPointer;

    /**
     * Constructs a new TestSuite:.
     *
     *   - PHPUnit\Framework\TestSuite() constructs an empty TestSuite.
     *
     *   - PHPUnit\Framework\TestSuite(ReflectionClass) constructs a
     *     TestSuite from the given class.
     *
     *   - PHPUnit\Framework\TestSuite(ReflectionClass, String)
     *     constructs a TestSuite from the given class with the given
     *     name.
     *
     *   - PHPUnit\Framework\TestSuite(String) either constructs a
     *     TestSuite from the given class (if the passed string is the
     *     name of an existing class) or constructs an empty TestSuite
     *     with the given name.
     *
     * @param ReflectionClass|string $theClass
     *
     * @throws Exception
     */
    public function __construct($theClass = '', string $name = '')
    {
        if (!is_string($theClass) && !$theClass instanceof ReflectionClass) {
            throw InvalidArgumentException::create(
                1,
                'ReflectionClass object or string'
            );
        }

        $this->declaredClassesPointer = count(get_declared_classes());

        if (!$theClass instanceof ReflectionClass) {
            if (class_exists($theClass, true)) {
                if ($name === '') {
                    $name = $theClass;
                }

                try {
                    $theClass = new ReflectionClass($theClass);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd
            } else {
                $this->setName($theClass);

                return;
            }
        }

        if (!$theClass->isSubclassOf(TestCase::class)) {
            $this->setName((string) $theClass);

            return;
        }

        if ($name !== '') {
            $this->setName($name);
        } else {
            $this->setName($theClass->getName());
        }

        $constructor = $theClass->getConstructor();

        if ($constructor !== null &&
            !$constructor->isPublic()) {
            $this->addTest(
                new WarningTestCase(
                    sprintf(
                        'Class "%s" has no public constructor.',
                        $theClass->getName()
                    )
                )
            );

            return;
        }

        foreach ((new Reflection)->publicMethodsInTestClass($theClass) as $method) {
            if (!TestUtil::isTestMethod($method)) {
                continue;
            }

            $this->addTestMethod($theClass, $method);
        }

        if (empty($this->tests)) {
            $this->addTest(
                new WarningTestCase(
                    sprintf(
                        'No tests found in class "%s".',
                        $theClass->getName()
                    )
                )
            );
        }

        $this->testCase = true;
    }

    /**
     * Returns a string representation of the test suite.
     */
    public function toString(): string
    {
        return $this->getName();
    }

    /**
     * Adds a test to the suite.
     *
     * @param array $groups
     */
    public function addTest(Test $test, $groups = []): void
    {
        try {
            $class = new ReflectionClass($test);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        if (!$class->isAbstract()) {
            $this->tests[]  = $test;
            $this->numTests = -1;

            if ($test instanceof self && empty($groups)) {
                $groups = $test->getGroups();
            }

            if (empty($groups)) {
                $groups = ['default'];
            }

            foreach ($groups as $group) {
                if (!isset($this->groups[$group])) {
                    $this->groups[$group] = [$test];
                } else {
                    $this->groups[$group][] = $test;
                }
            }

            if ($test instanceof TestCase) {
                $test->setGroups($groups);
            }
        }
    }

    /**
     * Adds the tests from the given class to the suite.
     *
     * @param object|string $testClass
     *
     * @throws Exception
     */
    public function addTestSuite($testClass): void
    {
        if (!(is_object($testClass) || (is_string($testClass) && class_exists($testClass)))) {
            throw InvalidArgumentException::create(
                1,
                'class name or object'
            );
        }

        if (!is_object($testClass)) {
            try {
                $testClass = new ReflectionClass($testClass);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd
        }

        if ($testClass instanceof self) {
            $this->addTest($testClass);
        } elseif ($testClass instanceof ReflectionClass) {
            $suiteMethod = false;

            if (!$testClass->isAbstract() && $testClass->hasMethod(BaseTestRunner::SUITE_METHODNAME)) {
                try {
                    $method = $testClass->getMethod(
                        BaseTestRunner::SUITE_METHODNAME
                    );
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if ($method->isStatic()) {
                    $this->addTest(
                        $method->invoke(null, $testClass->getName())
                    );

                    $suiteMethod = true;
                }
            }

            if (!$suiteMethod && !$testClass->isAbstract() && $testClass->isSubclassOf(TestCase::class)) {
                $this->addTest(new self($testClass));
            }
        } else {
            throw new Exception;
        }
    }

    /**
     * Wraps both <code>addTest()</code> and <code>addTestSuite</code>
     * as well as the separate import statements for the user's convenience.
     *
     * If the named file cannot be read or there are no new tests that can be
     * added, a <code>PHPUnit\Framework\WarningTestCase</code> will be created instead,
     * leaving the current test run untouched.
     *
     * @throws Exception
     */
    public function addTestFile(string $filename): void
    {
        if (file_exists($filename) && substr($filename, -5) === '.phpt') {
            $this->addTest(
                new PhptTestCase($filename)
            );

            return;
        }

        // The given file may contain further stub classes in addition to the
        // test class itself. Figure out the actual test class.
        $filename   = FileLoader::checkAndLoad($filename);
        $newClasses = array_slice(get_declared_classes(), $this->declaredClassesPointer);

        // The diff is empty in case a parent class (with test methods) is added
        // AFTER a child class that inherited from it. To account for that case,
        // accumulate all discovered classes, so the parent class may be found in
        // a later invocation.
        if (!empty($newClasses)) {
            // On the assumption that test classes are defined first in files,
            // process discovered classes in approximate LIFO order, so as to
            // avoid unnecessary reflection.
            $this->foundClasses           = array_merge($newClasses, $this->foundClasses);
            $this->declaredClassesPointer = count(get_declared_classes());
        }

        // The test class's name must match the filename, either in full, or as
        // a PEAR/PSR-0 prefixed short name ('NameSpace_ShortName'), or as a
        // PSR-1 local short name ('NameSpace\ShortName'). The comparison must be
        // anchored to prevent false-positive matches (e.g., 'OtherShortName').
        $shortName      = basename($filename, '.php');
        $shortNameRegEx = '/(?:^|_|\\\\)' . preg_quote($shortName, '/') . '$/';

        foreach ($this->foundClasses as $i => $className) {
            if (preg_match($shortNameRegEx, $className)) {
                try {
                    $class = new ReflectionClass($className);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if ($class->getFileName() == $filename) {
                    $newClasses = [$className];
                    unset($this->foundClasses[$i]);

                    break;
                }
            }
        }

        foreach ($newClasses as $className) {
            try {
                $class = new ReflectionClass($className);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if (dirname($class->getFileName()) === __DIR__) {
                continue;
            }

            if (!$class->isAbstract()) {
                if ($class->hasMethod(BaseTestRunner::SUITE_METHODNAME)) {
                    try {
                        $method = $class->getMethod(
                            BaseTestRunner::SUITE_METHODNAME
                        );
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new Exception(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    if ($method->isStatic()) {
                        $this->addTest($method->invoke(null, $className));
                    }
                } elseif ($class->implementsInterface(Test::class)) {
                    $this->addTestSuite($class);
                }
            }
        }

        $this->numTests = -1;
    }

    /**
     * Wrapper for addTestFile() that adds multiple test files.
     *
     * @throws Exception
     */
    public function addTestFiles(iterable $fileNames): void
    {
        foreach ($fileNames as $filename) {
            $this->addTestFile((string) $filename);
        }
    }

    /**
     * Counts the number of test cases that will be run by this test.
     */
    public function count(bool $preferCache = false): int
    {
        if ($preferCache && $this->cachedNumTests !== null) {
            return $this->cachedNumTests;
        }

        $numTests = 0;

        foreach ($this as $test) {
            $numTests += count($test);
        }

        $this->cachedNumTests = $numTests;

        return $numTests;
    }

    /**
     * Returns the name of the suite.
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * Returns the test groups of the suite.
     */
    public function getGroups(): array
    {
        return array_keys($this->groups);
    }

    public function getGroupDetails(): array
    {
        return $this->groups;
    }

    /**
     * Set tests groups of the test case.
     */
    public function setGroupDetails(array $groups): void
    {
        $this->groups = $groups;
    }

    /**
     * Runs the tests and collects their result in a TestResult.
     *
     * @throws \PHPUnit\Framework\CodeCoverageException
     * @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     * @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
     * @throws \SebastianBergmann\CodeCoverage\RuntimeException
     * @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Warning
     */
    public function run(TestResult $result = null): TestResult
    {
        if ($result === null) {
            $result = $this->createResult();
        }

        if (count($this) === 0) {
            return $result;
        }

        /** @psalm-var class-string $className */
        $className   = $this->name;
        $hookMethods = TestUtil::getHookMethods($className);

        $result->startTestSuite($this);

        try {
            foreach ($hookMethods['beforeClass'] as $beforeClassMethod) {
                if ($this->testCase &&
                    class_exists($this->name, false) &&
                    method_exists($this->name, $beforeClassMethod)) {
                    if ($missingRequirements = TestUtil::getMissingRequirements($this->name, $beforeClassMethod)) {
                        $this->markTestSuiteSkipped(implode(PHP_EOL, $missingRequirements));
                    }

                    call_user_func([$this->name, $beforeClassMethod]);
                }
            }
        } catch (SkippedTestSuiteError $error) {
            foreach ($this->tests() as $test) {
                $result->startTest($test);
                $result->addFailure($test, $error, 0);
                $result->endTest($test, 0);
            }

            $result->endTestSuite($this);

            return $result;
        } catch (Throwable $t) {
            $errorAdded = false;

            foreach ($this->tests() as $test) {
                if ($result->shouldStop()) {
                    break;
                }

                $result->startTest($test);

                if (!$errorAdded) {
                    $result->addError($test, $t, 0);

                    $errorAdded = true;
                } else {
                    $result->addFailure(
                        $test,
                        new SkippedTestError('Test skipped because of an error in hook method'),
                        0
                    );
                }

                $result->endTest($test, 0);
            }

            $result->endTestSuite($this);

            return $result;
        }

        foreach ($this as $test) {
            if ($result->shouldStop()) {
                break;
            }

            if ($test instanceof TestCase || $test instanceof self) {
                $test->setBeStrictAboutChangesToGlobalState($this->beStrictAboutChangesToGlobalState);
                $test->setBackupGlobals($this->backupGlobals);
                $test->setBackupStaticAttributes($this->backupStaticAttributes);
                $test->setRunTestInSeparateProcess($this->runTestInSeparateProcess);
            }

            $test->run($result);
        }

        try {
            foreach ($hookMethods['afterClass'] as $afterClassMethod) {
                if ($this->testCase &&
                    class_exists($this->name, false) &&
                    method_exists($this->name, $afterClassMethod)) {
                    call_user_func([$this->name, $afterClassMethod]);
                }
            }
        } catch (Throwable $t) {
            $message = "Exception in {$this->name}::{$afterClassMethod}" . PHP_EOL . $t->getMessage();
            $error   = new SyntheticError($message, 0, $t->getFile(), $t->getLine(), $t->getTrace());

            $placeholderTest = clone $test;
            $placeholderTest->setName($afterClassMethod);

            $result->startTest($placeholderTest);
            $result->addFailure($placeholderTest, $error, 0);
            $result->endTest($placeholderTest, 0);
        }

        $result->endTestSuite($this);

        return $result;
    }

    public function setRunTestInSeparateProcess(bool $runTestInSeparateProcess): void
    {
        $this->runTestInSeparateProcess = $runTestInSeparateProcess;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * Returns the test at the given index.
     *
     * @return false|Test
     */
    public function testAt(int $index)
    {
        return $this->tests[$index] ?? false;
    }

    /**
     * Returns the tests as an enumeration.
     *
     * @return Test[]
     */
    public function tests(): array
    {
        return $this->tests;
    }

    /**
     * Set tests of the test suite.
     *
     * @param Test[] $tests
     */
    public function setTests(array $tests): void
    {
        $this->tests = $tests;
    }

    /**
     * Mark the test suite as skipped.
     *
     * @param string $message
     *
     * @throws SkippedTestSuiteError
     *
     * @psalm-return never-return
     */
    public function markTestSuiteSkipped($message = ''): void
    {
        throw new SkippedTestSuiteError($message);
    }

    /**
     * @param bool $beStrictAboutChangesToGlobalState
     */
    public function setBeStrictAboutChangesToGlobalState($beStrictAboutChangesToGlobalState): void
    {
        if (null === $this->beStrictAboutChangesToGlobalState && is_bool($beStrictAboutChangesToGlobalState)) {
            $this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
        }
    }

    /**
     * @param bool $backupGlobals
     */
    public function setBackupGlobals($backupGlobals): void
    {
        if (null === $this->backupGlobals && is_bool($backupGlobals)) {
            $this->backupGlobals = $backupGlobals;
        }
    }

    /**
     * @param bool $backupStaticAttributes
     */
    public function setBackupStaticAttributes($backupStaticAttributes): void
    {
        if (null === $this->backupStaticAttributes && is_bool($backupStaticAttributes)) {
            $this->backupStaticAttributes = $backupStaticAttributes;
        }
    }

    /**
     * Returns an iterator for this test suite.
     */
    public function getIterator(): Iterator
    {
        $iterator = new TestSuiteIterator($this);

        if ($this->iteratorFilter !== null) {
            $iterator = $this->iteratorFilter->factory($iterator, $this);
        }

        return $iterator;
    }

    public function injectFilter(Factory $filter): void
    {
        $this->iteratorFilter = $filter;

        foreach ($this as $test) {
            if ($test instanceof self) {
                $test->injectFilter($filter);
            }
        }
    }

    /**
     * Creates a default TestResult object.
     */
    protected function createResult(): TestResult
    {
        return new TestResult;
    }

    /**
     * @throws Exception
     */
    protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method): void
    {
        if (!TestUtil::isTestMethod($method)) {
            return;
        }

        $methodName = $method->getName();

        $test = (new TestBuilder)->build($class, $methodName);

        if ($test instanceof TestCase || $test instanceof DataProviderTestSuite) {
            $test->setDependencies(
                TestUtil::getDependencies($class->getName(), $methodName)
            );
        }

        $this->addTest(
            $test,
            TestUtil::getGroups($class->getName(), $methodName)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface SelfDescribing
{
    /**
     * Returns a string representation of the object.
     */
    public function toString(): string;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface IncompleteTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function assert;
use function count;
use function get_class;
use function sprintf;
use function trim;
use PHPUnit\Util\Filter;
use PHPUnit\Util\InvalidDataSetException;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestBuilder
{
    public function build(ReflectionClass $theClass, string $methodName): Test
    {
        $className = $theClass->getName();

        if (!$theClass->isInstantiable()) {
            return new WarningTestCase(
                sprintf('Cannot instantiate class "%s".', $className)
            );
        }

        $backupSettings = TestUtil::getBackupSettings(
            $className,
            $methodName
        );

        $preserveGlobalState = TestUtil::getPreserveGlobalStateSettings(
            $className,
            $methodName
        );

        $runTestInSeparateProcess = TestUtil::getProcessIsolationSettings(
            $className,
            $methodName
        );

        $runClassInSeparateProcess = TestUtil::getClassProcessIsolationSettings(
            $className,
            $methodName
        );

        $constructor = $theClass->getConstructor();

        if ($constructor === null) {
            throw new Exception('No valid test provided.');
        }

        $parameters = $constructor->getParameters();

        // TestCase() or TestCase($name)
        if (count($parameters) < 2) {
            $test = $this->buildTestWithoutData($className);
        } // TestCase($name, $data)
        else {
            try {
                $data = TestUtil::getProvidedData(
                    $className,
                    $methodName
                );
            } catch (IncompleteTestError $e) {
                $message = sprintf(
                    "Test for %s::%s marked incomplete by data provider\n%s",
                    $className,
                    $methodName,
                    $this->throwableToString($e)
                );

                $data = new IncompleteTestCase($className, $methodName, $message);
            } catch (SkippedTestError $e) {
                $message = sprintf(
                    "Test for %s::%s skipped by data provider\n%s",
                    $className,
                    $methodName,
                    $this->throwableToString($e)
                );

                $data = new SkippedTestCase($className, $methodName, $message);
            } catch (Throwable $t) {
                $message = sprintf(
                    "The data provider specified for %s::%s is invalid.\n%s",
                    $className,
                    $methodName,
                    $this->throwableToString($t)
                );

                $data = new WarningTestCase($message);
            }

            // Test method with @dataProvider.
            if (isset($data)) {
                $test = $this->buildDataProviderTestSuite(
                    $methodName,
                    $className,
                    $data,
                    $runTestInSeparateProcess,
                    $preserveGlobalState,
                    $runClassInSeparateProcess,
                    $backupSettings
                );
            } else {
                $test = $this->buildTestWithoutData($className);
            }
        }

        if ($test instanceof TestCase) {
            $test->setName($methodName);
            $this->configureTestCase(
                $test,
                $runTestInSeparateProcess,
                $preserveGlobalState,
                $runClassInSeparateProcess,
                $backupSettings
            );
        }

        return $test;
    }

    /** @psalm-param class-string $className */
    private function buildTestWithoutData(string $className)
    {
        return new $className;
    }

    /** @psalm-param class-string $className */
    private function buildDataProviderTestSuite(
        string $methodName,
        string $className,
        $data,
        bool $runTestInSeparateProcess,
        ?bool $preserveGlobalState,
        bool $runClassInSeparateProcess,
        array $backupSettings
    ): DataProviderTestSuite {
        $dataProviderTestSuite = new DataProviderTestSuite(
            $className . '::' . $methodName
        );

        $groups = TestUtil::getGroups($className, $methodName);

        if ($data instanceof WarningTestCase ||
            $data instanceof SkippedTestCase ||
            $data instanceof IncompleteTestCase) {
            $dataProviderTestSuite->addTest($data, $groups);
        } else {
            foreach ($data as $_dataName => $_data) {
                $_test = new $className($methodName, $_data, $_dataName);

                assert($_test instanceof TestCase);

                $this->configureTestCase(
                    $_test,
                    $runTestInSeparateProcess,
                    $preserveGlobalState,
                    $runClassInSeparateProcess,
                    $backupSettings
                );

                $dataProviderTestSuite->addTest($_test, $groups);
            }
        }

        return $dataProviderTestSuite;
    }

    private function configureTestCase(
        TestCase $test,
        bool $runTestInSeparateProcess,
        ?bool $preserveGlobalState,
        bool $runClassInSeparateProcess,
        array $backupSettings
    ): void {
        if ($runTestInSeparateProcess) {
            $test->setRunTestInSeparateProcess(true);

            if ($preserveGlobalState !== null) {
                $test->setPreserveGlobalState($preserveGlobalState);
            }
        }

        if ($runClassInSeparateProcess) {
            $test->setRunClassInSeparateProcess(true);

            if ($preserveGlobalState !== null) {
                $test->setPreserveGlobalState($preserveGlobalState);
            }
        }

        if ($backupSettings['backupGlobals'] !== null) {
            $test->setBackupGlobals($backupSettings['backupGlobals']);
        }

        if ($backupSettings['backupStaticAttributes'] !== null) {
            $test->setBackupStaticAttributes(
                $backupSettings['backupStaticAttributes']
            );
        }
    }

    private function throwableToString(Throwable $t): string
    {
        $message = $t->getMessage();

        if (empty(trim($message))) {
            $message = '<no message>';
        }

        if ($t instanceof InvalidDataSetException) {
            return sprintf(
                "%s\n%s",
                $message,
                Filter::getFilteredStacktrace($t)
            );
        }

        return sprintf(
            "%s: %s\n%s",
            get_class($t),
            $message,
            Filter::getFilteredStacktrace($t)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function array_keys;
use function get_class;
use function spl_object_hash;
use PHPUnit\Util\Filter;
use Throwable;

/**
 * Wraps Exceptions thrown by code under test.
 *
 * Re-instantiates Exceptions thrown by user-space code to retain their original
 * class names, properties, and stack traces (but without arguments).
 *
 * Unlike PHPUnit\Framework_\Exception, the complete stack of previous Exceptions
 * is processed.
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ExceptionWrapper extends Exception
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @var null|ExceptionWrapper
     */
    protected $previous;

    public function __construct(Throwable $t)
    {
        // PDOException::getCode() is a string.
        // @see https://php.net/manual/en/class.pdoexception.php#95812
        parent::__construct($t->getMessage(), (int) $t->getCode());
        $this->setOriginalException($t);
    }

    public function __toString(): string
    {
        $string = TestFailure::exceptionToString($this);

        if ($trace = Filter::getFilteredStacktrace($this)) {
            $string .= "\n" . $trace;
        }

        if ($this->previous) {
            $string .= "\nCaused by\n" . $this->previous;
        }

        return $string;
    }

    public function getClassName(): string
    {
        return $this->className;
    }

    public function getPreviousWrapped(): ?self
    {
        return $this->previous;
    }

    public function setClassName(string $className): void
    {
        $this->className = $className;
    }

    public function setOriginalException(Throwable $t): void
    {
        $this->originalException($t);

        $this->className = get_class($t);
        $this->file      = $t->getFile();
        $this->line      = $t->getLine();

        $this->serializableTrace = $t->getTrace();

        foreach (array_keys($this->serializableTrace) as $key) {
            unset($this->serializableTrace[$key]['args']);
        }

        if ($t->getPrevious()) {
            $this->previous = new self($t->getPrevious());
        }
    }

    public function getOriginalException(): ?Throwable
    {
        return $this->originalException();
    }

    /**
     * Method to contain static originalException to exclude it from stacktrace to prevent the stacktrace contents,
     * which can be quite big, from being garbage-collected, thus blocking memory until shutdown.
     * Approach works both for var_dump() and var_export() and print_r().
     */
    private function originalException(Throwable $exceptionToStore = null): ?Throwable
    {
        static $originalExceptions;

        $instanceId = spl_object_hash($this);

        if ($exceptionToStore) {
            $originalExceptions[$instanceId] = $exceptionToStore;
        }

        return $originalExceptions[$instanceId] ?? null;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvalidParameterGroupException extends Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Constraint\ArrayHasKey;
use PHPUnit\Framework\Constraint\Attribute;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\ClassHasAttribute;
use PHPUnit\Framework\Constraint\ClassHasStaticAttribute;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\Count;
use PHPUnit\Framework\Constraint\DirectoryExists;
use PHPUnit\Framework\Constraint\FileExists;
use PHPUnit\Framework\Constraint\GreaterThan;
use PHPUnit\Framework\Constraint\IsAnything;
use PHPUnit\Framework\Constraint\IsEmpty;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\Constraint\IsFalse;
use PHPUnit\Framework\Constraint\IsFinite;
use PHPUnit\Framework\Constraint\IsIdentical;
use PHPUnit\Framework\Constraint\IsInfinite;
use PHPUnit\Framework\Constraint\IsInstanceOf;
use PHPUnit\Framework\Constraint\IsJson;
use PHPUnit\Framework\Constraint\IsNan;
use PHPUnit\Framework\Constraint\IsNull;
use PHPUnit\Framework\Constraint\IsReadable;
use PHPUnit\Framework\Constraint\IsTrue;
use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\Constraint\IsWritable;
use PHPUnit\Framework\Constraint\LessThan;
use PHPUnit\Framework\Constraint\LogicalAnd;
use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\Constraint\LogicalOr;
use PHPUnit\Framework\Constraint\LogicalXor;
use PHPUnit\Framework\Constraint\ObjectHasAttribute;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;
use PHPUnit\Framework\Constraint\StringEndsWith;
use PHPUnit\Framework\Constraint\StringMatchesFormatDescription;
use PHPUnit\Framework\Constraint\StringStartsWith;
use PHPUnit\Framework\Constraint\TraversableContains;
use PHPUnit\Framework\Constraint\TraversableContainsEqual;
use PHPUnit\Framework\Constraint\TraversableContainsIdentical;
use PHPUnit\Framework\Constraint\TraversableContainsOnly;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount as AnyInvokedCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtIndex as InvokedAtIndexMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtLeastCount as InvokedAtLeastCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtLeastOnce as InvokedAtLeastOnceMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtMostCount as InvokedAtMostCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCountMatcher;
use PHPUnit\Framework\MockObject\Stub\ConsecutiveCalls as ConsecutiveCallsStub;
use PHPUnit\Framework\MockObject\Stub\Exception as ExceptionStub;
use PHPUnit\Framework\MockObject\Stub\ReturnArgument as ReturnArgumentStub;
use PHPUnit\Framework\MockObject\Stub\ReturnCallback as ReturnCallbackStub;
use PHPUnit\Framework\MockObject\Stub\ReturnSelf as ReturnSelfStub;
use PHPUnit\Framework\MockObject\Stub\ReturnStub;
use PHPUnit\Framework\MockObject\Stub\ReturnValueMap as ReturnValueMapStub;

if (!\function_exists('PHPUnit\Framework\assertArrayHasKey')) {
    /**
     * Asserts that an array has a specified key.
     *
     * @param int|string        $key
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertArrayHasKey
     */
    function assertArrayHasKey($key, $array, string $message = ''): void
    {
        Assert::assertArrayHasKey(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertArraySubset')) {
    /**
     * Asserts that an array has a specified subset.
     *
     * @param array|ArrayAccess $subset
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @codeCoverageIgnore
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3494
     * @see Assert::assertArraySubset
     */
    function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false, string $message = ''): void
    {
        Assert::assertArraySubset(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertArrayNotHasKey')) {
    /**
     * Asserts that an array does not have a specified key.
     *
     * @param int|string        $key
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertArrayNotHasKey
     */
    function assertArrayNotHasKey($key, $array, string $message = ''): void
    {
        Assert::assertArrayNotHasKey(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertContains')) {
    /**
     * Asserts that a haystack contains a needle.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertContains
     */
    function assertContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        Assert::assertContains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertContainsEquals')) {
    function assertContainsEquals($needle, iterable $haystack, string $message = ''): void
    {
        Assert::assertContainsEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeContains')) {
    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object contains a needle.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeContains
     */
    function assertAttributeContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        Assert::assertAttributeContains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotContains')) {
    /**
     * Asserts that a haystack does not contain a needle.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotContains
     */
    function assertNotContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        Assert::assertNotContains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotContainsEquals')) {
    function assertNotContainsEquals($needle, iterable $haystack, string $message = ''): void
    {
        Assert::assertNotContainsEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotContains')) {
    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object does not contain a needle.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotContains
     */
    function assertAttributeNotContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        Assert::assertAttributeNotContains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertContainsOnly')) {
    /**
     * Asserts that a haystack contains only values of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertContainsOnly
     */
    function assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
    {
        Assert::assertContainsOnly(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertContainsOnlyInstancesOf')) {
    /**
     * Asserts that a haystack contains only instances of a given class name.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertContainsOnlyInstancesOf
     */
    function assertContainsOnlyInstancesOf(string $className, iterable $haystack, string $message = ''): void
    {
        Assert::assertContainsOnlyInstancesOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeContainsOnly')) {
    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object contains only values of a given type.
     *
     * @param object|string $haystackClassOrObject
     * @param bool          $isNativeType
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeContainsOnly
     */
    function assertAttributeContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
    {
        Assert::assertAttributeContainsOnly(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotContainsOnly')) {
    /**
     * Asserts that a haystack does not contain only values of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotContainsOnly
     */
    function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
    {
        Assert::assertNotContainsOnly(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotContainsOnly')) {
    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object does not contain only values of a given
     * type.
     *
     * @param object|string $haystackClassOrObject
     * @param bool          $isNativeType
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotContainsOnly
     */
    function assertAttributeNotContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
    {
        Assert::assertAttributeNotContainsOnly(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertCount')) {
    /**
     * Asserts the number of elements of an array, Countable or Traversable.
     *
     * @param Countable|iterable $haystack
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertCount
     */
    function assertCount(int $expectedCount, $haystack, string $message = ''): void
    {
        Assert::assertCount(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeCount')) {
    /**
     * Asserts the number of elements of an array, Countable or Traversable
     * that is stored in an attribute.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeCount
     */
    function assertAttributeCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeCount(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotCount')) {
    /**
     * Asserts the number of elements of an array, Countable or Traversable.
     *
     * @param Countable|iterable $haystack
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotCount
     */
    function assertNotCount(int $expectedCount, $haystack, string $message = ''): void
    {
        Assert::assertNotCount(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotCount')) {
    /**
     * Asserts the number of elements of an array, Countable or Traversable
     * that is stored in an attribute.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotCount
     */
    function assertAttributeNotCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeNotCount(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEquals')) {
    /**
     * Asserts that two variables are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertEquals
     */
    function assertEquals($expected, $actual, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEqualsCanonicalizing')) {
    /**
     * Asserts that two variables are equal (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertEqualsCanonicalizing
     */
    function assertEqualsCanonicalizing($expected, $actual, string $message = ''): void
    {
        Assert::assertEqualsCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEqualsIgnoringCase')) {
    /**
     * Asserts that two variables are equal (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertEqualsIgnoringCase
     */
    function assertEqualsIgnoringCase($expected, $actual, string $message = ''): void
    {
        Assert::assertEqualsIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEqualsWithDelta')) {
    /**
     * Asserts that two variables are equal (with delta).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertEqualsWithDelta
     */
    function assertEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
    {
        Assert::assertEqualsWithDelta(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeEquals')) {
    /**
     * Asserts that a variable is equal to an attribute of an object.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeEquals
     */
    function assertAttributeEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertAttributeEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotEquals')) {
    /**
     * Asserts that two variables are not equal.
     *
     * @param float $delta
     * @param int   $maxDepth
     * @param bool  $canonicalize
     * @param bool  $ignoreCase
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotEquals
     */
    function assertNotEquals($expected, $actual, string $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): void
    {
        Assert::assertNotEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotEqualsCanonicalizing')) {
    /**
     * Asserts that two variables are not equal (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotEqualsCanonicalizing
     */
    function assertNotEqualsCanonicalizing($expected, $actual, string $message = ''): void
    {
        Assert::assertNotEqualsCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotEqualsIgnoringCase')) {
    /**
     * Asserts that two variables are not equal (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotEqualsIgnoringCase
     */
    function assertNotEqualsIgnoringCase($expected, $actual, string $message = ''): void
    {
        Assert::assertNotEqualsIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotEqualsWithDelta')) {
    /**
     * Asserts that two variables are not equal (with delta).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotEqualsWithDelta
     */
    function assertNotEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
    {
        Assert::assertNotEqualsWithDelta(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotEquals')) {
    /**
     * Asserts that a variable is not equal to an attribute of an object.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotEquals
     */
    function assertAttributeNotEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertAttributeNotEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEmpty')) {
    /**
     * Asserts that a variable is empty.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert empty $actual
     *
     * @see Assert::assertEmpty
     */
    function assertEmpty($actual, string $message = ''): void
    {
        Assert::assertEmpty(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeEmpty')) {
    /**
     * Asserts that a static attribute of a class or an attribute of an object
     * is empty.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeEmpty
     */
    function assertAttributeEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeEmpty(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotEmpty')) {
    /**
     * Asserts that a variable is not empty.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !empty $actual
     *
     * @see Assert::assertNotEmpty
     */
    function assertNotEmpty($actual, string $message = ''): void
    {
        Assert::assertNotEmpty(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotEmpty')) {
    /**
     * Asserts that a static attribute of a class or an attribute of an object
     * is not empty.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotEmpty
     */
    function assertAttributeNotEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeNotEmpty(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertGreaterThan')) {
    /**
     * Asserts that a value is greater than another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertGreaterThan
     */
    function assertGreaterThan($expected, $actual, string $message = ''): void
    {
        Assert::assertGreaterThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeGreaterThan')) {
    /**
     * Asserts that an attribute is greater than another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeGreaterThan
     */
    function assertAttributeGreaterThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeGreaterThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertGreaterThanOrEqual')) {
    /**
     * Asserts that a value is greater than or equal to another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertGreaterThanOrEqual
     */
    function assertGreaterThanOrEqual($expected, $actual, string $message = ''): void
    {
        Assert::assertGreaterThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeGreaterThanOrEqual')) {
    /**
     * Asserts that an attribute is greater than or equal to another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeGreaterThanOrEqual
     */
    function assertAttributeGreaterThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeGreaterThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertLessThan')) {
    /**
     * Asserts that a value is smaller than another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertLessThan
     */
    function assertLessThan($expected, $actual, string $message = ''): void
    {
        Assert::assertLessThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeLessThan')) {
    /**
     * Asserts that an attribute is smaller than another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeLessThan
     */
    function assertAttributeLessThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeLessThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertLessThanOrEqual')) {
    /**
     * Asserts that a value is smaller than or equal to another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertLessThanOrEqual
     */
    function assertLessThanOrEqual($expected, $actual, string $message = ''): void
    {
        Assert::assertLessThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeLessThanOrEqual')) {
    /**
     * Asserts that an attribute is smaller than or equal to another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeLessThanOrEqual
     */
    function assertAttributeLessThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeLessThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileEquals')) {
    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileEquals
     */
    function assertFileEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertFileEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileEqualsCanonicalizing')) {
    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileEqualsCanonicalizing
     */
    function assertFileEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
    {
        Assert::assertFileEqualsCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileEqualsIgnoringCase')) {
    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileEqualsIgnoringCase
     */
    function assertFileEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
    {
        Assert::assertFileEqualsIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotEquals')) {
    /**
     * Asserts that the contents of one file is not equal to the contents of
     * another file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotEquals
     */
    function assertFileNotEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertFileNotEquals(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotEqualsCanonicalizing')) {
    /**
     * Asserts that the contents of one file is not equal to the contents of another
     * file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotEqualsCanonicalizing
     */
    function assertFileNotEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
    {
        Assert::assertFileNotEqualsCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotEqualsIgnoringCase')) {
    /**
     * Asserts that the contents of one file is not equal to the contents of another
     * file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotEqualsIgnoringCase
     */
    function assertFileNotEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
    {
        Assert::assertFileNotEqualsIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringEqualsFile')) {
    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringEqualsFile
     */
    function assertStringEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertStringEqualsFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringEqualsFileCanonicalizing')) {
    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringEqualsFileCanonicalizing
     */
    function assertStringEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
    {
        Assert::assertStringEqualsFileCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringEqualsFileIgnoringCase')) {
    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringEqualsFileIgnoringCase
     */
    function assertStringEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
    {
        Assert::assertStringEqualsFileIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFile')) {
    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotEqualsFile
     */
    function assertStringNotEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        Assert::assertStringNotEqualsFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFileCanonicalizing')) {
    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotEqualsFileCanonicalizing
     */
    function assertStringNotEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
    {
        Assert::assertStringNotEqualsFileCanonicalizing(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFileIgnoringCase')) {
    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotEqualsFileIgnoringCase
     */
    function assertStringNotEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
    {
        Assert::assertStringNotEqualsFileIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsReadable')) {
    /**
     * Asserts that a file/dir is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertIsReadable
     */
    function assertIsReadable(string $filename, string $message = ''): void
    {
        Assert::assertIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotIsReadable')) {
    /**
     * Asserts that a file/dir exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotIsReadable
     */
    function assertNotIsReadable(string $filename, string $message = ''): void
    {
        Assert::assertNotIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsWritable')) {
    /**
     * Asserts that a file/dir exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertIsWritable
     */
    function assertIsWritable(string $filename, string $message = ''): void
    {
        Assert::assertIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotIsWritable')) {
    /**
     * Asserts that a file/dir exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotIsWritable
     */
    function assertNotIsWritable(string $filename, string $message = ''): void
    {
        Assert::assertNotIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryExists')) {
    /**
     * Asserts that a directory exists.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryExists
     */
    function assertDirectoryExists(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryNotExists')) {
    /**
     * Asserts that a directory does not exist.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryNotExists
     */
    function assertDirectoryNotExists(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryNotExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryIsReadable')) {
    /**
     * Asserts that a directory exists and is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryIsReadable
     */
    function assertDirectoryIsReadable(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryNotIsReadable')) {
    /**
     * Asserts that a directory exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryNotIsReadable
     */
    function assertDirectoryNotIsReadable(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryNotIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryIsWritable')) {
    /**
     * Asserts that a directory exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryIsWritable
     */
    function assertDirectoryIsWritable(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertDirectoryNotIsWritable')) {
    /**
     * Asserts that a directory exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertDirectoryNotIsWritable
     */
    function assertDirectoryNotIsWritable(string $directory, string $message = ''): void
    {
        Assert::assertDirectoryNotIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileExists')) {
    /**
     * Asserts that a file exists.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileExists
     */
    function assertFileExists(string $filename, string $message = ''): void
    {
        Assert::assertFileExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotExists')) {
    /**
     * Asserts that a file does not exist.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotExists
     */
    function assertFileNotExists(string $filename, string $message = ''): void
    {
        Assert::assertFileNotExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileIsReadable')) {
    /**
     * Asserts that a file exists and is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileIsReadable
     */
    function assertFileIsReadable(string $file, string $message = ''): void
    {
        Assert::assertFileIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotIsReadable')) {
    /**
     * Asserts that a file exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotIsReadable
     */
    function assertFileNotIsReadable(string $file, string $message = ''): void
    {
        Assert::assertFileNotIsReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileIsWritable')) {
    /**
     * Asserts that a file exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileIsWritable
     */
    function assertFileIsWritable(string $file, string $message = ''): void
    {
        Assert::assertFileIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFileNotIsWritable')) {
    /**
     * Asserts that a file exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFileNotIsWritable
     */
    function assertFileNotIsWritable(string $file, string $message = ''): void
    {
        Assert::assertFileNotIsWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertTrue')) {
    /**
     * Asserts that a condition is true.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert true $condition
     *
     * @see Assert::assertTrue
     */
    function assertTrue($condition, string $message = ''): void
    {
        Assert::assertTrue(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotTrue')) {
    /**
     * Asserts that a condition is not true.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !true $condition
     *
     * @see Assert::assertNotTrue
     */
    function assertNotTrue($condition, string $message = ''): void
    {
        Assert::assertNotTrue(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFalse')) {
    /**
     * Asserts that a condition is false.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert false $condition
     *
     * @see Assert::assertFalse
     */
    function assertFalse($condition, string $message = ''): void
    {
        Assert::assertFalse(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotFalse')) {
    /**
     * Asserts that a condition is not false.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !false $condition
     *
     * @see Assert::assertNotFalse
     */
    function assertNotFalse($condition, string $message = ''): void
    {
        Assert::assertNotFalse(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNull')) {
    /**
     * Asserts that a variable is null.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert null $actual
     *
     * @see Assert::assertNull
     */
    function assertNull($actual, string $message = ''): void
    {
        Assert::assertNull(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotNull')) {
    /**
     * Asserts that a variable is not null.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !null $actual
     *
     * @see Assert::assertNotNull
     */
    function assertNotNull($actual, string $message = ''): void
    {
        Assert::assertNotNull(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertFinite')) {
    /**
     * Asserts that a variable is finite.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertFinite
     */
    function assertFinite($actual, string $message = ''): void
    {
        Assert::assertFinite(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertInfinite')) {
    /**
     * Asserts that a variable is infinite.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertInfinite
     */
    function assertInfinite($actual, string $message = ''): void
    {
        Assert::assertInfinite(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNan')) {
    /**
     * Asserts that a variable is nan.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNan
     */
    function assertNan($actual, string $message = ''): void
    {
        Assert::assertNan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertClassHasAttribute')) {
    /**
     * Asserts that a class has a specified attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertClassHasAttribute
     */
    function assertClassHasAttribute(string $attributeName, string $className, string $message = ''): void
    {
        Assert::assertClassHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertClassNotHasAttribute')) {
    /**
     * Asserts that a class does not have a specified attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertClassNotHasAttribute
     */
    function assertClassNotHasAttribute(string $attributeName, string $className, string $message = ''): void
    {
        Assert::assertClassNotHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertClassHasStaticAttribute')) {
    /**
     * Asserts that a class has a specified static attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertClassHasStaticAttribute
     */
    function assertClassHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
    {
        Assert::assertClassHasStaticAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertClassNotHasStaticAttribute')) {
    /**
     * Asserts that a class does not have a specified static attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertClassNotHasStaticAttribute
     */
    function assertClassNotHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
    {
        Assert::assertClassNotHasStaticAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertObjectHasAttribute')) {
    /**
     * Asserts that an object has a specified attribute.
     *
     * @param object $object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertObjectHasAttribute
     */
    function assertObjectHasAttribute(string $attributeName, $object, string $message = ''): void
    {
        Assert::assertObjectHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertObjectNotHasAttribute')) {
    /**
     * Asserts that an object does not have a specified attribute.
     *
     * @param object $object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertObjectNotHasAttribute
     */
    function assertObjectNotHasAttribute(string $attributeName, $object, string $message = ''): void
    {
        Assert::assertObjectNotHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertSame')) {
    /**
     * Asserts that two variables have the same type and value.
     * Used on objects, it asserts that two variables reference
     * the same object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType
     *
     * @psalm-param ExpectedType $expected
     *
     * @psalm-assert =ExpectedType $actual
     *
     * @see Assert::assertSame
     */
    function assertSame($expected, $actual, string $message = ''): void
    {
        Assert::assertSame(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeSame')) {
    /**
     * Asserts that a variable and an attribute of an object have the same type
     * and value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeSame
     */
    function assertAttributeSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeSame(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotSame')) {
    /**
     * Asserts that two variables do not have the same type and value.
     * Used on objects, it asserts that two variables do not reference
     * the same object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotSame
     */
    function assertNotSame($expected, $actual, string $message = ''): void
    {
        Assert::assertNotSame(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotSame')) {
    /**
     * Asserts that a variable and an attribute of an object do not have the
     * same type and value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotSame
     */
    function assertAttributeNotSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        Assert::assertAttributeNotSame(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertInstanceOf')) {
    /**
     * Asserts that a variable is of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType of object
     *
     * @psalm-param class-string<ExpectedType> $expected
     *
     * @psalm-assert =ExpectedType $actual
     *
     * @see Assert::assertInstanceOf
     */
    function assertInstanceOf(string $expected, $actual, string $message = ''): void
    {
        Assert::assertInstanceOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeInstanceOf')) {
    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @psalm-param class-string $expected
     *
     * @see Assert::assertAttributeInstanceOf
     */
    function assertAttributeInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        Assert::assertAttributeInstanceOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotInstanceOf')) {
    /**
     * Asserts that a variable is not of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType of object
     *
     * @psalm-param class-string<ExpectedType> $expected
     *
     * @psalm-assert !ExpectedType $actual
     *
     * @see Assert::assertNotInstanceOf
     */
    function assertNotInstanceOf(string $expected, $actual, string $message = ''): void
    {
        Assert::assertNotInstanceOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotInstanceOf')) {
    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @psalm-param class-string $expected
     *
     * @see Assert::assertAttributeNotInstanceOf
     */
    function assertAttributeNotInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        Assert::assertAttributeNotInstanceOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertInternalType')) {
    /**
     * Asserts that a variable is of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertInternalType
     */
    function assertInternalType(string $expected, $actual, string $message = ''): void
    {
        Assert::assertInternalType(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeInternalType')) {
    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeInternalType
     */
    function assertAttributeInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        Assert::assertAttributeInternalType(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsArray')) {
    /**
     * Asserts that a variable is of type array.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert array $actual
     *
     * @see Assert::assertIsArray
     */
    function assertIsArray($actual, string $message = ''): void
    {
        Assert::assertIsArray(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsBool')) {
    /**
     * Asserts that a variable is of type bool.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert bool $actual
     *
     * @see Assert::assertIsBool
     */
    function assertIsBool($actual, string $message = ''): void
    {
        Assert::assertIsBool(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsFloat')) {
    /**
     * Asserts that a variable is of type float.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert float $actual
     *
     * @see Assert::assertIsFloat
     */
    function assertIsFloat($actual, string $message = ''): void
    {
        Assert::assertIsFloat(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsInt')) {
    /**
     * Asserts that a variable is of type int.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert int $actual
     *
     * @see Assert::assertIsInt
     */
    function assertIsInt($actual, string $message = ''): void
    {
        Assert::assertIsInt(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNumeric')) {
    /**
     * Asserts that a variable is of type numeric.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert numeric $actual
     *
     * @see Assert::assertIsNumeric
     */
    function assertIsNumeric($actual, string $message = ''): void
    {
        Assert::assertIsNumeric(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsObject')) {
    /**
     * Asserts that a variable is of type object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert object $actual
     *
     * @see Assert::assertIsObject
     */
    function assertIsObject($actual, string $message = ''): void
    {
        Assert::assertIsObject(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsResource')) {
    /**
     * Asserts that a variable is of type resource.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert resource $actual
     *
     * @see Assert::assertIsResource
     */
    function assertIsResource($actual, string $message = ''): void
    {
        Assert::assertIsResource(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsString')) {
    /**
     * Asserts that a variable is of type string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert string $actual
     *
     * @see Assert::assertIsString
     */
    function assertIsString($actual, string $message = ''): void
    {
        Assert::assertIsString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsScalar')) {
    /**
     * Asserts that a variable is of type scalar.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert scalar $actual
     *
     * @see Assert::assertIsScalar
     */
    function assertIsScalar($actual, string $message = ''): void
    {
        Assert::assertIsScalar(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsCallable')) {
    /**
     * Asserts that a variable is of type callable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert callable $actual
     *
     * @see Assert::assertIsCallable
     */
    function assertIsCallable($actual, string $message = ''): void
    {
        Assert::assertIsCallable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsIterable')) {
    /**
     * Asserts that a variable is of type iterable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert iterable $actual
     *
     * @see Assert::assertIsIterable
     */
    function assertIsIterable($actual, string $message = ''): void
    {
        Assert::assertIsIterable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotInternalType')) {
    /**
     * Asserts that a variable is not of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertNotInternalType
     */
    function assertNotInternalType(string $expected, $actual, string $message = ''): void
    {
        Assert::assertNotInternalType(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotArray')) {
    /**
     * Asserts that a variable is not of type array.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !array $actual
     *
     * @see Assert::assertIsNotArray
     */
    function assertIsNotArray($actual, string $message = ''): void
    {
        Assert::assertIsNotArray(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotBool')) {
    /**
     * Asserts that a variable is not of type bool.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !bool $actual
     *
     * @see Assert::assertIsNotBool
     */
    function assertIsNotBool($actual, string $message = ''): void
    {
        Assert::assertIsNotBool(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotFloat')) {
    /**
     * Asserts that a variable is not of type float.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !float $actual
     *
     * @see Assert::assertIsNotFloat
     */
    function assertIsNotFloat($actual, string $message = ''): void
    {
        Assert::assertIsNotFloat(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotInt')) {
    /**
     * Asserts that a variable is not of type int.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !int $actual
     *
     * @see Assert::assertIsNotInt
     */
    function assertIsNotInt($actual, string $message = ''): void
    {
        Assert::assertIsNotInt(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotNumeric')) {
    /**
     * Asserts that a variable is not of type numeric.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !numeric $actual
     *
     * @see Assert::assertIsNotNumeric
     */
    function assertIsNotNumeric($actual, string $message = ''): void
    {
        Assert::assertIsNotNumeric(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotObject')) {
    /**
     * Asserts that a variable is not of type object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !object $actual
     *
     * @see Assert::assertIsNotObject
     */
    function assertIsNotObject($actual, string $message = ''): void
    {
        Assert::assertIsNotObject(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotResource')) {
    /**
     * Asserts that a variable is not of type resource.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !resource $actual
     *
     * @see Assert::assertIsNotResource
     */
    function assertIsNotResource($actual, string $message = ''): void
    {
        Assert::assertIsNotResource(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotString')) {
    /**
     * Asserts that a variable is not of type string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !string $actual
     *
     * @see Assert::assertIsNotString
     */
    function assertIsNotString($actual, string $message = ''): void
    {
        Assert::assertIsNotString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotScalar')) {
    /**
     * Asserts that a variable is not of type scalar.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !scalar $actual
     *
     * @see Assert::assertIsNotScalar
     */
    function assertIsNotScalar($actual, string $message = ''): void
    {
        Assert::assertIsNotScalar(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotCallable')) {
    /**
     * Asserts that a variable is not of type callable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !callable $actual
     *
     * @see Assert::assertIsNotCallable
     */
    function assertIsNotCallable($actual, string $message = ''): void
    {
        Assert::assertIsNotCallable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertIsNotIterable')) {
    /**
     * Asserts that a variable is not of type iterable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !iterable $actual
     *
     * @see Assert::assertIsNotIterable
     */
    function assertIsNotIterable($actual, string $message = ''): void
    {
        Assert::assertIsNotIterable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertAttributeNotInternalType')) {
    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @see Assert::assertAttributeNotInternalType
     */
    function assertAttributeNotInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        Assert::assertAttributeNotInternalType(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertRegExp')) {
    /**
     * Asserts that a string matches a given regular expression.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertRegExp
     */
    function assertRegExp(string $pattern, string $string, string $message = ''): void
    {
        Assert::assertRegExp(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotRegExp')) {
    /**
     * Asserts that a string does not match a given regular expression.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotRegExp
     */
    function assertNotRegExp(string $pattern, string $string, string $message = ''): void
    {
        Assert::assertNotRegExp(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertSameSize')) {
    /**
     * Assert that the size of two arrays (or `Countable` or `Traversable` objects)
     * is the same.
     *
     * @param Countable|iterable $expected
     * @param Countable|iterable $actual
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertSameSize
     */
    function assertSameSize($expected, $actual, string $message = ''): void
    {
        Assert::assertSameSize(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertNotSameSize')) {
    /**
     * Assert that the size of two arrays (or `Countable` or `Traversable` objects)
     * is not the same.
     *
     * @param Countable|iterable $expected
     * @param Countable|iterable $actual
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertNotSameSize
     */
    function assertNotSameSize($expected, $actual, string $message = ''): void
    {
        Assert::assertNotSameSize(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringMatchesFormat')) {
    /**
     * Asserts that a string matches a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringMatchesFormat
     */
    function assertStringMatchesFormat(string $format, string $string, string $message = ''): void
    {
        Assert::assertStringMatchesFormat(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotMatchesFormat')) {
    /**
     * Asserts that a string does not match a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotMatchesFormat
     */
    function assertStringNotMatchesFormat(string $format, string $string, string $message = ''): void
    {
        Assert::assertStringNotMatchesFormat(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringMatchesFormatFile')) {
    /**
     * Asserts that a string matches a given format file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringMatchesFormatFile
     */
    function assertStringMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
    {
        Assert::assertStringMatchesFormatFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotMatchesFormatFile')) {
    /**
     * Asserts that a string does not match a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotMatchesFormatFile
     */
    function assertStringNotMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
    {
        Assert::assertStringNotMatchesFormatFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringStartsWith')) {
    /**
     * Asserts that a string starts with a given prefix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringStartsWith
     */
    function assertStringStartsWith(string $prefix, string $string, string $message = ''): void
    {
        Assert::assertStringStartsWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringStartsNotWith')) {
    /**
     * Asserts that a string starts not with a given prefix.
     *
     * @param string $prefix
     * @param string $string
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringStartsNotWith
     */
    function assertStringStartsNotWith($prefix, $string, string $message = ''): void
    {
        Assert::assertStringStartsNotWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringContainsString')) {
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringContainsString
     */
    function assertStringContainsString(string $needle, string $haystack, string $message = ''): void
    {
        Assert::assertStringContainsString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringContainsStringIgnoringCase')) {
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringContainsStringIgnoringCase
     */
    function assertStringContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
    {
        Assert::assertStringContainsStringIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotContainsString')) {
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotContainsString
     */
    function assertStringNotContainsString(string $needle, string $haystack, string $message = ''): void
    {
        Assert::assertStringNotContainsString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringNotContainsStringIgnoringCase')) {
    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringNotContainsStringIgnoringCase
     */
    function assertStringNotContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
    {
        Assert::assertStringNotContainsStringIgnoringCase(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringEndsWith')) {
    /**
     * Asserts that a string ends with a given suffix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringEndsWith
     */
    function assertStringEndsWith(string $suffix, string $string, string $message = ''): void
    {
        Assert::assertStringEndsWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertStringEndsNotWith')) {
    /**
     * Asserts that a string ends not with a given suffix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertStringEndsNotWith
     */
    function assertStringEndsNotWith(string $suffix, string $string, string $message = ''): void
    {
        Assert::assertStringEndsNotWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlFileEqualsXmlFile')) {
    /**
     * Asserts that two XML files are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlFileEqualsXmlFile
     */
    function assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        Assert::assertXmlFileEqualsXmlFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlFileNotEqualsXmlFile')) {
    /**
     * Asserts that two XML files are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlFileNotEqualsXmlFile
     */
    function assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        Assert::assertXmlFileNotEqualsXmlFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlFile')) {
    /**
     * Asserts that two XML documents are equal.
     *
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlStringEqualsXmlFile
     */
    function assertXmlStringEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
    {
        Assert::assertXmlStringEqualsXmlFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlFile')) {
    /**
     * Asserts that two XML documents are not equal.
     *
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlStringNotEqualsXmlFile
     */
    function assertXmlStringNotEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
    {
        Assert::assertXmlStringNotEqualsXmlFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlString')) {
    /**
     * Asserts that two XML documents are equal.
     *
     * @param DOMDocument|string $expectedXml
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlStringEqualsXmlString
     */
    function assertXmlStringEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
    {
        Assert::assertXmlStringEqualsXmlString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlString')) {
    /**
     * Asserts that two XML documents are not equal.
     *
     * @param DOMDocument|string $expectedXml
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @see Assert::assertXmlStringNotEqualsXmlString
     */
    function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
    {
        Assert::assertXmlStringNotEqualsXmlString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertEqualXMLStructure')) {
    /**
     * Asserts that a hierarchy of DOMElements matches.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws AssertionFailedError
     * @throws ExpectationFailedException
     *
     * @see Assert::assertEqualXMLStructure
     */
    function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, bool $checkAttributes = false, string $message = ''): void
    {
        Assert::assertEqualXMLStructure(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertThat')) {
    /**
     * Evaluates a PHPUnit\Framework\Constraint matcher object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertThat
     */
    function assertThat($value, Constraint $constraint, string $message = ''): void
    {
        Assert::assertThat(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJson')) {
    /**
     * Asserts that a string is a valid JSON string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJson
     */
    function assertJson(string $actualJson, string $message = ''): void
    {
        Assert::assertJson(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonString')) {
    /**
     * Asserts that two given JSON encoded objects or arrays are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonStringEqualsJsonString
     */
    function assertJsonStringEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void
    {
        Assert::assertJsonStringEqualsJsonString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonString')) {
    /**
     * Asserts that two given JSON encoded objects or arrays are not equal.
     *
     * @param string $expectedJson
     * @param string $actualJson
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonStringNotEqualsJsonString
     */
    function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, string $message = ''): void
    {
        Assert::assertJsonStringNotEqualsJsonString(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonFile')) {
    /**
     * Asserts that the generated JSON encoded object and the content of the given file are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonStringEqualsJsonFile
     */
    function assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
    {
        Assert::assertJsonStringEqualsJsonFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonFile')) {
    /**
     * Asserts that the generated JSON encoded object and the content of the given file are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonStringNotEqualsJsonFile
     */
    function assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
    {
        Assert::assertJsonStringNotEqualsJsonFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonFileEqualsJsonFile')) {
    /**
     * Asserts that two JSON files are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonFileEqualsJsonFile
     */
    function assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        Assert::assertJsonFileEqualsJsonFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\assertJsonFileNotEqualsJsonFile')) {
    /**
     * Asserts that two JSON files are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @see Assert::assertJsonFileNotEqualsJsonFile
     */
    function assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        Assert::assertJsonFileNotEqualsJsonFile(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\logicalAnd')) {
    function logicalAnd(): LogicalAnd
    {
        return Assert::logicalAnd(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\logicalOr')) {
    function logicalOr(): LogicalOr
    {
        return Assert::logicalOr(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\logicalNot')) {
    function logicalNot(Constraint $constraint): LogicalNot
    {
        return Assert::logicalNot(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\logicalXor')) {
    function logicalXor(): LogicalXor
    {
        return Assert::logicalXor(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\anything')) {
    function anything(): IsAnything
    {
        return Assert::anything(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isTrue')) {
    function isTrue(): IsTrue
    {
        return Assert::isTrue(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\callback')) {
    function callback(callable $callback): Callback
    {
        return Assert::callback(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isFalse')) {
    function isFalse(): IsFalse
    {
        return Assert::isFalse(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isJson')) {
    function isJson(): IsJson
    {
        return Assert::isJson(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isNull')) {
    function isNull(): IsNull
    {
        return Assert::isNull(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isFinite')) {
    function isFinite(): IsFinite
    {
        return Assert::isFinite(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isInfinite')) {
    function isInfinite(): IsInfinite
    {
        return Assert::isInfinite(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isNan')) {
    function isNan(): IsNan
    {
        return Assert::isNan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\attribute')) {
    function attribute(Constraint $constraint, string $attributeName): Attribute
    {
        return Assert::attribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\contains')) {
    function contains($value, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): TraversableContains
    {
        return Assert::contains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\containsEqual')) {
    function containsEqual($value): TraversableContainsEqual
    {
        return Assert::containsEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\containsIdentical')) {
    function containsIdentical($value): TraversableContainsIdentical
    {
        return Assert::containsIdentical(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\containsOnly')) {
    function containsOnly(string $type): TraversableContainsOnly
    {
        return Assert::containsOnly(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\containsOnlyInstancesOf')) {
    function containsOnlyInstancesOf(string $className): TraversableContainsOnly
    {
        return Assert::containsOnlyInstancesOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\arrayHasKey')) {
    function arrayHasKey($key): ArrayHasKey
    {
        return Assert::arrayHasKey(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\equalTo')) {
    function equalTo($value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): IsEqual
    {
        return Assert::equalTo(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\attributeEqualTo')) {
    function attributeEqualTo(string $attributeName, $value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): Attribute
    {
        return Assert::attributeEqualTo(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isEmpty')) {
    function isEmpty(): IsEmpty
    {
        return Assert::isEmpty(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isWritable')) {
    function isWritable(): IsWritable
    {
        return Assert::isWritable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isReadable')) {
    function isReadable(): IsReadable
    {
        return Assert::isReadable(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\directoryExists')) {
    function directoryExists(): DirectoryExists
    {
        return Assert::directoryExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\fileExists')) {
    function fileExists(): FileExists
    {
        return Assert::fileExists(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\greaterThan')) {
    function greaterThan($value): GreaterThan
    {
        return Assert::greaterThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\greaterThanOrEqual')) {
    function greaterThanOrEqual($value): LogicalOr
    {
        return Assert::greaterThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\classHasAttribute')) {
    function classHasAttribute(string $attributeName): ClassHasAttribute
    {
        return Assert::classHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\classHasStaticAttribute')) {
    function classHasStaticAttribute(string $attributeName): ClassHasStaticAttribute
    {
        return Assert::classHasStaticAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\objectHasAttribute')) {
    function objectHasAttribute($attributeName): ObjectHasAttribute
    {
        return Assert::objectHasAttribute(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\identicalTo')) {
    function identicalTo($value): IsIdentical
    {
        return Assert::identicalTo(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isInstanceOf')) {
    function isInstanceOf(string $className): IsInstanceOf
    {
        return Assert::isInstanceOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\isType')) {
    function isType(string $type): IsType
    {
        return Assert::isType(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\lessThan')) {
    function lessThan($value): LessThan
    {
        return Assert::lessThan(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\lessThanOrEqual')) {
    function lessThanOrEqual($value): LogicalOr
    {
        return Assert::lessThanOrEqual(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\matchesRegularExpression')) {
    function matchesRegularExpression(string $pattern): RegularExpression
    {
        return Assert::matchesRegularExpression(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\matches')) {
    function matches(string $string): StringMatchesFormatDescription
    {
        return Assert::matches(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\stringStartsWith')) {
    function stringStartsWith($prefix): StringStartsWith
    {
        return Assert::stringStartsWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\stringContains')) {
    function stringContains(string $string, bool $case = true): StringContains
    {
        return Assert::stringContains(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\stringEndsWith')) {
    function stringEndsWith(string $suffix): StringEndsWith
    {
        return Assert::stringEndsWith(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\countOf')) {
    function countOf(int $count): Count
    {
        return Assert::countOf(...\func_get_args());
    }
}

if (!\function_exists('PHPUnit\Framework\any')) {
    /**
     * Returns a matcher that matches when the method is executed
     * zero or more times.
     */
    function any(): AnyInvokedCountMatcher
    {
        return new AnyInvokedCountMatcher;
    }
}

if (!\function_exists('PHPUnit\Framework\never')) {
    /**
     * Returns a matcher that matches when the method is never executed.
     */
    function never(): InvokedCountMatcher
    {
        return new InvokedCountMatcher(0);
    }
}

if (!\function_exists('PHPUnit\Framework\atLeast')) {
    /**
     * Returns a matcher that matches when the method is executed
     * at least N times.
     */
    function atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher
    {
        return new InvokedAtLeastCountMatcher(
            $requiredInvocations
        );
    }
}

if (!\function_exists('PHPUnit\Framework\atLeastOnce')) {
    /**
     * Returns a matcher that matches when the method is executed at least once.
     */
    function atLeastOnce(): InvokedAtLeastOnceMatcher
    {
        return new InvokedAtLeastOnceMatcher;
    }
}

if (!\function_exists('PHPUnit\Framework\once')) {
    /**
     * Returns a matcher that matches when the method is executed exactly once.
     */
    function once(): InvokedCountMatcher
    {
        return new InvokedCountMatcher(1);
    }
}

if (!\function_exists('PHPUnit\Framework\exactly')) {
    /**
     * Returns a matcher that matches when the method is executed
     * exactly $count times.
     */
    function exactly(int $count): InvokedCountMatcher
    {
        return new InvokedCountMatcher($count);
    }
}

if (!\function_exists('PHPUnit\Framework\atMost')) {
    /**
     * Returns a matcher that matches when the method is executed
     * at most N times.
     */
    function atMost(int $allowedInvocations): InvokedAtMostCountMatcher
    {
        return new InvokedAtMostCountMatcher($allowedInvocations);
    }
}

if (!\function_exists('PHPUnit\Framework\at')) {
    /**
     * Returns a matcher that matches when the method is executed
     * at the given index.
     */
    function at(int $index): InvokedAtIndexMatcher
    {
        return new InvokedAtIndexMatcher($index);
    }
}

if (!\function_exists('PHPUnit\Framework\returnValue')) {
    function returnValue($value): ReturnStub
    {
        return new ReturnStub($value);
    }
}

if (!\function_exists('PHPUnit\Framework\returnValueMap')) {
    function returnValueMap(array $valueMap): ReturnValueMapStub
    {
        return new ReturnValueMapStub($valueMap);
    }
}

if (!\function_exists('PHPUnit\Framework\returnArgument')) {
    function returnArgument(int $argumentIndex): ReturnArgumentStub
    {
        return new ReturnArgumentStub($argumentIndex);
    }
}

if (!\function_exists('PHPUnit\Framework\returnCallback')) {
    function returnCallback($callback): ReturnCallbackStub
    {
        return new ReturnCallbackStub($callback);
    }
}

if (!\function_exists('PHPUnit\Framework\returnSelf')) {
    /**
     * Returns the current object.
     *
     * This method is useful when mocking a fluent interface.
     */
    function returnSelf(): ReturnSelfStub
    {
        return new ReturnSelfStub;
    }
}

if (!\function_exists('PHPUnit\Framework\throwException')) {
    function throwException(Throwable $exception): ExceptionStub
    {
        return new ExceptionStub($exception);
    }
}

if (!\function_exists('PHPUnit\Framework\onConsecutiveCalls')) {
    function onConsecutiveCalls(): ConsecutiveCallsStub
    {
        $args = \func_get_args();

        return new ConsecutiveCallsStub($args);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function count;
use function explode;
use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DataProviderTestSuite extends TestSuite
{
    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @param string[] $dependencies
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;

        foreach ($this->tests as $test) {
            if (!$test instanceof TestCase) {
                continue;
            }

            $test->setDependencies($dependencies);
        }
    }

    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    public function hasDependencies(): bool
    {
        return count($this->dependencies) > 0;
    }

    /**
     * Returns the size of the each test created using the data provider(s).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function getSize(): int
    {
        [$className, $methodName] = explode('::', $this->getName());

        return TestUtil::getSize($className, $methodName);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use const DEBUG_BACKTRACE_IGNORE_ARGS;
use const PHP_EOL;
use function array_key_exists;
use function array_shift;
use function array_unshift;
use function assert;
use function class_exists;
use function count;
use function debug_backtrace;
use function explode;
use function file_get_contents;
use function func_get_args;
use function implode;
use function interface_exists;
use function is_array;
use function is_bool;
use function is_int;
use function is_iterable;
use function is_object;
use function is_string;
use function preg_match;
use function preg_split;
use function sprintf;
use function strpos;
use ArrayAccess;
use Countable;
use DOMAttr;
use DOMDocument;
use DOMElement;
use PHPUnit\Framework\Constraint\ArrayHasKey;
use PHPUnit\Framework\Constraint\ArraySubset;
use PHPUnit\Framework\Constraint\Attribute;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\ClassHasAttribute;
use PHPUnit\Framework\Constraint\ClassHasStaticAttribute;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\Count;
use PHPUnit\Framework\Constraint\DirectoryExists;
use PHPUnit\Framework\Constraint\FileExists;
use PHPUnit\Framework\Constraint\GreaterThan;
use PHPUnit\Framework\Constraint\IsAnything;
use PHPUnit\Framework\Constraint\IsEmpty;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\Constraint\IsFalse;
use PHPUnit\Framework\Constraint\IsFinite;
use PHPUnit\Framework\Constraint\IsIdentical;
use PHPUnit\Framework\Constraint\IsInfinite;
use PHPUnit\Framework\Constraint\IsInstanceOf;
use PHPUnit\Framework\Constraint\IsJson;
use PHPUnit\Framework\Constraint\IsNan;
use PHPUnit\Framework\Constraint\IsNull;
use PHPUnit\Framework\Constraint\IsReadable;
use PHPUnit\Framework\Constraint\IsTrue;
use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\Constraint\IsWritable;
use PHPUnit\Framework\Constraint\JsonMatches;
use PHPUnit\Framework\Constraint\LessThan;
use PHPUnit\Framework\Constraint\LogicalAnd;
use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\Constraint\LogicalOr;
use PHPUnit\Framework\Constraint\LogicalXor;
use PHPUnit\Framework\Constraint\ObjectHasAttribute;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\SameSize;
use PHPUnit\Framework\Constraint\StringContains;
use PHPUnit\Framework\Constraint\StringEndsWith;
use PHPUnit\Framework\Constraint\StringMatchesFormatDescription;
use PHPUnit\Framework\Constraint\StringStartsWith;
use PHPUnit\Framework\Constraint\TraversableContains;
use PHPUnit\Framework\Constraint\TraversableContainsEqual;
use PHPUnit\Framework\Constraint\TraversableContainsIdentical;
use PHPUnit\Framework\Constraint\TraversableContainsOnly;
use PHPUnit\Util\Type;
use PHPUnit\Util\Xml;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
use Traversable;

/**
 * A set of assertion methods.
 */
abstract class Assert
{
    /**
     * @var int
     */
    private static $count = 0;

    /**
     * Asserts that an array has a specified key.
     *
     * @param int|string        $key
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertArrayHasKey($key, $array, string $message = ''): void
    {
        if (!(is_int($key) || is_string($key))) {
            throw InvalidArgumentException::create(
                1,
                'integer or string'
            );
        }

        if (!(is_array($array) || $array instanceof ArrayAccess)) {
            throw InvalidArgumentException::create(
                2,
                'array or ArrayAccess'
            );
        }

        $constraint = new ArrayHasKey($key);

        static::assertThat($array, $constraint, $message);
    }

    /**
     * Asserts that an array has a specified subset.
     *
     * @param array|ArrayAccess $subset
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @codeCoverageIgnore
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3494
     */
    public static function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false, string $message = ''): void
    {
        self::createWarning('assertArraySubset() is deprecated and will be removed in PHPUnit 9.');

        if (!(is_array($subset) || $subset instanceof ArrayAccess)) {
            throw InvalidArgumentException::create(
                1,
                'array or ArrayAccess'
            );
        }

        if (!(is_array($array) || $array instanceof ArrayAccess)) {
            throw InvalidArgumentException::create(
                2,
                'array or ArrayAccess'
            );
        }

        $constraint = new ArraySubset($subset, $checkForObjectIdentity);

        static::assertThat($array, $constraint, $message);
    }

    /**
     * Asserts that an array does not have a specified key.
     *
     * @param int|string        $key
     * @param array|ArrayAccess $array
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertArrayNotHasKey($key, $array, string $message = ''): void
    {
        if (!(is_int($key) || is_string($key))) {
            throw InvalidArgumentException::create(
                1,
                'integer or string'
            );
        }

        if (!(is_array($array) || $array instanceof ArrayAccess)) {
            throw InvalidArgumentException::create(
                2,
                'array or ArrayAccess'
            );
        }

        $constraint = new LogicalNot(
            new ArrayHasKey($key)
        );

        static::assertThat($array, $constraint, $message);
    }

    /**
     * Asserts that a haystack contains a needle.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        // @codeCoverageIgnoreStart
        if (is_string($haystack)) {
            self::createWarning('Using assertContains() with string haystacks is deprecated and will not be supported in PHPUnit 9. Refactor your test to use assertStringContainsString() or assertStringContainsStringIgnoringCase() instead.');
        }

        if (!$checkForObjectIdentity) {
            self::createWarning('The optional $checkForObjectIdentity parameter of assertContains() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertContainsEquals() instead.');
        }

        if ($checkForNonObjectIdentity) {
            self::createWarning('The optional $checkForNonObjectIdentity parameter of assertContains() is deprecated and will be removed in PHPUnit 9.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertContains() is deprecated and will be removed in PHPUnit 9.');
        }
        // @codeCoverageIgnoreEnd

        if (is_array($haystack) ||
            (is_object($haystack) && $haystack instanceof Traversable)) {
            $constraint = new TraversableContains(
                $needle,
                $checkForObjectIdentity,
                $checkForNonObjectIdentity
            );
        } elseif (is_string($haystack)) {
            if (!is_string($needle)) {
                throw InvalidArgumentException::create(
                    1,
                    'string'
                );
            }

            $constraint = new StringContains(
                $needle,
                $ignoreCase
            );
        } else {
            throw InvalidArgumentException::create(
                2,
                'array, traversable or string'
            );
        }

        static::assertThat($haystack, $constraint, $message);
    }

    public static function assertContainsEquals($needle, iterable $haystack, string $message = ''): void
    {
        $constraint = new TraversableContainsEqual($needle);

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object contains a needle.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        self::createWarning('assertAttributeContains() is deprecated and will be removed in PHPUnit 9.');

        static::assertContains(
            $needle,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message,
            $ignoreCase,
            $checkForObjectIdentity,
            $checkForNonObjectIdentity
        );
    }

    /**
     * Asserts that a haystack does not contain a needle.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertNotContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        // @codeCoverageIgnoreStart
        if (is_string($haystack)) {
            self::createWarning('Using assertNotContains() with string haystacks is deprecated and will not be supported in PHPUnit 9. Refactor your test to use assertStringNotContainsString() or assertStringNotContainsStringIgnoringCase() instead.');
        }

        if (!$checkForObjectIdentity) {
            self::createWarning('The optional $checkForObjectIdentity parameter of assertNotContains() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertNotContainsEquals() instead.');
        }

        if ($checkForNonObjectIdentity) {
            self::createWarning('The optional $checkForNonObjectIdentity parameter of assertNotContains() is deprecated and will be removed in PHPUnit 9.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertNotContains() is deprecated and will be removed in PHPUnit 9.');
        }
        // @codeCoverageIgnoreEnd

        if (is_array($haystack) ||
            (is_object($haystack) && $haystack instanceof Traversable)) {
            $constraint = new LogicalNot(
                new TraversableContains(
                    $needle,
                    $checkForObjectIdentity,
                    $checkForNonObjectIdentity
                )
            );
        } elseif (is_string($haystack)) {
            if (!is_string($needle)) {
                throw InvalidArgumentException::create(
                    1,
                    'string'
                );
            }

            $constraint = new LogicalNot(
                new StringContains(
                    $needle,
                    $ignoreCase
                )
            );
        } else {
            throw InvalidArgumentException::create(
                2,
                'array, traversable or string'
            );
        }

        static::assertThat($haystack, $constraint, $message);
    }

    public static function assertNotContainsEquals($needle, iterable $haystack, string $message = ''): void
    {
        $constraint = new LogicalNot(new TraversableContainsEqual($needle));

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object does not contain a needle.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotContains($needle, string $haystackAttributeName, $haystackClassOrObject, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void
    {
        self::createWarning('assertAttributeNotContains() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotContains(
            $needle,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message,
            $ignoreCase,
            $checkForObjectIdentity,
            $checkForNonObjectIdentity
        );
    }

    /**
     * Asserts that a haystack contains only values of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
    {
        if ($isNativeType === null) {
            $isNativeType = Type::isType($type);
        }

        static::assertThat(
            $haystack,
            new TraversableContainsOnly(
                $type,
                $isNativeType
            ),
            $message
        );
    }

    /**
     * Asserts that a haystack contains only instances of a given class name.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertContainsOnlyInstancesOf(string $className, iterable $haystack, string $message = ''): void
    {
        static::assertThat(
            $haystack,
            new TraversableContainsOnly(
                $className,
                false
            ),
            $message
        );
    }

    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object contains only values of a given type.
     *
     * @param object|string $haystackClassOrObject
     * @param bool          $isNativeType
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
    {
        self::createWarning('assertAttributeContainsOnly() is deprecated and will be removed in PHPUnit 9.');

        static::assertContainsOnly(
            $type,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $isNativeType,
            $message
        );
    }

    /**
     * Asserts that a haystack does not contain only values of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
    {
        if ($isNativeType === null) {
            $isNativeType = Type::isType($type);
        }

        static::assertThat(
            $haystack,
            new LogicalNot(
                new TraversableContainsOnly(
                    $type,
                    $isNativeType
                )
            ),
            $message
        );
    }

    /**
     * Asserts that a haystack that is stored in a static attribute of a class
     * or an attribute of an object does not contain only values of a given
     * type.
     *
     * @param object|string $haystackClassOrObject
     * @param bool          $isNativeType
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotContainsOnly(string $type, string $haystackAttributeName, $haystackClassOrObject, ?bool $isNativeType = null, string $message = ''): void
    {
        self::createWarning('assertAttributeNotContainsOnly() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotContainsOnly(
            $type,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $isNativeType,
            $message
        );
    }

    /**
     * Asserts the number of elements of an array, Countable or Traversable.
     *
     * @param Countable|iterable $haystack
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertCount(int $expectedCount, $haystack, string $message = ''): void
    {
        if (!$haystack instanceof Countable && !is_iterable($haystack)) {
            throw InvalidArgumentException::create(2, 'countable or iterable');
        }

        static::assertThat(
            $haystack,
            new Count($expectedCount),
            $message
        );
    }

    /**
     * Asserts the number of elements of an array, Countable or Traversable
     * that is stored in an attribute.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeCount() is deprecated and will be removed in PHPUnit 9.');

        static::assertCount(
            $expectedCount,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message
        );
    }

    /**
     * Asserts the number of elements of an array, Countable or Traversable.
     *
     * @param Countable|iterable $haystack
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertNotCount(int $expectedCount, $haystack, string $message = ''): void
    {
        if (!$haystack instanceof Countable && !is_iterable($haystack)) {
            throw InvalidArgumentException::create(2, 'countable or iterable');
        }

        $constraint = new LogicalNot(
            new Count($expectedCount)
        );

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * Asserts the number of elements of an array, Countable or Traversable
     * that is stored in an attribute.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotCount(int $expectedCount, string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeNotCount() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotCount(
            $expectedCount,
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message
        );
    }

    /**
     * Asserts that two variables are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertEquals($expected, $actual, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($delta !== 0.0) {
            self::createWarning('The optional $delta parameter of assertEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertEqualsWithDelta() instead.');
        }

        if ($maxDepth !== 10) {
            self::createWarning('The optional $maxDepth parameter of assertEquals() is deprecated and will be removed in PHPUnit 9.');
        }

        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertEqualsCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertEqualsIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        $constraint = new IsEqual(
            $expected,
            $delta,
            $maxDepth,
            $canonicalize,
            $ignoreCase
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are equal (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertEqualsCanonicalizing($expected, $actual, string $message = ''): void
    {
        $constraint = new IsEqual(
            $expected,
            0.0,
            10,
            true,
            false
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are equal (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertEqualsIgnoringCase($expected, $actual, string $message = ''): void
    {
        $constraint = new IsEqual(
            $expected,
            0.0,
            10,
            false,
            true
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are equal (with delta).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
    {
        $constraint = new IsEqual(
            $expected,
            $delta
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that a variable is equal to an attribute of an object.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        self::createWarning('assertAttributeEquals() is deprecated and will be removed in PHPUnit 9.');

        static::assertEquals(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message,
            $delta,
            $maxDepth,
            $canonicalize,
            $ignoreCase
        );
    }

    /**
     * Asserts that two variables are not equal.
     *
     * @param float $delta
     * @param int   $maxDepth
     * @param bool  $canonicalize
     * @param bool  $ignoreCase
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotEquals($expected, $actual, string $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($delta !== 0.0) {
            self::createWarning('The optional $delta parameter of assertNotEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertNotEqualsWithDelta() instead.');
        }

        if ($maxDepth !== 10) {
            self::createWarning('The optional $maxDepth parameter of assertNotEquals() is deprecated and will be removed in PHPUnit 9.');
        }

        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertNotEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertNotEqualsCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertNotEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertNotEqualsIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        $constraint = new LogicalNot(
            new IsEqual(
                $expected,
                $delta,
                $maxDepth,
                $canonicalize,
                $ignoreCase
            )
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are not equal (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotEqualsCanonicalizing($expected, $actual, string $message = ''): void
    {
        $constraint = new LogicalNot(
            new IsEqual(
                $expected,
                0.0,
                10,
                true,
                false
            )
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are not equal (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotEqualsIgnoringCase($expected, $actual, string $message = ''): void
    {
        $constraint = new LogicalNot(
            new IsEqual(
                $expected,
                0.0,
                10,
                false,
                true
            )
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that two variables are not equal (with delta).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void
    {
        $constraint = new LogicalNot(
            new IsEqual(
                $expected,
                $delta
            )
        );

        static::assertThat($actual, $constraint, $message);
    }

    /**
     * Asserts that a variable is not equal to an attribute of an object.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotEquals($expected, string $actualAttributeName, $actualClassOrObject, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void
    {
        self::createWarning('assertAttributeNotEquals() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotEquals(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message,
            $delta,
            $maxDepth,
            $canonicalize,
            $ignoreCase
        );
    }

    /**
     * Asserts that a variable is empty.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert empty $actual
     */
    public static function assertEmpty($actual, string $message = ''): void
    {
        static::assertThat($actual, static::isEmpty(), $message);
    }

    /**
     * Asserts that a static attribute of a class or an attribute of an object
     * is empty.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeEmpty() is deprecated and will be removed in PHPUnit 9.');

        static::assertEmpty(
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message
        );
    }

    /**
     * Asserts that a variable is not empty.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !empty $actual
     */
    public static function assertNotEmpty($actual, string $message = ''): void
    {
        static::assertThat($actual, static::logicalNot(static::isEmpty()), $message);
    }

    /**
     * Asserts that a static attribute of a class or an attribute of an object
     * is not empty.
     *
     * @param object|string $haystackClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotEmpty(string $haystackAttributeName, $haystackClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeNotEmpty() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotEmpty(
            static::readAttribute($haystackClassOrObject, $haystackAttributeName),
            $message
        );
    }

    /**
     * Asserts that a value is greater than another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertGreaterThan($expected, $actual, string $message = ''): void
    {
        static::assertThat($actual, static::greaterThan($expected), $message);
    }

    /**
     * Asserts that an attribute is greater than another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeGreaterThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeGreaterThan() is deprecated and will be removed in PHPUnit 9.');

        static::assertGreaterThan(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that a value is greater than or equal to another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertGreaterThanOrEqual($expected, $actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            static::greaterThanOrEqual($expected),
            $message
        );
    }

    /**
     * Asserts that an attribute is greater than or equal to another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeGreaterThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeGreaterThanOrEqual() is deprecated and will be removed in PHPUnit 9.');

        static::assertGreaterThanOrEqual(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that a value is smaller than another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertLessThan($expected, $actual, string $message = ''): void
    {
        static::assertThat($actual, static::lessThan($expected), $message);
    }

    /**
     * Asserts that an attribute is smaller than another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeLessThan($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeLessThan() is deprecated and will be removed in PHPUnit 9.');

        static::assertLessThan(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that a value is smaller than or equal to another value.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertLessThanOrEqual($expected, $actual, string $message = ''): void
    {
        static::assertThat($actual, static::lessThanOrEqual($expected), $message);
    }

    /**
     * Asserts that an attribute is smaller than or equal to another value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeLessThanOrEqual($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeLessThanOrEqual() is deprecated and will be removed in PHPUnit 9.');

        static::assertLessThanOrEqual(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertFileEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertFileEqualsCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertFileEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertFileEqualsIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new IsEqual(
            file_get_contents($expected),
            0.0,
            10,
            $canonicalize,
            $ignoreCase
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
    {
        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new IsEqual(
            file_get_contents($expected),
            0.0,
            10,
            true
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of one file is equal to the contents of another
     * file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
    {
        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new IsEqual(
            file_get_contents($expected),
            0.0,
            10,
            false,
            true
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of one file is not equal to the contents of
     * another file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertFileNotEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertFileNotEqualsCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertFileNotEquals() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertFileNotEqualsIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expected),
                0.0,
                10,
                $canonicalize,
                $ignoreCase
            )
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of one file is not equal to the contents of another
     * file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
    {
        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expected),
                0.0,
                10,
                true
            )
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of one file is not equal to the contents of another
     * file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
    {
        static::assertFileExists($expected, $message);
        static::assertFileExists($actual, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expected),
                0.0,
                10,
                false,
                true
            )
        );

        static::assertThat(file_get_contents($actual), $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertStringEqualsFile() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertStringEqualsFileCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertStringEqualsFile() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertStringEqualsFileIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        static::assertFileExists($expectedFile, $message);

        $constraint = new IsEqual(
            file_get_contents($expectedFile),
            0.0,
            10,
            $canonicalize,
            $ignoreCase
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);

        $constraint = new IsEqual(
            file_get_contents($expectedFile),
            0.0,
            10,
            true
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is equal
     * to the contents of a file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);

        $constraint = new IsEqual(
            file_get_contents($expectedFile),
            0.0,
            10,
            false,
            true
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void
    {
        // @codeCoverageIgnoreStart
        if ($canonicalize) {
            self::createWarning('The optional $canonicalize parameter of assertStringNotEqualsFile() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertStringNotEqualsFileCanonicalizing() instead.');
        }

        if ($ignoreCase) {
            self::createWarning('The optional $ignoreCase parameter of assertStringNotEqualsFile() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertStringNotEqualsFileIgnoringCase() instead.');
        }
        // @codeCoverageIgnoreEnd

        static::assertFileExists($expectedFile, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expectedFile),
                0.0,
                10,
                $canonicalize,
                $ignoreCase
            )
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file (canonicalizing).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expectedFile),
                0.0,
                10,
                true
            )
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that the contents of a string is not equal
     * to the contents of a file (ignoring case).
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);

        $constraint = new LogicalNot(
            new IsEqual(
                file_get_contents($expectedFile),
                0.0,
                10,
                false,
                true
            )
        );

        static::assertThat($actualString, $constraint, $message);
    }

    /**
     * Asserts that a file/dir is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertIsReadable(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new IsReadable, $message);
    }

    /**
     * Asserts that a file/dir exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotIsReadable(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new LogicalNot(new IsReadable), $message);
    }

    /**
     * Asserts that a file/dir exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertIsWritable(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new IsWritable, $message);
    }

    /**
     * Asserts that a file/dir exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotIsWritable(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new LogicalNot(new IsWritable), $message);
    }

    /**
     * Asserts that a directory exists.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryExists(string $directory, string $message = ''): void
    {
        static::assertThat($directory, new DirectoryExists, $message);
    }

    /**
     * Asserts that a directory does not exist.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryNotExists(string $directory, string $message = ''): void
    {
        static::assertThat($directory, new LogicalNot(new DirectoryExists), $message);
    }

    /**
     * Asserts that a directory exists and is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryIsReadable(string $directory, string $message = ''): void
    {
        self::assertDirectoryExists($directory, $message);
        self::assertIsReadable($directory, $message);
    }

    /**
     * Asserts that a directory exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryNotIsReadable(string $directory, string $message = ''): void
    {
        self::assertDirectoryExists($directory, $message);
        self::assertNotIsReadable($directory, $message);
    }

    /**
     * Asserts that a directory exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryIsWritable(string $directory, string $message = ''): void
    {
        self::assertDirectoryExists($directory, $message);
        self::assertIsWritable($directory, $message);
    }

    /**
     * Asserts that a directory exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertDirectoryNotIsWritable(string $directory, string $message = ''): void
    {
        self::assertDirectoryExists($directory, $message);
        self::assertNotIsWritable($directory, $message);
    }

    /**
     * Asserts that a file exists.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileExists(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new FileExists, $message);
    }

    /**
     * Asserts that a file does not exist.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotExists(string $filename, string $message = ''): void
    {
        static::assertThat($filename, new LogicalNot(new FileExists), $message);
    }

    /**
     * Asserts that a file exists and is readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileIsReadable(string $file, string $message = ''): void
    {
        self::assertFileExists($file, $message);
        self::assertIsReadable($file, $message);
    }

    /**
     * Asserts that a file exists and is not readable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotIsReadable(string $file, string $message = ''): void
    {
        self::assertFileExists($file, $message);
        self::assertNotIsReadable($file, $message);
    }

    /**
     * Asserts that a file exists and is writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileIsWritable(string $file, string $message = ''): void
    {
        self::assertFileExists($file, $message);
        self::assertIsWritable($file, $message);
    }

    /**
     * Asserts that a file exists and is not writable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFileNotIsWritable(string $file, string $message = ''): void
    {
        self::assertFileExists($file, $message);
        self::assertNotIsWritable($file, $message);
    }

    /**
     * Asserts that a condition is true.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert true $condition
     */
    public static function assertTrue($condition, string $message = ''): void
    {
        static::assertThat($condition, static::isTrue(), $message);
    }

    /**
     * Asserts that a condition is not true.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !true $condition
     */
    public static function assertNotTrue($condition, string $message = ''): void
    {
        static::assertThat($condition, static::logicalNot(static::isTrue()), $message);
    }

    /**
     * Asserts that a condition is false.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert false $condition
     */
    public static function assertFalse($condition, string $message = ''): void
    {
        static::assertThat($condition, static::isFalse(), $message);
    }

    /**
     * Asserts that a condition is not false.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !false $condition
     */
    public static function assertNotFalse($condition, string $message = ''): void
    {
        static::assertThat($condition, static::logicalNot(static::isFalse()), $message);
    }

    /**
     * Asserts that a variable is null.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert null $actual
     */
    public static function assertNull($actual, string $message = ''): void
    {
        static::assertThat($actual, static::isNull(), $message);
    }

    /**
     * Asserts that a variable is not null.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !null $actual
     */
    public static function assertNotNull($actual, string $message = ''): void
    {
        static::assertThat($actual, static::logicalNot(static::isNull()), $message);
    }

    /**
     * Asserts that a variable is finite.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertFinite($actual, string $message = ''): void
    {
        static::assertThat($actual, static::isFinite(), $message);
    }

    /**
     * Asserts that a variable is infinite.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertInfinite($actual, string $message = ''): void
    {
        static::assertThat($actual, static::isInfinite(), $message);
    }

    /**
     * Asserts that a variable is nan.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNan($actual, string $message = ''): void
    {
        static::assertThat($actual, static::isNan(), $message);
    }

    /**
     * Asserts that a class has a specified attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertClassHasAttribute(string $attributeName, string $className, string $message = ''): void
    {
        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!class_exists($className)) {
            throw InvalidArgumentException::create(2, 'class name');
        }

        static::assertThat($className, new ClassHasAttribute($attributeName), $message);
    }

    /**
     * Asserts that a class does not have a specified attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertClassNotHasAttribute(string $attributeName, string $className, string $message = ''): void
    {
        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!class_exists($className)) {
            throw InvalidArgumentException::create(2, 'class name');
        }

        static::assertThat(
            $className,
            new LogicalNot(
                new ClassHasAttribute($attributeName)
            ),
            $message
        );
    }

    /**
     * Asserts that a class has a specified static attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertClassHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
    {
        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!class_exists($className)) {
            throw InvalidArgumentException::create(2, 'class name');
        }

        static::assertThat(
            $className,
            new ClassHasStaticAttribute($attributeName),
            $message
        );
    }

    /**
     * Asserts that a class does not have a specified static attribute.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertClassNotHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
    {
        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!class_exists($className)) {
            throw InvalidArgumentException::create(2, 'class name');
        }

        static::assertThat(
            $className,
            new LogicalNot(
                new ClassHasStaticAttribute($attributeName)
            ),
            $message
        );
    }

    /**
     * Asserts that an object has a specified attribute.
     *
     * @param object $object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertObjectHasAttribute(string $attributeName, $object, string $message = ''): void
    {
        if (!self::isValidObjectAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!is_object($object)) {
            throw InvalidArgumentException::create(2, 'object');
        }

        static::assertThat(
            $object,
            new ObjectHasAttribute($attributeName),
            $message
        );
    }

    /**
     * Asserts that an object does not have a specified attribute.
     *
     * @param object $object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertObjectNotHasAttribute(string $attributeName, $object, string $message = ''): void
    {
        if (!self::isValidObjectAttributeName($attributeName)) {
            throw InvalidArgumentException::create(1, 'valid attribute name');
        }

        if (!is_object($object)) {
            throw InvalidArgumentException::create(2, 'object');
        }

        static::assertThat(
            $object,
            new LogicalNot(
                new ObjectHasAttribute($attributeName)
            ),
            $message
        );
    }

    /**
     * Asserts that two variables have the same type and value.
     * Used on objects, it asserts that two variables reference
     * the same object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType
     *
     * @psalm-param ExpectedType $expected
     *
     * @psalm-assert =ExpectedType $actual
     */
    public static function assertSame($expected, $actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsIdentical($expected),
            $message
        );
    }

    /**
     * Asserts that a variable and an attribute of an object have the same type
     * and value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeSame() is deprecated and will be removed in PHPUnit 9.');

        static::assertSame(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that two variables do not have the same type and value.
     * Used on objects, it asserts that two variables do not reference
     * the same object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotSame($expected, $actual, string $message = ''): void
    {
        if (is_bool($expected) && is_bool($actual)) {
            static::assertNotEquals($expected, $actual, $message);
        }

        static::assertThat(
            $actual,
            new LogicalNot(
                new IsIdentical($expected)
            ),
            $message
        );
    }

    /**
     * Asserts that a variable and an attribute of an object do not have the
     * same type and value.
     *
     * @param object|string $actualClassOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotSame($expected, string $actualAttributeName, $actualClassOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeNotSame() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotSame(
            $expected,
            static::readAttribute($actualClassOrObject, $actualAttributeName),
            $message
        );
    }

    /**
     * Asserts that a variable is of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType of object
     *
     * @psalm-param class-string<ExpectedType> $expected
     *
     * @psalm-assert =ExpectedType $actual
     */
    public static function assertInstanceOf(string $expected, $actual, string $message = ''): void
    {
        if (!class_exists($expected) && !interface_exists($expected)) {
            throw InvalidArgumentException::create(1, 'class or interface name');
        }

        static::assertThat(
            $actual,
            new IsInstanceOf($expected),
            $message
        );
    }

    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @psalm-param class-string $expected
     */
    public static function assertAttributeInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeInstanceOf() is deprecated and will be removed in PHPUnit 9.');

        static::assertInstanceOf(
            $expected,
            static::readAttribute($classOrObject, $attributeName),
            $message
        );
    }

    /**
     * Asserts that a variable is not of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @psalm-template ExpectedType of object
     *
     * @psalm-param class-string<ExpectedType> $expected
     *
     * @psalm-assert !ExpectedType $actual
     */
    public static function assertNotInstanceOf(string $expected, $actual, string $message = ''): void
    {
        if (!class_exists($expected) && !interface_exists($expected)) {
            throw InvalidArgumentException::create(1, 'class or interface name');
        }

        static::assertThat(
            $actual,
            new LogicalNot(
                new IsInstanceOf($expected)
            ),
            $message
        );
    }

    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     *
     * @psalm-param class-string $expected
     */
    public static function assertAttributeNotInstanceOf(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeNotInstanceOf() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotInstanceOf(
            $expected,
            static::readAttribute($classOrObject, $attributeName),
            $message
        );
    }

    /**
     * Asserts that a variable is of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369
     *
     * @codeCoverageIgnore
     */
    public static function assertInternalType(string $expected, $actual, string $message = ''): void
    {
        self::createWarning(
            sprintf(
                'assertInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use %s() instead.',
                self::assertInternalTypeReplacement($expected, false)
            )
        );

        static::assertThat(
            $actual,
            new IsType($expected),
            $message
        );
    }

    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeInternalType() is deprecated and will be removed in PHPUnit 9.');

        static::assertInternalType(
            $expected,
            static::readAttribute($classOrObject, $attributeName),
            $message
        );
    }

    /**
     * Asserts that a variable is of type array.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert array $actual
     */
    public static function assertIsArray($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_ARRAY),
            $message
        );
    }

    /**
     * Asserts that a variable is of type bool.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert bool $actual
     */
    public static function assertIsBool($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_BOOL),
            $message
        );
    }

    /**
     * Asserts that a variable is of type float.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert float $actual
     */
    public static function assertIsFloat($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_FLOAT),
            $message
        );
    }

    /**
     * Asserts that a variable is of type int.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert int $actual
     */
    public static function assertIsInt($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_INT),
            $message
        );
    }

    /**
     * Asserts that a variable is of type numeric.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert numeric $actual
     */
    public static function assertIsNumeric($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_NUMERIC),
            $message
        );
    }

    /**
     * Asserts that a variable is of type object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert object $actual
     */
    public static function assertIsObject($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_OBJECT),
            $message
        );
    }

    /**
     * Asserts that a variable is of type resource.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert resource $actual
     */
    public static function assertIsResource($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_RESOURCE),
            $message
        );
    }

    /**
     * Asserts that a variable is of type string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert string $actual
     */
    public static function assertIsString($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_STRING),
            $message
        );
    }

    /**
     * Asserts that a variable is of type scalar.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert scalar $actual
     */
    public static function assertIsScalar($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_SCALAR),
            $message
        );
    }

    /**
     * Asserts that a variable is of type callable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert callable $actual
     */
    public static function assertIsCallable($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_CALLABLE),
            $message
        );
    }

    /**
     * Asserts that a variable is of type iterable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert iterable $actual
     */
    public static function assertIsIterable($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new IsType(IsType::TYPE_ITERABLE),
            $message
        );
    }

    /**
     * Asserts that a variable is not of a given type.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369
     *
     * @codeCoverageIgnore
     */
    public static function assertNotInternalType(string $expected, $actual, string $message = ''): void
    {
        self::createWarning(
            sprintf(
                'assertNotInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use %s() instead.',
                self::assertInternalTypeReplacement($expected, true)
            )
        );

        static::assertThat(
            $actual,
            new LogicalNot(
                new IsType($expected)
            ),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type array.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !array $actual
     */
    public static function assertIsNotArray($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_ARRAY)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type bool.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !bool $actual
     */
    public static function assertIsNotBool($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_BOOL)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type float.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !float $actual
     */
    public static function assertIsNotFloat($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_FLOAT)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type int.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !int $actual
     */
    public static function assertIsNotInt($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_INT)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type numeric.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !numeric $actual
     */
    public static function assertIsNotNumeric($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_NUMERIC)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !object $actual
     */
    public static function assertIsNotObject($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_OBJECT)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type resource.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !resource $actual
     */
    public static function assertIsNotResource($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_RESOURCE)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !string $actual
     */
    public static function assertIsNotString($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_STRING)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type scalar.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !scalar $actual
     */
    public static function assertIsNotScalar($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_SCALAR)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type callable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !callable $actual
     */
    public static function assertIsNotCallable($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_CALLABLE)),
            $message
        );
    }

    /**
     * Asserts that a variable is not of type iterable.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-assert !iterable $actual
     */
    public static function assertIsNotIterable($actual, string $message = ''): void
    {
        static::assertThat(
            $actual,
            new LogicalNot(new IsType(IsType::TYPE_ITERABLE)),
            $message
        );
    }

    /**
     * Asserts that an attribute is of a given type.
     *
     * @param object|string $classOrObject
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function assertAttributeNotInternalType(string $expected, string $attributeName, $classOrObject, string $message = ''): void
    {
        self::createWarning('assertAttributeNotInternalType() is deprecated and will be removed in PHPUnit 9.');

        static::assertNotInternalType(
            $expected,
            static::readAttribute($classOrObject, $attributeName),
            $message
        );
    }

    /**
     * Asserts that a string matches a given regular expression.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertRegExp(string $pattern, string $string, string $message = ''): void
    {
        static::assertThat($string, new RegularExpression($pattern), $message);
    }

    /**
     * Asserts that a string does not match a given regular expression.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertNotRegExp(string $pattern, string $string, string $message = ''): void
    {
        static::assertThat(
            $string,
            new LogicalNot(
                new RegularExpression($pattern)
            ),
            $message
        );
    }

    /**
     * Assert that the size of two arrays (or `Countable` or `Traversable` objects)
     * is the same.
     *
     * @param Countable|iterable $expected
     * @param Countable|iterable $actual
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertSameSize($expected, $actual, string $message = ''): void
    {
        if (!$expected instanceof Countable && !is_iterable($expected)) {
            throw InvalidArgumentException::create(1, 'countable or iterable');
        }

        if (!$actual instanceof Countable && !is_iterable($actual)) {
            throw InvalidArgumentException::create(2, 'countable or iterable');
        }

        static::assertThat(
            $actual,
            new SameSize($expected),
            $message
        );
    }

    /**
     * Assert that the size of two arrays (or `Countable` or `Traversable` objects)
     * is not the same.
     *
     * @param Countable|iterable $expected
     * @param Countable|iterable $actual
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertNotSameSize($expected, $actual, string $message = ''): void
    {
        if (!$expected instanceof Countable && !is_iterable($expected)) {
            throw InvalidArgumentException::create(1, 'countable or iterable');
        }

        if (!$actual instanceof Countable && !is_iterable($actual)) {
            throw InvalidArgumentException::create(2, 'countable or iterable');
        }

        static::assertThat(
            $actual,
            new LogicalNot(
                new SameSize($expected)
            ),
            $message
        );
    }

    /**
     * Asserts that a string matches a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringMatchesFormat(string $format, string $string, string $message = ''): void
    {
        static::assertThat($string, new StringMatchesFormatDescription($format), $message);
    }

    /**
     * Asserts that a string does not match a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotMatchesFormat(string $format, string $string, string $message = ''): void
    {
        static::assertThat(
            $string,
            new LogicalNot(
                new StringMatchesFormatDescription($format)
            ),
            $message
        );
    }

    /**
     * Asserts that a string matches a given format file.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
    {
        static::assertFileExists($formatFile, $message);

        static::assertThat(
            $string,
            new StringMatchesFormatDescription(
                file_get_contents($formatFile)
            ),
            $message
        );
    }

    /**
     * Asserts that a string does not match a given format string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
    {
        static::assertFileExists($formatFile, $message);

        static::assertThat(
            $string,
            new LogicalNot(
                new StringMatchesFormatDescription(
                    file_get_contents($formatFile)
                )
            ),
            $message
        );
    }

    /**
     * Asserts that a string starts with a given prefix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringStartsWith(string $prefix, string $string, string $message = ''): void
    {
        static::assertThat($string, new StringStartsWith($prefix), $message);
    }

    /**
     * Asserts that a string starts not with a given prefix.
     *
     * @param string $prefix
     * @param string $string
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringStartsNotWith($prefix, $string, string $message = ''): void
    {
        static::assertThat(
            $string,
            new LogicalNot(
                new StringStartsWith($prefix)
            ),
            $message
        );
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringContainsString(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = new StringContains($needle, false);

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = new StringContains($needle, true);

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotContainsString(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = new LogicalNot(new StringContains($needle));

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringNotContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = new LogicalNot(new StringContains($needle, true));

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * Asserts that a string ends with a given suffix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringEndsWith(string $suffix, string $string, string $message = ''): void
    {
        static::assertThat($string, new StringEndsWith($suffix), $message);
    }

    /**
     * Asserts that a string ends not with a given suffix.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertStringEndsNotWith(string $suffix, string $string, string $message = ''): void
    {
        static::assertThat(
            $string,
            new LogicalNot(
                new StringEndsWith($suffix)
            ),
            $message
        );
    }

    /**
     * Asserts that two XML files are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        $expected = Xml::loadFile($expectedFile);
        $actual   = Xml::loadFile($actualFile);

        static::assertEquals($expected, $actual, $message);
    }

    /**
     * Asserts that two XML files are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        $expected = Xml::loadFile($expectedFile);
        $actual   = Xml::loadFile($actualFile);

        static::assertNotEquals($expected, $actual, $message);
    }

    /**
     * Asserts that two XML documents are equal.
     *
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlStringEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
    {
        $expected = Xml::loadFile($expectedFile);
        $actual   = Xml::load($actualXml);

        static::assertEquals($expected, $actual, $message);
    }

    /**
     * Asserts that two XML documents are not equal.
     *
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlStringNotEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void
    {
        $expected = Xml::loadFile($expectedFile);
        $actual   = Xml::load($actualXml);

        static::assertNotEquals($expected, $actual, $message);
    }

    /**
     * Asserts that two XML documents are equal.
     *
     * @param DOMDocument|string $expectedXml
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
    {
        $expected = Xml::load($expectedXml);
        $actual   = Xml::load($actualXml);

        static::assertEquals($expected, $actual, $message);
    }

    /**
     * Asserts that two XML documents are not equal.
     *
     * @param DOMDocument|string $expectedXml
     * @param DOMDocument|string $actualXml
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, string $message = ''): void
    {
        $expected = Xml::load($expectedXml);
        $actual   = Xml::load($actualXml);

        static::assertNotEquals($expected, $actual, $message);
    }

    /**
     * Asserts that a hierarchy of DOMElements matches.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws AssertionFailedError
     * @throws ExpectationFailedException
     */
    public static function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, bool $checkAttributes = false, string $message = ''): void
    {
        $expectedElement = Xml::import($expectedElement);
        $actualElement   = Xml::import($actualElement);

        static::assertSame(
            $expectedElement->tagName,
            $actualElement->tagName,
            $message
        );

        if ($checkAttributes) {
            static::assertSame(
                $expectedElement->attributes->length,
                $actualElement->attributes->length,
                sprintf(
                    '%s%sNumber of attributes on node "%s" does not match',
                    $message,
                    !empty($message) ? "\n" : '',
                    $expectedElement->tagName
                )
            );

            for ($i = 0; $i < $expectedElement->attributes->length; $i++) {
                $expectedAttribute = $expectedElement->attributes->item($i);
                $actualAttribute   = $actualElement->attributes->getNamedItem($expectedAttribute->name);

                assert($expectedAttribute instanceof DOMAttr);

                if (!$actualAttribute) {
                    static::fail(
                        sprintf(
                            '%s%sCould not find attribute "%s" on node "%s"',
                            $message,
                            !empty($message) ? "\n" : '',
                            $expectedAttribute->name,
                            $expectedElement->tagName
                        )
                    );
                }
            }
        }

        Xml::removeCharacterDataNodes($expectedElement);
        Xml::removeCharacterDataNodes($actualElement);

        static::assertSame(
            $expectedElement->childNodes->length,
            $actualElement->childNodes->length,
            sprintf(
                '%s%sNumber of child nodes of "%s" differs',
                $message,
                !empty($message) ? "\n" : '',
                $expectedElement->tagName
            )
        );

        for ($i = 0; $i < $expectedElement->childNodes->length; $i++) {
            static::assertEqualXMLStructure(
                $expectedElement->childNodes->item($i),
                $actualElement->childNodes->item($i),
                $checkAttributes,
                $message
            );
        }
    }

    /**
     * Evaluates a PHPUnit\Framework\Constraint matcher object.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertThat($value, Constraint $constraint, string $message = ''): void
    {
        self::$count += count($constraint);

        $constraint->evaluate($value, $message);
    }

    /**
     * Asserts that a string is a valid JSON string.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJson(string $actualJson, string $message = ''): void
    {
        static::assertThat($actualJson, static::isJson(), $message);
    }

    /**
     * Asserts that two given JSON encoded objects or arrays are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonStringEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void
    {
        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        static::assertThat($actualJson, new JsonMatches($expectedJson), $message);
    }

    /**
     * Asserts that two given JSON encoded objects or arrays are not equal.
     *
     * @param string $expectedJson
     * @param string $actualJson
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, string $message = ''): void
    {
        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        static::assertThat(
            $actualJson,
            new LogicalNot(
                new JsonMatches($expectedJson)
            ),
            $message
        );
    }

    /**
     * Asserts that the generated JSON encoded object and the content of the given file are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);
        $expectedJson = file_get_contents($expectedFile);

        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        static::assertThat($actualJson, new JsonMatches($expectedJson), $message);
    }

    /**
     * Asserts that the generated JSON encoded object and the content of the given file are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);
        $expectedJson = file_get_contents($expectedFile);

        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        static::assertThat(
            $actualJson,
            new LogicalNot(
                new JsonMatches($expectedJson)
            ),
            $message
        );
    }

    /**
     * Asserts that two JSON files are equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);
        static::assertFileExists($actualFile, $message);

        $actualJson   = file_get_contents($actualFile);
        $expectedJson = file_get_contents($expectedFile);

        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        $constraintExpected = new JsonMatches(
            $expectedJson
        );

        $constraintActual = new JsonMatches($actualJson);

        static::assertThat($expectedJson, $constraintActual, $message);
        static::assertThat($actualJson, $constraintExpected, $message);
    }

    /**
     * Asserts that two JSON files are not equal.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public static function assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
    {
        static::assertFileExists($expectedFile, $message);
        static::assertFileExists($actualFile, $message);

        $actualJson   = file_get_contents($actualFile);
        $expectedJson = file_get_contents($expectedFile);

        static::assertJson($expectedJson, $message);
        static::assertJson($actualJson, $message);

        $constraintExpected = new JsonMatches(
            $expectedJson
        );

        $constraintActual = new JsonMatches($actualJson);

        static::assertThat($expectedJson, new LogicalNot($constraintActual), $message);
        static::assertThat($actualJson, new LogicalNot($constraintExpected), $message);
    }

    /**
     * @throws Exception
     */
    public static function logicalAnd(): LogicalAnd
    {
        $constraints = func_get_args();

        $constraint = new LogicalAnd;
        $constraint->setConstraints($constraints);

        return $constraint;
    }

    public static function logicalOr(): LogicalOr
    {
        $constraints = func_get_args();

        $constraint = new LogicalOr;
        $constraint->setConstraints($constraints);

        return $constraint;
    }

    public static function logicalNot(Constraint $constraint): LogicalNot
    {
        return new LogicalNot($constraint);
    }

    public static function logicalXor(): LogicalXor
    {
        $constraints = func_get_args();

        $constraint = new LogicalXor;
        $constraint->setConstraints($constraints);

        return $constraint;
    }

    public static function anything(): IsAnything
    {
        return new IsAnything;
    }

    public static function isTrue(): IsTrue
    {
        return new IsTrue;
    }

    /**
     * @psalm-template CallbackInput of mixed
     *
     * @psalm-param callable(CallbackInput $callback): bool $callback
     *
     * @psalm-return Callback<CallbackInput>
     */
    public static function callback(callable $callback): Callback
    {
        return new Callback($callback);
    }

    public static function isFalse(): IsFalse
    {
        return new IsFalse;
    }

    public static function isJson(): IsJson
    {
        return new IsJson;
    }

    public static function isNull(): IsNull
    {
        return new IsNull;
    }

    public static function isFinite(): IsFinite
    {
        return new IsFinite;
    }

    public static function isInfinite(): IsInfinite
    {
        return new IsInfinite;
    }

    public static function isNan(): IsNan
    {
        return new IsNan;
    }

    /**
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function attribute(Constraint $constraint, string $attributeName): Attribute
    {
        self::createWarning('attribute() is deprecated and will be removed in PHPUnit 9.');

        return new Attribute($constraint, $attributeName);
    }

    /**
     * @deprecated Use containsEqual() or containsIdentical() instead
     */
    public static function contains($value, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): TraversableContains
    {
        return new TraversableContains($value, $checkForObjectIdentity, $checkForNonObjectIdentity);
    }

    public static function containsEqual($value): TraversableContainsEqual
    {
        return new TraversableContainsEqual($value);
    }

    public static function containsIdentical($value): TraversableContainsIdentical
    {
        return new TraversableContainsIdentical($value);
    }

    public static function containsOnly(string $type): TraversableContainsOnly
    {
        return new TraversableContainsOnly($type);
    }

    public static function containsOnlyInstancesOf(string $className): TraversableContainsOnly
    {
        return new TraversableContainsOnly($className, false);
    }

    /**
     * @param int|string $key
     */
    public static function arrayHasKey($key): ArrayHasKey
    {
        return new ArrayHasKey($key);
    }

    public static function equalTo($value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): IsEqual
    {
        return new IsEqual($value, $delta, $maxDepth, $canonicalize, $ignoreCase);
    }

    /**
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function attributeEqualTo(string $attributeName, $value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): Attribute
    {
        self::createWarning('attributeEqualTo() is deprecated and will be removed in PHPUnit 9.');

        return static::attribute(
            static::equalTo(
                $value,
                $delta,
                $maxDepth,
                $canonicalize,
                $ignoreCase
            ),
            $attributeName
        );
    }

    public static function isEmpty(): IsEmpty
    {
        return new IsEmpty;
    }

    public static function isWritable(): IsWritable
    {
        return new IsWritable;
    }

    public static function isReadable(): IsReadable
    {
        return new IsReadable;
    }

    public static function directoryExists(): DirectoryExists
    {
        return new DirectoryExists;
    }

    public static function fileExists(): FileExists
    {
        return new FileExists;
    }

    public static function greaterThan($value): GreaterThan
    {
        return new GreaterThan($value);
    }

    public static function greaterThanOrEqual($value): LogicalOr
    {
        return static::logicalOr(
            new IsEqual($value),
            new GreaterThan($value)
        );
    }

    public static function classHasAttribute(string $attributeName): ClassHasAttribute
    {
        return new ClassHasAttribute($attributeName);
    }

    public static function classHasStaticAttribute(string $attributeName): ClassHasStaticAttribute
    {
        return new ClassHasStaticAttribute($attributeName);
    }

    public static function objectHasAttribute($attributeName): ObjectHasAttribute
    {
        return new ObjectHasAttribute($attributeName);
    }

    public static function identicalTo($value): IsIdentical
    {
        return new IsIdentical($value);
    }

    public static function isInstanceOf(string $className): IsInstanceOf
    {
        return new IsInstanceOf($className);
    }

    public static function isType(string $type): IsType
    {
        return new IsType($type);
    }

    public static function lessThan($value): LessThan
    {
        return new LessThan($value);
    }

    public static function lessThanOrEqual($value): LogicalOr
    {
        return static::logicalOr(
            new IsEqual($value),
            new LessThan($value)
        );
    }

    public static function matchesRegularExpression(string $pattern): RegularExpression
    {
        return new RegularExpression($pattern);
    }

    public static function matches(string $string): StringMatchesFormatDescription
    {
        return new StringMatchesFormatDescription($string);
    }

    public static function stringStartsWith($prefix): StringStartsWith
    {
        return new StringStartsWith($prefix);
    }

    public static function stringContains(string $string, bool $case = true): StringContains
    {
        return new StringContains($string, $case);
    }

    public static function stringEndsWith(string $suffix): StringEndsWith
    {
        return new StringEndsWith($suffix);
    }

    public static function countOf(int $count): Count
    {
        return new Count($count);
    }

    /**
     * Fails a test with the given message.
     *
     * @throws AssertionFailedError
     *
     * @psalm-return never-return
     */
    public static function fail(string $message = ''): void
    {
        self::$count++;

        throw new AssertionFailedError($message);
    }

    /**
     * Returns the value of an attribute of a class or an object.
     * This also works for attributes that are declared protected or private.
     *
     * @param object|string $classOrObject
     *
     * @throws Exception
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function readAttribute($classOrObject, string $attributeName)
    {
        self::createWarning('readAttribute() is deprecated and will be removed in PHPUnit 9.');

        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(2, 'valid attribute name');
        }

        if (is_string($classOrObject)) {
            if (!class_exists($classOrObject)) {
                throw InvalidArgumentException::create(
                    1,
                    'class name'
                );
            }

            return static::getStaticAttribute(
                $classOrObject,
                $attributeName
            );
        }

        if (is_object($classOrObject)) {
            return static::getObjectAttribute(
                $classOrObject,
                $attributeName
            );
        }

        throw InvalidArgumentException::create(
            1,
            'class name or object'
        );
    }

    /**
     * Returns the value of a static attribute.
     * This also works for attributes that are declared protected or private.
     *
     * @throws Exception
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function getStaticAttribute(string $className, string $attributeName)
    {
        self::createWarning('getStaticAttribute() is deprecated and will be removed in PHPUnit 9.');

        if (!class_exists($className)) {
            throw InvalidArgumentException::create(1, 'class name');
        }

        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(2, 'valid attribute name');
        }

        try {
            $class = new ReflectionClass($className);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        while ($class) {
            $attributes = $class->getStaticProperties();

            if (array_key_exists($attributeName, $attributes)) {
                return $attributes[$attributeName];
            }

            $class = $class->getParentClass();
        }

        throw new Exception(
            sprintf(
                'Attribute "%s" not found in class.',
                $attributeName
            )
        );
    }

    /**
     * Returns the value of an object's attribute.
     * This also works for attributes that are declared protected or private.
     *
     * @param object $object
     *
     * @throws Exception
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
     *
     * @codeCoverageIgnore
     */
    public static function getObjectAttribute($object, string $attributeName)
    {
        self::createWarning('getObjectAttribute() is deprecated and will be removed in PHPUnit 9.');

        if (!is_object($object)) {
            throw InvalidArgumentException::create(1, 'object');
        }

        if (!self::isValidClassAttributeName($attributeName)) {
            throw InvalidArgumentException::create(2, 'valid attribute name');
        }

        $reflector = new ReflectionObject($object);

        do {
            try {
                $attribute = $reflector->getProperty($attributeName);

                if (!$attribute || $attribute->isPublic()) {
                    return $object->{$attributeName};
                }

                $attribute->setAccessible(true);
                $value = $attribute->getValue($object);
                $attribute->setAccessible(false);

                return $value;
            } catch (ReflectionException $e) {
            }
        } while ($reflector = $reflector->getParentClass());

        throw new Exception(
            sprintf(
                'Attribute "%s" not found in object.',
                $attributeName
            )
        );
    }

    /**
     * Mark the test as incomplete.
     *
     * @throws IncompleteTestError
     *
     * @psalm-return never-return
     */
    public static function markTestIncomplete(string $message = ''): void
    {
        throw new IncompleteTestError($message);
    }

    /**
     * Mark the test as skipped.
     *
     * @throws SkippedTestError
     * @throws SyntheticSkippedError
     *
     * @psalm-return never-return
     */
    public static function markTestSkipped(string $message = ''): void
    {
        if ($hint = self::detectLocationHint($message)) {
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
            array_unshift($trace, $hint);

            throw new SyntheticSkippedError($hint['message'], 0, $hint['file'], (int) $hint['line'], $trace);
        }

        throw new SkippedTestError($message);
    }

    /**
     * Return the current assertion count.
     */
    public static function getCount(): int
    {
        return self::$count;
    }

    /**
     * Reset the assertion counter.
     */
    public static function resetCount(): void
    {
        self::$count = 0;
    }

    private static function detectLocationHint(string $message): ?array
    {
        $hint  = null;
        $lines = preg_split('/\r\n|\r|\n/', $message);

        while (strpos($lines[0], '__OFFSET') !== false) {
            $offset = explode('=', array_shift($lines));

            if ($offset[0] === '__OFFSET_FILE') {
                $hint['file'] = $offset[1];
            }

            if ($offset[0] === '__OFFSET_LINE') {
                $hint['line'] = $offset[1];
            }
        }

        if ($hint) {
            $hint['message'] = implode(PHP_EOL, $lines);
        }

        return $hint;
    }

    private static function isValidObjectAttributeName(string $attributeName): bool
    {
        return (bool) preg_match('/[^\x00-\x1f\x7f-\x9f]+/', $attributeName);
    }

    private static function isValidClassAttributeName(string $attributeName): bool
    {
        return (bool) preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName);
    }

    /**
     * @codeCoverageIgnore
     */
    private static function createWarning(string $warning): void
    {
        foreach (debug_backtrace() as $step) {
            if (isset($step['object']) && $step['object'] instanceof TestCase) {
                assert($step['object'] instanceof TestCase);

                $step['object']->addWarning($warning);

                break;
            }
        }
    }

    /**
     * @throws Exception
     */
    private static function assertInternalTypeReplacement(string $type, bool $not): string
    {
        switch ($type) {
            case 'numeric':
                return 'assertIs' . ($not ? 'Not' : '') . 'Numeric';

            case 'integer':
            case 'int':
                return 'assertIs' . ($not ? 'Not' : '') . 'Int';

            case 'double':
            case 'float':
            case 'real':
                return 'assertIs' . ($not ? 'Not' : '') . 'Float';

            case 'string':
                return 'assertIs' . ($not ? 'Not' : '') . 'String';

            case 'boolean':
            case 'bool':
                return 'assertIs' . ($not ? 'Not' : '') . 'Bool';

            case 'null':
                return 'assert' . ($not ? 'Not' : '') . 'Null';

            case 'array':
                return 'assertIs' . ($not ? 'Not' : '') . 'Array';

            case 'object':
                return 'assertIs' . ($not ? 'Not' : '') . 'Object';

            case 'resource':
                return 'assertIs' . ($not ? 'Not' : '') . 'Resource';

            case 'scalar':
                return 'assertIs' . ($not ? 'Not' : '') . 'Scalar';

            case 'callable':
                return 'assertIs' . ($not ? 'Not' : '') . 'Callable';

            case 'iterable':
                return 'assertIs' . ($not ? 'Not' : '') . 'Iterable';
        }

        throw new Exception(
            sprintf(
                '"%s" is not a type supported by assertInternalType() / assertNotInternalType()',
                $type
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface SkippedTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use Countable;

/**
 * A Test can be run and collect its results.
 */
interface Test extends Countable
{
    /**
     * Runs a test and collects its result in a TestResult instance.
     */
    public function run(TestResult $result = null): TestResult;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function call_user_func;
use function class_exists;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MockClass implements MockType
{
    /**
     * @var string
     */
    private $classCode;

    /**
     * @var string
     */
    private $mockName;

    /**
     * @var ConfigurableMethod[]
     */
    private $configurableMethods;

    public function __construct(string $classCode, string $mockName, array $configurableMethods)
    {
        $this->classCode           = $classCode;
        $this->mockName            = $mockName;
        $this->configurableMethods = $configurableMethods;
    }

    public function generate(): string
    {
        if (!class_exists($this->mockName, false)) {
            eval($this->classCode);

            call_user_func(
                [
                    $this->mockName,
                    '__phpunit_initConfigurableMethods',
                ],
                ...$this->configurableMethods
            );
        }

        return $this->mockName;
    }

    public function getClassCode(): string
    {
        return $this->classCode;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function is_string;
use function sprintf;
use function strtolower;
use PHPUnit\Framework\Constraint\Constraint;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MethodNameConstraint extends Constraint
{
    /**
     * @var string
     */
    private $methodName;

    public function __construct(string $methodName)
    {
        $this->methodName = $methodName;
    }

    public function toString(): string
    {
        return sprintf(
            'is "%s"',
            $this->methodName
        );
    }

    protected function matches($other): bool
    {
        if (!is_string($other)) {
            return false;
        }

        return strtolower($this->methodName) === strtolower($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use PHPUnit\Framework\MockObject\Builder\InvocationMocker as BuilderInvocationMocker;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;

/**
 * @method BuilderInvocationMocker method($constraint)
 */
interface MockObject extends Stub
{
    public function __phpunit_setOriginalObject($originalObject): void;

    public function __phpunit_verify(bool $unsetInvocationMocker = true): void;

    public function expects(InvocationOrder $invocationRule): BuilderInvocationMocker;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface MockType
{
    public function generate(): string;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function array_map;
use function implode;
use function is_object;
use function ltrim;
use function sprintf;
use function strpos;
use function strtolower;
use function substr;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Util\Type;
use SebastianBergmann\Exporter\Exporter;
use stdClass;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Invocation implements SelfDescribing
{
    /**
     * @var string
     */
    private $className;

    /**
     * @var string
     */
    private $methodName;

    /**
     * @var array
     */
    private $parameters;

    /**
     * @var string
     */
    private $returnType;

    /**
     * @var bool
     */
    private $isReturnTypeNullable = false;

    /**
     * @var bool
     */
    private $proxiedCall;

    /**
     * @var object
     */
    private $object;

    public function __construct(string $className, string $methodName, array $parameters, string $returnType, object $object, bool $cloneObjects = false, bool $proxiedCall = false)
    {
        $this->className   = $className;
        $this->methodName  = $methodName;
        $this->parameters  = $parameters;
        $this->object      = $object;
        $this->proxiedCall = $proxiedCall;

        $returnType = ltrim($returnType, ': ');

        if (strtolower($methodName) === '__tostring') {
            $returnType = 'string';
        }

        if (strpos($returnType, '?') === 0) {
            $returnType                 = substr($returnType, 1);
            $this->isReturnTypeNullable = true;
        }

        $this->returnType = $returnType;

        if (!$cloneObjects) {
            return;
        }

        foreach ($this->parameters as $key => $value) {
            if (is_object($value)) {
                $this->parameters[$key] = $this->cloneObject($value);
            }
        }
    }

    public function getClassName(): string
    {
        return $this->className;
    }

    public function getMethodName(): string
    {
        return $this->methodName;
    }

    public function getParameters(): array
    {
        return $this->parameters;
    }

    /**
     * @throws RuntimeException
     *
     * @return mixed Mocked return value
     */
    public function generateReturnValue()
    {
        if ($this->isReturnTypeNullable || $this->proxiedCall) {
            return;
        }

        switch (strtolower($this->returnType)) {
            case '':
            case 'void':
                return;

            case 'string':
                return '';

            case 'float':
                return 0.0;

            case 'int':
                return 0;

            case 'bool':
                return false;

            case 'array':
                return [];

            case 'object':
                return new stdClass;

            case 'callable':
            case 'closure':
                return static function (): void
                {
                };

            case 'traversable':
            case 'generator':
            case 'iterable':
                $generator = static function ()
                {
                    yield from [];
                };

                return $generator();

            default:
                $generator = new Generator;

                return $generator->getMock($this->returnType, [], [], '', false);
        }
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            '%s::%s(%s)%s',
            $this->className,
            $this->methodName,
            implode(
                ', ',
                array_map(
                    [$exporter, 'shortenedExport'],
                    $this->parameters
                )
            ),
            $this->returnType ? sprintf(': %s', $this->returnType) : ''
        );
    }

    public function getObject(): object
    {
        return $this->object;
    }

    private function cloneObject(object $original): object
    {
        if (Type::isCloneable($original)) {
            return clone $original;
        }

        return $original;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function array_diff;
use function array_merge;
use function sprintf;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionException;

/**
 * @psalm-template MockedType
 */
final class MockBuilder
{
    /**
     * @var TestCase
     */
    private $testCase;

    /**
     * @var string
     */
    private $type;

    /**
     * @var null|string[]
     */
    private $methods = [];

    /**
     * @var bool
     */
    private $emptyMethodsArray = false;

    /**
     * @var string
     */
    private $mockClassName = '';

    /**
     * @var array
     */
    private $constructorArgs = [];

    /**
     * @var bool
     */
    private $originalConstructor = true;

    /**
     * @var bool
     */
    private $originalClone = true;

    /**
     * @var bool
     */
    private $autoload = true;

    /**
     * @var bool
     */
    private $cloneArguments = false;

    /**
     * @var bool
     */
    private $callOriginalMethods = false;

    /**
     * @var ?object
     */
    private $proxyTarget;

    /**
     * @var bool
     */
    private $allowMockingUnknownTypes = true;

    /**
     * @var bool
     */
    private $returnValueGeneration = true;

    /**
     * @var Generator
     */
    private $generator;

    /**
     * @param string|string[] $type
     *
     * @psalm-param class-string<MockedType>|string|string[] $type
     */
    public function __construct(TestCase $testCase, $type)
    {
        $this->testCase  = $testCase;
        $this->type      = $type;
        $this->generator = new Generator;
    }

    /**
     * Creates a mock object using a fluent interface.
     *
     * @throws RuntimeException
     *
     * @psalm-return MockObject&MockedType
     */
    public function getMock(): MockObject
    {
        $object = $this->generator->getMock(
            $this->type,
            !$this->emptyMethodsArray ? $this->methods : null,
            $this->constructorArgs,
            $this->mockClassName,
            $this->originalConstructor,
            $this->originalClone,
            $this->autoload,
            $this->cloneArguments,
            $this->callOriginalMethods,
            $this->proxyTarget,
            $this->allowMockingUnknownTypes,
            $this->returnValueGeneration
        );

        $this->testCase->registerMockObject($object);

        return $object;
    }

    /**
     * Creates a mock object for an abstract class using a fluent interface.
     *
     * @throws \PHPUnit\Framework\Exception
     * @throws RuntimeException
     *
     * @psalm-return MockObject&MockedType
     */
    public function getMockForAbstractClass(): MockObject
    {
        $object = $this->generator->getMockForAbstractClass(
            $this->type,
            $this->constructorArgs,
            $this->mockClassName,
            $this->originalConstructor,
            $this->originalClone,
            $this->autoload,
            $this->methods,
            $this->cloneArguments
        );

        $this->testCase->registerMockObject($object);

        return $object;
    }

    /**
     * Creates a mock object for a trait using a fluent interface.
     *
     * @throws \PHPUnit\Framework\Exception
     * @throws RuntimeException
     *
     * @psalm-return MockObject&MockedType
     */
    public function getMockForTrait(): MockObject
    {
        $object = $this->generator->getMockForTrait(
            $this->type,
            $this->constructorArgs,
            $this->mockClassName,
            $this->originalConstructor,
            $this->originalClone,
            $this->autoload,
            $this->methods,
            $this->cloneArguments
        );

        $this->testCase->registerMockObject($object);

        return $object;
    }

    /**
     * Specifies the subset of methods to mock. Default is to mock none of them.
     *
     * @deprecated https://github.com/sebastianbergmann/phpunit/pull/3687
     *
     * @return $this
     */
    public function setMethods(?array $methods = null): self
    {
        if ($methods === null) {
            $this->methods = $methods;
        } else {
            $this->methods = array_merge($this->methods ?? [], $methods);
        }

        return $this;
    }

    /**
     * Specifies the subset of methods to mock, requiring each to exist in the class.
     *
     * @param string[] $methods
     *
     * @throws RuntimeException
     *
     * @return $this
     */
    public function onlyMethods(array $methods): self
    {
        if (empty($methods)) {
            $this->emptyMethodsArray = true;

            return $this;
        }

        try {
            $reflector = new ReflectionClass($this->type);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        foreach ($methods as $method) {
            if (!$reflector->hasMethod($method)) {
                throw new RuntimeException(
                    sprintf(
                        'Trying to set mock method "%s" with onlyMethods, but it does not exist in class "%s". Use addMethods() for methods that don\'t exist in the class.',
                        $method,
                        $this->type
                    )
                );
            }
        }

        $this->methods = array_merge($this->methods ?? [], $methods);

        return $this;
    }

    /**
     * Specifies methods that don't exist in the class which you want to mock.
     *
     * @param string[] $methods
     *
     * @throws RuntimeException
     *
     * @return $this
     */
    public function addMethods(array $methods): self
    {
        if (empty($methods)) {
            $this->emptyMethodsArray = true;

            return $this;
        }

        try {
            $reflector = new ReflectionClass($this->type);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        foreach ($methods as $method) {
            if ($reflector->hasMethod($method)) {
                throw new RuntimeException(
                    sprintf(
                        'Trying to set mock method "%s" with addMethods(), but it exists in class "%s". Use onlyMethods() for methods that exist in the class.',
                        $method,
                        $this->type
                    )
                );
            }
        }

        $this->methods = array_merge($this->methods ?? [], $methods);

        return $this;
    }

    /**
     * Specifies the subset of methods to not mock. Default is to mock all of them.
     */
    public function setMethodsExcept(array $methods = []): self
    {
        return $this->setMethods(
            array_diff(
                $this->generator->getClassMethods($this->type),
                $methods
            )
        );
    }

    /**
     * Specifies the arguments for the constructor.
     *
     * @return $this
     */
    public function setConstructorArgs(array $args): self
    {
        $this->constructorArgs = $args;

        return $this;
    }

    /**
     * Specifies the name for the mock class.
     *
     * @return $this
     */
    public function setMockClassName(string $name): self
    {
        $this->mockClassName = $name;

        return $this;
    }

    /**
     * Disables the invocation of the original constructor.
     *
     * @return $this
     */
    public function disableOriginalConstructor(): self
    {
        $this->originalConstructor = false;

        return $this;
    }

    /**
     * Enables the invocation of the original constructor.
     *
     * @return $this
     */
    public function enableOriginalConstructor(): self
    {
        $this->originalConstructor = true;

        return $this;
    }

    /**
     * Disables the invocation of the original clone constructor.
     *
     * @return $this
     */
    public function disableOriginalClone(): self
    {
        $this->originalClone = false;

        return $this;
    }

    /**
     * Enables the invocation of the original clone constructor.
     *
     * @return $this
     */
    public function enableOriginalClone(): self
    {
        $this->originalClone = true;

        return $this;
    }

    /**
     * Disables the use of class autoloading while creating the mock object.
     *
     * @return $this
     */
    public function disableAutoload(): self
    {
        $this->autoload = false;

        return $this;
    }

    /**
     * Enables the use of class autoloading while creating the mock object.
     *
     * @return $this
     */
    public function enableAutoload(): self
    {
        $this->autoload = true;

        return $this;
    }

    /**
     * Disables the cloning of arguments passed to mocked methods.
     *
     * @return $this
     */
    public function disableArgumentCloning(): self
    {
        $this->cloneArguments = false;

        return $this;
    }

    /**
     * Enables the cloning of arguments passed to mocked methods.
     *
     * @return $this
     */
    public function enableArgumentCloning(): self
    {
        $this->cloneArguments = true;

        return $this;
    }

    /**
     * Enables the invocation of the original methods.
     *
     * @return $this
     */
    public function enableProxyingToOriginalMethods(): self
    {
        $this->callOriginalMethods = true;

        return $this;
    }

    /**
     * Disables the invocation of the original methods.
     *
     * @return $this
     */
    public function disableProxyingToOriginalMethods(): self
    {
        $this->callOriginalMethods = false;
        $this->proxyTarget         = null;

        return $this;
    }

    /**
     * Sets the proxy target.
     *
     * @return $this
     */
    public function setProxyTarget(object $object): self
    {
        $this->proxyTarget = $object;

        return $this;
    }

    /**
     * @return $this
     */
    public function allowMockingUnknownTypes(): self
    {
        $this->allowMockingUnknownTypes = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function disallowMockingUnknownTypes(): self
    {
        $this->allowMockingUnknownTypes = false;

        return $this;
    }

    /**
     * @return $this
     */
    public function enableAutoReturnValueGeneration(): self
    {
        $this->returnValueGeneration = true;

        return $this;
    }

    /**
     * @return $this
     */
    public function disableAutoReturnValueGeneration(): self
    {
        $this->returnValueGeneration = false;

        return $this;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function array_key_exists;
use function array_values;
use function strtolower;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MockMethodSet
{
    /**
     * @var MockMethod[]
     */
    private $methods = [];

    public function addMethods(MockMethod ...$methods): void
    {
        foreach ($methods as $method) {
            $this->methods[strtolower($method->getName())] = $method;
        }
    }

    /**
     * @return MockMethod[]
     */
    public function asArray(): array
    {
        return array_values($this->methods);
    }

    public function hasMethod(string $methodName): bool
    {
        return array_key_exists(strtolower($methodName), $this->methods);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function is_string;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\MethodNameConstraint;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MethodName
{
    /**
     * @var Constraint
     */
    private $constraint;

    /**
     * @param Constraint|string $constraint
     *
     * @throws InvalidArgumentException
     */
    public function __construct($constraint)
    {
        if (is_string($constraint)) {
            $constraint = new MethodNameConstraint($constraint);
        }

        if (!$constraint instanceof Constraint) {
            throw InvalidArgumentException::create(1, 'PHPUnit\Framework\Constraint\Constraint object or string');
        }

        $this->constraint = $constraint;
    }

    public function toString(): string
    {
        return 'method name ' . $this->constraint->toString();
    }

    /**
     * @throws \PHPUnit\Framework\ExpectationFailedException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function matches(BaseInvocation $invocation): bool
    {
        return $this->matchesName($invocation->getMethodName());
    }

    public function matchesName(string $methodName): bool
    {
        return $this->constraint->evaluate($methodName, '', true);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function count;
use function gettype;
use function is_iterable;
use function sprintf;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\InvalidParameterGroupException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ConsecutiveParameters implements ParametersRule
{
    /**
     * @var array
     */
    private $parameterGroups = [];

    /**
     * @var array
     */
    private $invocations = [];

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct(array $parameterGroups)
    {
        foreach ($parameterGroups as $index => $parameters) {
            if (!is_iterable($parameters)) {
                throw new InvalidParameterGroupException(
                    sprintf(
                        'Parameter group #%d must be an array or Traversable, got %s',
                        $index,
                        gettype($parameters)
                    )
                );
            }

            foreach ($parameters as $parameter) {
                if (!$parameter instanceof Constraint) {
                    $parameter = new IsEqual($parameter);
                }

                $this->parameterGroups[$index][] = $parameter;
            }
        }
    }

    public function toString(): string
    {
        return 'with consecutive parameters';
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function apply(BaseInvocation $invocation): void
    {
        $this->invocations[] = $invocation;
        $callIndex           = count($this->invocations) - 1;

        $this->verifyInvocation($invocation, $callIndex);
    }

    /**
     * @throws \PHPUnit\Framework\ExpectationFailedException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function verify(): void
    {
        foreach ($this->invocations as $callIndex => $invocation) {
            $this->verifyInvocation($invocation, $callIndex);
        }
    }

    /**
     * Verify a single invocation.
     *
     * @param int $callIndex
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    private function verifyInvocation(BaseInvocation $invocation, $callIndex): void
    {
        if (!isset($this->parameterGroups[$callIndex])) {
            // no parameter assertion for this call index
            return;
        }

        if ($invocation === null) {
            throw new ExpectationFailedException(
                'Mocked method does not exist.'
            );
        }

        $parameters = $this->parameterGroups[$callIndex];

        if (count($invocation->getParameters()) < count($parameters)) {
            throw new ExpectationFailedException(
                sprintf(
                    'Parameter count for invocation %s is too low.',
                    $invocation->toString()
                )
            );
        }

        foreach ($parameters as $i => $parameter) {
            $parameter->evaluate(
                $invocation->getParameters()[$i],
                sprintf(
                    'Parameter %s for invocation #%d %s does not match expected ' .
                    'value.',
                    $i,
                    $callIndex,
                    $invocation->toString()
                )
            );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\Verifiable;
use PHPUnit\Framework\SelfDescribing;

interface ParametersRule extends SelfDescribing, Verifiable
{
    /**
     * @throws ExpectationFailedException if the invocation violates the rule
     */
    public function apply(BaseInvocation $invocation): void;

    public function verify(): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function count;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\Verifiable;
use PHPUnit\Framework\SelfDescribing;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
abstract class InvocationOrder implements SelfDescribing, Verifiable
{
    /**
     * @var BaseInvocation[]
     */
    private $invocations = [];

    public function getInvocationCount(): int
    {
        return count($this->invocations);
    }

    public function hasBeenInvoked(): bool
    {
        return count($this->invocations) > 0;
    }

    final public function invoked(BaseInvocation $invocation)
    {
        $this->invocations[] = $invocation;

        return $this->invokedDo($invocation);
    }

    abstract public function matches(BaseInvocation $invocation): bool;

    abstract protected function invokedDo(BaseInvocation $invocation);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AnyInvokedCount extends InvocationOrder
{
    public function toString(): string
    {
        return 'invoked zero or more times';
    }

    public function verify(): void
    {
    }

    public function matches(BaseInvocation $invocation): bool
    {
        return true;
    }

    protected function invokedDo(BaseInvocation $invocation): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvokedAtLeastOnce extends InvocationOrder
{
    public function toString(): string
    {
        return 'invoked at least once';
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        $count = $this->getInvocationCount();

        if ($count < 1) {
            throw new ExpectationFailedException(
                'Expected invocation at least once but it never occurred.'
            );
        }
    }

    public function matches(BaseInvocation $invocation): bool
    {
        return true;
    }

    protected function invokedDo(BaseInvocation $invocation): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AnyParameters implements ParametersRule
{
    public function toString(): string
    {
        return 'with any parameters';
    }

    public function apply(BaseInvocation $invocation): void
    {
    }

    public function verify(): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvokedAtMostCount extends InvocationOrder
{
    /**
     * @var int
     */
    private $allowedInvocations;

    /**
     * @param int $allowedInvocations
     */
    public function __construct($allowedInvocations)
    {
        $this->allowedInvocations = $allowedInvocations;
    }

    public function toString(): string
    {
        return 'invoked at most ' . $this->allowedInvocations . ' times';
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        $count = $this->getInvocationCount();

        if ($count > $this->allowedInvocations) {
            throw new ExpectationFailedException(
                'Expected invocation at most ' . $this->allowedInvocations .
                ' times but it occurred ' . $count . ' time(s).'
            );
        }
    }

    public function matches(BaseInvocation $invocation): bool
    {
        return true;
    }

    protected function invokedDo(BaseInvocation $invocation): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class InvokedAtIndex extends InvocationOrder
{
    /**
     * @var int
     */
    private $sequenceIndex;

    /**
     * @var int
     */
    private $currentIndex = -1;

    /**
     * @param int $sequenceIndex
     */
    public function __construct($sequenceIndex)
    {
        $this->sequenceIndex = $sequenceIndex;
    }

    public function toString(): string
    {
        return 'invoked at sequence index ' . $this->sequenceIndex;
    }

    public function matches(BaseInvocation $invocation): bool
    {
        $this->currentIndex++;

        return $this->currentIndex == $this->sequenceIndex;
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        if ($this->currentIndex < $this->sequenceIndex) {
            throw new ExpectationFailedException(
                sprintf(
                    'The expected invocation at index %s was never reached.',
                    $this->sequenceIndex
                )
            );
        }
    }

    protected function invokedDo(BaseInvocation $invocation): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvokedAtLeastCount extends InvocationOrder
{
    /**
     * @var int
     */
    private $requiredInvocations;

    /**
     * @param int $requiredInvocations
     */
    public function __construct($requiredInvocations)
    {
        $this->requiredInvocations = $requiredInvocations;
    }

    public function toString(): string
    {
        return 'invoked at least ' . $this->requiredInvocations . ' times';
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        $count = $this->getInvocationCount();

        if ($count < $this->requiredInvocations) {
            throw new ExpectationFailedException(
                'Expected invocation at least ' . $this->requiredInvocations .
                ' times but it occurred ' . $count . ' time(s).'
            );
        }
    }

    public function matches(BaseInvocation $invocation): bool
    {
        return true;
    }

    protected function invokedDo(BaseInvocation $invocation): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function count;
use function get_class;
use function sprintf;
use Exception;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsAnything;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Parameters implements ParametersRule
{
    /**
     * @var Constraint[]
     */
    private $parameters = [];

    /**
     * @var BaseInvocation
     */
    private $invocation;

    /**
     * @var bool|ExpectationFailedException
     */
    private $parameterVerificationResult;

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct(array $parameters)
    {
        foreach ($parameters as $parameter) {
            if (!($parameter instanceof Constraint)) {
                $parameter = new IsEqual(
                    $parameter
                );
            }

            $this->parameters[] = $parameter;
        }
    }

    public function toString(): string
    {
        $text = 'with parameter';

        foreach ($this->parameters as $index => $parameter) {
            if ($index > 0) {
                $text .= ' and';
            }

            $text .= ' ' . $index . ' ' . $parameter->toString();
        }

        return $text;
    }

    /**
     * @throws Exception
     */
    public function apply(BaseInvocation $invocation): void
    {
        $this->invocation                  = $invocation;
        $this->parameterVerificationResult = null;

        try {
            $this->parameterVerificationResult = $this->doVerify();
        } catch (ExpectationFailedException $e) {
            $this->parameterVerificationResult = $e;

            throw $this->parameterVerificationResult;
        }
    }

    /**
     * Checks if the invocation $invocation matches the current rules. If it
     * does the rule will get the invoked() method called which should check
     * if an expectation is met.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        $this->doVerify();
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    private function doVerify(): bool
    {
        if (isset($this->parameterVerificationResult)) {
            return $this->guardAgainstDuplicateEvaluationOfParameterConstraints();
        }

        if ($this->invocation === null) {
            throw new ExpectationFailedException('Mocked method does not exist.');
        }

        if (count($this->invocation->getParameters()) < count($this->parameters)) {
            $message = 'Parameter count for invocation %s is too low.';

            // The user called `->with($this->anything())`, but may have meant
            // `->withAnyParameters()`.
            //
            // @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/199
            if (count($this->parameters) === 1 &&
                get_class($this->parameters[0]) === IsAnything::class) {
                $message .= "\nTo allow 0 or more parameters with any value, omit ->with() or use ->withAnyParameters() instead.";
            }

            throw new ExpectationFailedException(
                sprintf($message, $this->invocation->toString())
            );
        }

        foreach ($this->parameters as $i => $parameter) {
            $parameter->evaluate(
                $this->invocation->getParameters()[$i],
                sprintf(
                    'Parameter %s for invocation %s does not match expected ' .
                    'value.',
                    $i,
                    $this->invocation->toString()
                )
            );
        }

        return true;
    }

    /**
     * @throws ExpectationFailedException
     */
    private function guardAgainstDuplicateEvaluationOfParameterConstraints(): bool
    {
        if ($this->parameterVerificationResult instanceof ExpectationFailedException) {
            throw $this->parameterVerificationResult;
        }

        return (bool) $this->parameterVerificationResult;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvokedCount extends InvocationOrder
{
    /**
     * @var int
     */
    private $expectedCount;

    /**
     * @param int $expectedCount
     */
    public function __construct($expectedCount)
    {
        $this->expectedCount = $expectedCount;
    }

    public function isNever(): bool
    {
        return $this->expectedCount === 0;
    }

    public function toString(): string
    {
        return 'invoked ' . $this->expectedCount . ' time(s)';
    }

    public function matches(BaseInvocation $invocation): bool
    {
        return true;
    }

    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void
    {
        $count = $this->getInvocationCount();

        if ($count !== $this->expectedCount) {
            throw new ExpectationFailedException(
                sprintf(
                    'Method was expected to be called %d times, ' .
                    'actually called %d times.',
                    $this->expectedCount,
                    $count
                )
            );
        }
    }

    /**
     * @throws ExpectationFailedException
     */
    protected function invokedDo(BaseInvocation $invocation): void
    {
        $count = $this->getInvocationCount();

        if ($count > $this->expectedCount) {
            $message = $invocation->toString() . ' ';

            switch ($this->expectedCount) {
                case 0:
                    $message .= 'was not expected to be called.';

                    break;

                case 1:
                    $message .= 'was not expected to be called more than once.';

                    break;

                default:
                    $message .= sprintf(
                        'was not expected to be called more than %d times.',
                        $this->expectedCount
                    );
            }

            throw new ExpectationFailedException($message);
        }
    }
}

    {modifier} function {reference}{method_name}({arguments_decl}){return_declaration}
    {{deprecation}
        $__phpunit_arguments = [{arguments_call}];
        $__phpunit_count     = func_num_args();

        if ($__phpunit_count > {arguments_count}) {
            $__phpunit_arguments_tmp = func_get_args();

            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
            }
        }

        $__phpunit_result = $this->__phpunit_getInvocationHandler()->invoke(
            new \PHPUnit\Framework\MockObject\Invocation(
                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_declaration}', $this, {clone_arguments}
            )
        );

        return $__phpunit_result;
    }
declare(strict_types=1);

{prologue}{class_declaration}
{
    use \PHPUnit\Framework\MockObject\Api;{method}{clone}
{mocked_methods}}{epilogue}

    public function {method_name}({arguments})
    {
    }

    {modifier} function {reference}{method_name}({arguments_decl}){return_declaration}
    {
        $__phpunit_arguments = [{arguments_call}];
        $__phpunit_count     = func_num_args();

        if ($__phpunit_count > {arguments_count}) {
            $__phpunit_arguments_tmp = func_get_args();

            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
            }
        }

        $this->__phpunit_getInvocationHandler()->invoke(
            new \PHPUnit\Framework\MockObject\Invocation(
                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_declaration}', $this, {clone_arguments}, true
            )
        );

        return call_user_func_array(array($this->__phpunit_originalObject, "{method_name}"), $__phpunit_arguments);
    }
declare(strict_types=1);

{namespace}class {class_name} extends \SoapClient
{
    public function __construct($wsdl, array $options)
    {
        parent::__construct('{wsdl}', $options);
    }
{methods}}
declare(strict_types=1);

{prologue}class {class_name}
{
    use {trait_name};
}

    {modifier} function {reference}{method_name}({arguments_decl}){return_declaration}
    {
        $__phpunit_arguments = [{arguments_call}];
        $__phpunit_count     = func_num_args();

        if ($__phpunit_count > {arguments_count}) {
            $__phpunit_arguments_tmp = func_get_args();

            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
            }
        }

        $this->__phpunit_getInvocationHandler()->invoke(
            new \PHPUnit\Framework\MockObject\Invocation(
                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_declaration}', $this, {clone_arguments}, true
            )
        );

        call_user_func_array(array($this->__phpunit_originalObject, "{method_name}"), $__phpunit_arguments);
    }

        @trigger_error({deprecation}, E_USER_DEPRECATED);

    {modifier} function {reference}{method_name}({arguments_decl}){return_declaration}
    {
        throw new \PHPUnit\Framework\MockObject\BadMethodCallException('Static method "{method_name}" cannot be invoked on mock object');
    }

    {modifier} function {reference}{method_name}({arguments_decl}){return_declaration}
    {{deprecation}
        $__phpunit_arguments = [{arguments_call}];
        $__phpunit_count     = func_num_args();

        if ($__phpunit_count > {arguments_count}) {
            $__phpunit_arguments_tmp = func_get_args();

            for ($__phpunit_i = {arguments_count}; $__phpunit_i < $__phpunit_count; $__phpunit_i++) {
                $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i];
            }
        }

        $this->__phpunit_getInvocationHandler()->invoke(
            new \PHPUnit\Framework\MockObject\Invocation(
                '{class_name}', '{method_name}', $__phpunit_arguments, '{return_declaration}', $this, {clone_arguments}
            )
        );
    }
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use SebastianBergmann\Type\Type;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ConfigurableMethod
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var Type
     */
    private $returnType;

    public function __construct(string $name, Type $returnType)
    {
        $this->name       = $name;
        $this->returnType = $returnType;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function mayReturn($value): bool
    {
        if ($value === null && $this->returnType->allowsNull()) {
            return true;
        }

        return $this->returnType->isAssignable(Type::fromValue($value, false));
    }

    public function getReturnTypeDeclaration(): string
    {
        return $this->returnType->getReturnTypeDeclaration();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function assert;
use function implode;
use function sprintf;
use Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount;
use PHPUnit\Framework\MockObject\Rule\AnyParameters;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;
use PHPUnit\Framework\MockObject\Rule\InvokedAtMostCount;
use PHPUnit\Framework\MockObject\Rule\InvokedCount;
use PHPUnit\Framework\MockObject\Rule\MethodName;
use PHPUnit\Framework\MockObject\Rule\ParametersRule;
use PHPUnit\Framework\MockObject\Stub\Stub;
use PHPUnit\Framework\TestFailure;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Matcher
{
    /**
     * @var InvocationOrder
     */
    private $invocationRule;

    /**
     * @var mixed
     */
    private $afterMatchBuilderId;

    /**
     * @var bool
     */
    private $afterMatchBuilderIsInvoked = false;

    /**
     * @var MethodName
     */
    private $methodNameRule;

    /**
     * @var ParametersRule
     */
    private $parametersRule;

    /**
     * @var Stub
     */
    private $stub;

    public function __construct(InvocationOrder $rule)
    {
        $this->invocationRule = $rule;
    }

    public function hasMatchers(): bool
    {
        return !$this->invocationRule instanceof AnyInvokedCount;
    }

    public function hasMethodNameRule(): bool
    {
        return $this->methodNameRule !== null;
    }

    public function getMethodNameRule(): MethodName
    {
        return $this->methodNameRule;
    }

    public function setMethodNameRule(MethodName $rule): void
    {
        $this->methodNameRule = $rule;
    }

    public function hasParametersRule(): bool
    {
        return $this->parametersRule !== null;
    }

    public function setParametersRule(ParametersRule $rule): void
    {
        $this->parametersRule = $rule;
    }

    public function setStub(Stub $stub): void
    {
        $this->stub = $stub;
    }

    public function setAfterMatchBuilderId(string $id): void
    {
        $this->afterMatchBuilderId = $id;
    }

    /**
     * @throws Exception
     * @throws ExpectationFailedException
     * @throws RuntimeException
     */
    public function invoked(Invocation $invocation)
    {
        if ($this->methodNameRule === null) {
            throw new RuntimeException('No method rule is set');
        }

        if ($this->afterMatchBuilderId !== null) {
            $matcher = $invocation->getObject()
                                  ->__phpunit_getInvocationHandler()
                                  ->lookupMatcher($this->afterMatchBuilderId);

            if (!$matcher) {
                throw new RuntimeException(
                    sprintf(
                        'No builder found for match builder identification <%s>',
                        $this->afterMatchBuilderId
                    )
                );
            }
            assert($matcher instanceof self);

            if ($matcher->invocationRule->hasBeenInvoked()) {
                $this->afterMatchBuilderIsInvoked = true;
            }
        }

        $this->invocationRule->invoked($invocation);

        try {
            if ($this->parametersRule !== null) {
                $this->parametersRule->apply($invocation);
            }
        } catch (ExpectationFailedException $e) {
            throw new ExpectationFailedException(
                sprintf(
                    "Expectation failed for %s when %s\n%s",
                    $this->methodNameRule->toString(),
                    $this->invocationRule->toString(),
                    $e->getMessage()
                ),
                $e->getComparisonFailure()
            );
        }

        if ($this->stub) {
            return $this->stub->invoke($invocation);
        }

        return $invocation->generateReturnValue();
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     * @throws RuntimeException
     */
    public function matches(Invocation $invocation): bool
    {
        if ($this->afterMatchBuilderId !== null) {
            $matcher = $invocation->getObject()
                                  ->__phpunit_getInvocationHandler()
                                  ->lookupMatcher($this->afterMatchBuilderId);

            if (!$matcher) {
                throw new RuntimeException(
                    sprintf(
                        'No builder found for match builder identification <%s>',
                        $this->afterMatchBuilderId
                    )
                );
            }
            assert($matcher instanceof self);

            if (!$matcher->invocationRule->hasBeenInvoked()) {
                return false;
            }
        }

        if ($this->methodNameRule === null) {
            throw new RuntimeException('No method rule is set');
        }

        if (!$this->invocationRule->matches($invocation)) {
            return false;
        }

        try {
            if (!$this->methodNameRule->matches($invocation)) {
                return false;
            }
        } catch (ExpectationFailedException $e) {
            throw new ExpectationFailedException(
                sprintf(
                    "Expectation failed for %s when %s\n%s",
                    $this->methodNameRule->toString(),
                    $this->invocationRule->toString(),
                    $e->getMessage()
                ),
                $e->getComparisonFailure()
            );
        }

        return true;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     * @throws RuntimeException
     */
    public function verify(): void
    {
        if ($this->methodNameRule === null) {
            throw new RuntimeException('No method rule is set');
        }

        try {
            $this->invocationRule->verify();

            if ($this->parametersRule === null) {
                $this->parametersRule = new AnyParameters;
            }

            $invocationIsAny    = $this->invocationRule instanceof AnyInvokedCount;
            $invocationIsNever  = $this->invocationRule instanceof InvokedCount && $this->invocationRule->isNever();
            $invocationIsAtMost = $this->invocationRule instanceof InvokedAtMostCount;

            if (!$invocationIsAny && !$invocationIsNever && !$invocationIsAtMost) {
                $this->parametersRule->verify();
            }
        } catch (ExpectationFailedException $e) {
            throw new ExpectationFailedException(
                sprintf(
                    "Expectation failed for %s when %s.\n%s",
                    $this->methodNameRule->toString(),
                    $this->invocationRule->toString(),
                    TestFailure::exceptionToString($e)
                )
            );
        }
    }

    public function toString(): string
    {
        $list = [];

        if ($this->invocationRule !== null) {
            $list[] = $this->invocationRule->toString();
        }

        if ($this->methodNameRule !== null) {
            $list[] = 'where ' . $this->methodNameRule->toString();
        }

        if ($this->parametersRule !== null) {
            $list[] = 'and ' . $this->parametersRule->toString();
        }

        if ($this->afterMatchBuilderId !== null) {
            $list[] = 'after ' . $this->afterMatchBuilderId;
        }

        if ($this->stub !== null) {
            $list[] = 'will ' . $this->stub->toString();
        }

        return implode(' ', $list);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnStub implements Stub
{
    /**
     * @var mixed
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function invoke(Invocation $invocation)
    {
        return $this->value;
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            'return user-specified value %s',
            $exporter->export($this->value)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function array_shift;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ConsecutiveCalls implements Stub
{
    /**
     * @var array
     */
    private $stack;

    /**
     * @var mixed
     */
    private $value;

    public function __construct(array $stack)
    {
        $this->stack = $stack;
    }

    public function invoke(Invocation $invocation)
    {
        $this->value = array_shift($this->stack);

        if ($this->value instanceof Stub) {
            $this->value = $this->value->invoke($invocation);
        }

        return $this->value;
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            'return user-specified value %s',
            $exporter->export($this->value)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnArgument implements Stub
{
    /**
     * @var int
     */
    private $argumentIndex;

    public function __construct($argumentIndex)
    {
        $this->argumentIndex = $argumentIndex;
    }

    public function invoke(Invocation $invocation)
    {
        if (isset($invocation->getParameters()[$this->argumentIndex])) {
            return $invocation->getParameters()[$this->argumentIndex];
        }
    }

    public function toString(): string
    {
        return sprintf('return argument #%d', $this->argumentIndex);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnReference implements Stub
{
    /**
     * @var mixed
     */
    private $reference;

    public function __construct(&$reference)
    {
        $this->reference = &$reference;
    }

    public function invoke(Invocation $invocation)
    {
        return $this->reference;
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            'return user-specified reference %s',
            $exporter->export($this->reference)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function array_pop;
use function count;
use function is_array;
use PHPUnit\Framework\MockObject\Invocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnValueMap implements Stub
{
    /**
     * @var array
     */
    private $valueMap;

    public function __construct(array $valueMap)
    {
        $this->valueMap = $valueMap;
    }

    public function invoke(Invocation $invocation)
    {
        $parameterCount = count($invocation->getParameters());

        foreach ($this->valueMap as $map) {
            if (!is_array($map) || $parameterCount !== (count($map) - 1)) {
                continue;
            }

            $return = array_pop($map);

            if ($invocation->getParameters() === $map) {
                return $return;
            }
        }
    }

    public function toString(): string
    {
        return 'return value from a map';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function call_user_func_array;
use function get_class;
use function is_array;
use function is_object;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnCallback implements Stub
{
    private $callback;

    public function __construct($callback)
    {
        $this->callback = $callback;
    }

    public function invoke(Invocation $invocation)
    {
        return call_user_func_array($this->callback, $invocation->getParameters());
    }

    public function toString(): string
    {
        if (is_array($this->callback)) {
            if (is_object($this->callback[0])) {
                $class = get_class($this->callback[0]);
                $type  = '->';
            } else {
                $class = $this->callback[0];
                $type  = '::';
            }

            return sprintf(
                'return result of user defined callback %s%s%s() with the ' .
                'passed arguments',
                $class,
                $type,
                $this->callback[1]
            );
        }

        return 'return result of user defined callback ' . $this->callback .
               ' with the passed arguments';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use PHPUnit\Framework\MockObject\Invocation;
use PHPUnit\Framework\MockObject\RuntimeException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnSelf implements Stub
{
    /**
     * @throws RuntimeException
     */
    public function invoke(Invocation $invocation)
    {
        return $invocation->getObject();
    }

    public function toString(): string
    {
        return 'return the current object';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use PHPUnit\Framework\MockObject\Invocation;
use PHPUnit\Framework\SelfDescribing;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Stub extends SelfDescribing
{
    /**
     * Fakes the processing of the invocation $invocation by returning a
     * specific value.
     *
     * @param Invocation $invocation The invocation which was mocked and matched by the current method and argument matchers
     */
    public function invoke(Invocation $invocation);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Stub;

use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Exception implements Stub
{
    private $exception;

    public function __construct(Throwable $exception)
    {
        $this->exception = $exception;
    }

    /**
     * @throws Throwable
     */
    public function invoke(Invocation $invocation): void
    {
        throw $this->exception;
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            'raise user-specified exception %s',
            $exporter->export($this->exception)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function call_user_func_array;
use function func_get_args;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount;

/**
 * @internal This trait is not covered by the backward compatibility promise for PHPUnit
 */
trait Method
{
    public function method()
    {
        $expects = $this->expects(new AnyInvokedCount);

        return call_user_func_array(
            [$expects, 'method'],
            func_get_args()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use PHPUnit\Framework\MockObject\Builder\InvocationMocker as InvocationMockerBuilder;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;

/**
 * @internal This trait is not covered by the backward compatibility promise for PHPUnit
 */
trait Api
{
    /**
     * @var ConfigurableMethod[]
     */
    private static $__phpunit_configurableMethods;

    /**
     * @var object
     */
    private $__phpunit_originalObject;

    /**
     * @var bool
     */
    private $__phpunit_returnValueGeneration = true;

    /**
     * @var InvocationHandler
     */
    private $__phpunit_invocationMocker;

    /** @noinspection MagicMethodsValidityInspection */
    public static function __phpunit_initConfigurableMethods(ConfigurableMethod ...$configurableMethods): void
    {
        if (isset(static::$__phpunit_configurableMethods)) {
            throw new ConfigurableMethodsAlreadyInitializedException(
                'Configurable methods is already initialized and can not be reinitialized'
            );
        }

        static::$__phpunit_configurableMethods = $configurableMethods;
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __phpunit_setOriginalObject($originalObject): void
    {
        $this->__phpunit_originalObject = $originalObject;
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration): void
    {
        $this->__phpunit_returnValueGeneration = $returnValueGeneration;
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __phpunit_getInvocationHandler(): InvocationHandler
    {
        if ($this->__phpunit_invocationMocker === null) {
            $this->__phpunit_invocationMocker = new InvocationHandler(
                static::$__phpunit_configurableMethods,
                $this->__phpunit_returnValueGeneration
            );
        }

        return $this->__phpunit_invocationMocker;
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __phpunit_hasMatchers(): bool
    {
        return $this->__phpunit_getInvocationHandler()->hasMatchers();
    }

    /** @noinspection MagicMethodsValidityInspection */
    public function __phpunit_verify(bool $unsetInvocationMocker = true): void
    {
        $this->__phpunit_getInvocationHandler()->verify();

        if ($unsetInvocationMocker) {
            $this->__phpunit_invocationMocker = null;
        }
    }

    public function expects(InvocationOrder $matcher): InvocationMockerBuilder
    {
        return $this->__phpunit_getInvocationHandler()->expects($matcher);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use PHPUnit\Framework\MockObject\Builder\InvocationStubber;

/**
 * @method InvocationStubber method($constraint)
 */
interface Stub
{
    public function __phpunit_getInvocationHandler(): InvocationHandler;

    public function __phpunit_hasMatchers(): bool;

    public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use const DIRECTORY_SEPARATOR;
use function implode;
use function is_string;
use function method_exists;
use function preg_match;
use function preg_replace;
use function sprintf;
use function str_replace;
use function substr_count;
use function trim;
use function var_export;
use ReflectionException;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionType;
use SebastianBergmann\Type\ObjectType;
use SebastianBergmann\Type\Type;
use SebastianBergmann\Type\UnknownType;
use SebastianBergmann\Type\VoidType;
use Text_Template;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MockMethod
{
    /**
     * @var Text_Template[]
     */
    private static $templates = [];

    /**
     * @var string
     */
    private $className;

    /**
     * @var string
     */
    private $methodName;

    /**
     * @var bool
     */
    private $cloneArguments;

    /**
     * @var string
     */
    private $modifier;

    /**
     * @var string
     */
    private $argumentsForDeclaration;

    /**
     * @var string
     */
    private $argumentsForCall;

    /**
     * @var Type
     */
    private $returnType;

    /**
     * @var string
     */
    private $reference;

    /**
     * @var bool
     */
    private $callOriginalMethod;

    /**
     * @var bool
     */
    private $static;

    /**
     * @var ?string
     */
    private $deprecation;

    /**
     * @throws RuntimeException
     */
    public static function fromReflection(ReflectionMethod $method, bool $callOriginalMethod, bool $cloneArguments): self
    {
        if ($method->isPrivate()) {
            $modifier = 'private';
        } elseif ($method->isProtected()) {
            $modifier = 'protected';
        } else {
            $modifier = 'public';
        }

        if ($method->isStatic()) {
            $modifier .= ' static';
        }

        if ($method->returnsReference()) {
            $reference = '&';
        } else {
            $reference = '';
        }

        $docComment = $method->getDocComment();

        if (is_string($docComment) &&
            preg_match('#\*[ \t]*+@deprecated[ \t]*+(.*?)\r?+\n[ \t]*+\*(?:[ \t]*+@|/$)#s', $docComment, $deprecation)) {
            $deprecation = trim(preg_replace('#[ \t]*\r?\n[ \t]*+\*[ \t]*+#', ' ', $deprecation[1]));
        } else {
            $deprecation = null;
        }

        return new self(
            $method->getDeclaringClass()->getName(),
            $method->getName(),
            $cloneArguments,
            $modifier,
            self::getMethodParametersForDeclaration($method),
            self::getMethodParametersForCall($method),
            self::deriveReturnType($method),
            $reference,
            $callOriginalMethod,
            $method->isStatic(),
            $deprecation
        );
    }

    public static function fromName(string $fullClassName, string $methodName, bool $cloneArguments): self
    {
        return new self(
            $fullClassName,
            $methodName,
            $cloneArguments,
            'public',
            '',
            '',
            new UnknownType,
            '',
            false,
            false,
            null
        );
    }

    public function __construct(string $className, string $methodName, bool $cloneArguments, string $modifier, string $argumentsForDeclaration, string $argumentsForCall, Type $returnType, string $reference, bool $callOriginalMethod, bool $static, ?string $deprecation)
    {
        $this->className               = $className;
        $this->methodName              = $methodName;
        $this->cloneArguments          = $cloneArguments;
        $this->modifier                = $modifier;
        $this->argumentsForDeclaration = $argumentsForDeclaration;
        $this->argumentsForCall        = $argumentsForCall;
        $this->returnType              = $returnType;
        $this->reference               = $reference;
        $this->callOriginalMethod      = $callOriginalMethod;
        $this->static                  = $static;
        $this->deprecation             = $deprecation;
    }

    public function getName(): string
    {
        return $this->methodName;
    }

    /**
     * @throws RuntimeException
     */
    public function generateCode(): string
    {
        if ($this->static) {
            $templateFile = 'mocked_static_method.tpl';
        } elseif ($this->returnType instanceof VoidType) {
            $templateFile = sprintf(
                '%s_method_void.tpl',
                $this->callOriginalMethod ? 'proxied' : 'mocked'
            );
        } else {
            $templateFile = sprintf(
                '%s_method.tpl',
                $this->callOriginalMethod ? 'proxied' : 'mocked'
            );
        }

        $deprecation = $this->deprecation;

        if (null !== $this->deprecation) {
            $deprecation         = "The {$this->className}::{$this->methodName} method is deprecated ({$this->deprecation}).";
            $deprecationTemplate = $this->getTemplate('deprecation.tpl');

            $deprecationTemplate->setVar([
                'deprecation' => var_export($deprecation, true),
            ]);

            $deprecation = $deprecationTemplate->render();
        }

        /**
         * This is required as the version of sebastian/type used
         * by PHPUnit 8.5 does now know about the mixed type.
         */
        $returnTypeDeclaration = str_replace(
            '?mixed',
            'mixed',
            $this->returnType->getReturnTypeDeclaration()
        );

        $template = $this->getTemplate($templateFile);

        $template->setVar(
            [
                'arguments_decl'     => $this->argumentsForDeclaration,
                'arguments_call'     => $this->argumentsForCall,
                'return_declaration' => $returnTypeDeclaration,
                'arguments_count'    => !empty($this->argumentsForCall) ? substr_count($this->argumentsForCall, ',') + 1 : 0,
                'class_name'         => $this->className,
                'method_name'        => $this->methodName,
                'modifier'           => $this->modifier,
                'reference'          => $this->reference,
                'clone_arguments'    => $this->cloneArguments ? 'true' : 'false',
                'deprecation'        => $deprecation,
            ]
        );

        return $template->render();
    }

    public function getReturnType(): Type
    {
        return $this->returnType;
    }

    private function getTemplate(string $template): Text_Template
    {
        $filename = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR . $template;

        if (!isset(self::$templates[$filename])) {
            self::$templates[$filename] = new Text_Template($filename);
        }

        return self::$templates[$filename];
    }

    /**
     * Returns the parameters of a function or method.
     *
     * @throws RuntimeException
     */
    private static function getMethodParametersForDeclaration(ReflectionMethod $method): string
    {
        $parameters = [];

        foreach ($method->getParameters() as $i => $parameter) {
            $name = '$' . $parameter->getName();

            /* Note: PHP extensions may use empty names for reference arguments
             * or "..." for methods taking a variable number of arguments.
             */
            if ($name === '$' || $name === '$...') {
                $name = '$arg' . $i;
            }

            $nullable        = '';
            $default         = '';
            $reference       = '';
            $typeDeclaration = '';
            $type            = null;
            $typeName        = null;

            if ($parameter->hasType()) {
                $type = $parameter->getType();

                if ($type instanceof ReflectionNamedType) {
                    $typeName = $type->getName();
                }
            }

            if ($parameter->isVariadic()) {
                $name = '...' . $name;
            } elseif ($parameter->isDefaultValueAvailable()) {
                $default = ' = ' . var_export($parameter->getDefaultValue(), true);
            } elseif ($parameter->isOptional()) {
                $default = ' = null';
            }

            if ($type !== null) {
                if ($typeName !== 'mixed' && $parameter->allowsNull()) {
                    $nullable = '?';
                }

                if ($typeName === 'self') {
                    $typeDeclaration = $method->getDeclaringClass()->getName() . ' ';
                } elseif ($typeName !== null) {
                    $typeDeclaration = $typeName . ' ';
                }
            }

            if ($parameter->isPassedByReference()) {
                $reference = '&';
            }

            $parameters[] = $nullable . $typeDeclaration . $reference . $name . $default;
        }

        return implode(', ', $parameters);
    }

    /**
     * Returns the parameters of a function or method.
     *
     * @throws ReflectionException
     */
    private static function getMethodParametersForCall(ReflectionMethod $method): string
    {
        $parameters = [];

        foreach ($method->getParameters() as $i => $parameter) {
            $name = '$' . $parameter->getName();

            /* Note: PHP extensions may use empty names for reference arguments
             * or "..." for methods taking a variable number of arguments.
             */
            if ($name === '$' || $name === '$...') {
                $name = '$arg' . $i;
            }

            if ($parameter->isVariadic()) {
                continue;
            }

            if ($parameter->isPassedByReference()) {
                $parameters[] = '&' . $name;
            } else {
                $parameters[] = $name;
            }
        }

        return implode(', ', $parameters);
    }

    private static function deriveReturnType(ReflectionMethod $method): Type
    {
        $returnType = self::reflectionMethodGetReturnType($method);

        if ($returnType === null) {
            return new UnknownType;
        }

        // @see https://bugs.php.net/bug.php?id=70722
        if ($returnType instanceof ReflectionNamedType && $returnType->getName() === 'self') {
            return ObjectType::fromName($method->getDeclaringClass()->getName(), $returnType->allowsNull());
        }

        // @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/406
        if ($returnType instanceof ReflectionNamedType && $returnType->getName() === 'parent') {
            $parentClass = $method->getDeclaringClass()->getParentClass();

            if ($parentClass === false) {
                throw new RuntimeException(
                    sprintf(
                        'Cannot mock %s::%s because "parent" return type declaration is used but %s does not have a parent class',
                        $method->getDeclaringClass()->getName(),
                        $method->getName(),
                        $method->getDeclaringClass()->getName()
                    )
                );
            }

            return ObjectType::fromName($parentClass->getName(), $returnType->allowsNull());
        }

        return Type::fromName($returnType->getName(), $returnType->allowsNull());
    }

    private static function reflectionMethodGetReturnType(ReflectionMethod $method): ?ReflectionType
    {
        if ($method->hasReturnType()) {
            return $method->getReturnType();
        }

        if (!method_exists($method, 'getTentativeReturnType')) {
            return null;
        }

        return $method->getTentativeReturnType();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use const DIRECTORY_SEPARATOR;
use const PHP_EOL;
use const PHP_MAJOR_VERSION;
use const PREG_OFFSET_CAPTURE;
use const WSDL_CACHE_NONE;
use function array_diff_assoc;
use function array_map;
use function array_merge;
use function array_pop;
use function array_unique;
use function class_exists;
use function count;
use function explode;
use function extension_loaded;
use function implode;
use function in_array;
use function interface_exists;
use function is_array;
use function is_object;
use function is_string;
use function md5;
use function mt_rand;
use function preg_match;
use function preg_match_all;
use function range;
use function serialize;
use function sort;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
use function trait_exists;
use Doctrine\Instantiator\Exception\ExceptionInterface as InstantiatorException;
use Doctrine\Instantiator\Instantiator;
use Exception;
use Iterator;
use IteratorAggregate;
use PHPUnit\Framework\InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use SoapClient;
use SoapFault;
use Text_Template;
use Throwable;
use Traversable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Generator
{
    private const MOCKED_CLONE_METHOD_WITH_VOID_RETURN_TYPE_TRAIT = <<<'EOT'
namespace PHPUnit\Framework\MockObject;

trait MockedCloneMethodWithVoidReturnType
{
    public function __clone(): void
    {
        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationHandler();
    }
}
EOT;

    private const MOCKED_CLONE_METHOD_WITHOUT_RETURN_TYPE_TRAIT = <<<'EOT'
namespace PHPUnit\Framework\MockObject;

trait MockedCloneMethodWithoutReturnType
{
    public function __clone()
    {
        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationHandler();
    }
}
EOT;

    private const UNMOCKED_CLONE_METHOD_WITH_VOID_RETURN_TYPE_TRAIT = <<<'EOT'
namespace PHPUnit\Framework\MockObject;

trait UnmockedCloneMethodWithVoidReturnType
{
    public function __clone(): void
    {
        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationHandler();

        parent::__clone();
    }
}
EOT;

    private const UNMOCKED_CLONE_METHOD_WITHOUT_RETURN_TYPE_TRAIT = <<<'EOT'
namespace PHPUnit\Framework\MockObject;

trait UnmockedCloneMethodWithoutReturnType
{
    public function __clone()
    {
        $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationHandler();

        parent::__clone();
    }
}
EOT;

    /**
     * @var array
     */
    private const BLACKLISTED_METHOD_NAMES = [
        '__CLASS__'       => true,
        '__DIR__'         => true,
        '__FILE__'        => true,
        '__FUNCTION__'    => true,
        '__LINE__'        => true,
        '__METHOD__'      => true,
        '__NAMESPACE__'   => true,
        '__TRAIT__'       => true,
        '__clone'         => true,
        '__halt_compiler' => true,
    ];

    /**
     * @var array
     */
    private static $cache = [];

    /**
     * @var Text_Template[]
     */
    private static $templates = [];

    /**
     * Returns a mock object for the specified class.
     *
     * @param string|string[] $type
     * @param null|array      $methods
     *
     * @throws RuntimeException
     */
    public function getMock($type, $methods = [], array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, bool $cloneArguments = true, bool $callOriginalMethods = false, object $proxyTarget = null, bool $allowMockingUnknownTypes = true, bool $returnValueGeneration = true): MockObject
    {
        if (!is_array($type) && !is_string($type)) {
            throw InvalidArgumentException::create(1, 'array or string');
        }

        if (!is_array($methods) && null !== $methods) {
            throw InvalidArgumentException::create(2, 'array');
        }

        if ($type === 'Traversable' || $type === '\\Traversable') {
            $type = 'Iterator';
        }

        if (is_array($type)) {
            $type = array_unique(
                array_map(
                    static function ($type)
                    {
                        if ($type === 'Traversable' ||
                            $type === '\\Traversable' ||
                            $type === '\\Iterator') {
                            return 'Iterator';
                        }

                        return $type;
                    },
                    $type
                )
            );
        }

        if (!$allowMockingUnknownTypes) {
            if (is_array($type)) {
                foreach ($type as $_type) {
                    if (!class_exists($_type, $callAutoload) &&
                        !interface_exists($_type, $callAutoload)) {
                        throw new RuntimeException(
                            sprintf(
                                'Cannot stub or mock class or interface "%s" which does not exist',
                                $_type
                            )
                        );
                    }
                }
            } elseif (!class_exists($type, $callAutoload) && !interface_exists($type, $callAutoload)) {
                throw new RuntimeException(
                    sprintf(
                        'Cannot stub or mock class or interface "%s" which does not exist',
                        $type
                    )
                );
            }
        }

        if (null !== $methods) {
            foreach ($methods as $method) {
                if (!preg_match('~[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*~', (string) $method)) {
                    throw new RuntimeException(
                        sprintf(
                            'Cannot stub or mock method with invalid name "%s"',
                            $method
                        )
                    );
                }
            }

            if ($methods !== array_unique($methods)) {
                throw new RuntimeException(
                    sprintf(
                        'Cannot stub or mock using a method list that contains duplicates: "%s" (duplicate: "%s")',
                        implode(', ', $methods),
                        implode(', ', array_unique(array_diff_assoc($methods, array_unique($methods))))
                    )
                );
            }
        }

        if ($mockClassName !== '' && class_exists($mockClassName, false)) {
            try {
                $reflector = new ReflectionClass($mockClassName);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new RuntimeException(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if (!$reflector->implementsInterface(MockObject::class)) {
                throw new RuntimeException(
                    sprintf(
                        'Class "%s" already exists.',
                        $mockClassName
                    )
                );
            }
        }

        if (!$callOriginalConstructor && $callOriginalMethods) {
            throw new RuntimeException(
                'Proxying to original methods requires invoking the original constructor'
            );
        }

        $mock = $this->generate(
            $type,
            $methods,
            $mockClassName,
            $callOriginalClone,
            $callAutoload,
            $cloneArguments,
            $callOriginalMethods
        );

        return $this->getObject(
            $mock,
            $type,
            $callOriginalConstructor,
            $callAutoload,
            $arguments,
            $callOriginalMethods,
            $proxyTarget,
            $returnValueGeneration
        );
    }

    /**
     * Returns a mock object for the specified abstract class with all abstract
     * methods of the class mocked. Concrete methods to mock can be specified with
     * the $mockedMethods parameter.
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType> $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     *
     * @throws RuntimeException
     */
    public function getMockForAbstractClass(string $originalClassName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = null, bool $cloneArguments = true): MockObject
    {
        if (class_exists($originalClassName, $callAutoload) ||
            interface_exists($originalClassName, $callAutoload)) {
            try {
                $reflector = new ReflectionClass($originalClassName);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new RuntimeException(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            $methods = $mockedMethods;

            foreach ($reflector->getMethods() as $method) {
                if ($method->isAbstract() && !in_array($method->getName(), $methods ?? [], true)) {
                    $methods[] = $method->getName();
                }
            }

            if (empty($methods)) {
                $methods = null;
            }

            return $this->getMock(
                $originalClassName,
                $methods,
                $arguments,
                $mockClassName,
                $callOriginalConstructor,
                $callOriginalClone,
                $callAutoload,
                $cloneArguments
            );
        }

        throw new RuntimeException(
            sprintf('Class "%s" does not exist.', $originalClassName)
        );
    }

    /**
     * Returns a mock object for the specified trait with all abstract methods
     * of the trait mocked. Concrete methods to mock can be specified with the
     * `$mockedMethods` parameter.
     *
     * @throws RuntimeException
     */
    public function getMockForTrait(string $traitName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = null, bool $cloneArguments = true): MockObject
    {
        if (!trait_exists($traitName, $callAutoload)) {
            throw new RuntimeException(
                sprintf(
                    'Trait "%s" does not exist.',
                    $traitName
                )
            );
        }

        $className = $this->generateClassName(
            $traitName,
            '',
            'Trait_'
        );

        $classTemplate = $this->getTemplate('trait_class.tpl');

        $classTemplate->setVar(
            [
                'prologue'   => 'abstract ',
                'class_name' => $className['className'],
                'trait_name' => $traitName,
            ]
        );

        $mockTrait = new MockTrait($classTemplate->render(), $className['className']);
        $mockTrait->generate();

        return $this->getMockForAbstractClass($className['className'], $arguments, $mockClassName, $callOriginalConstructor, $callOriginalClone, $callAutoload, $mockedMethods, $cloneArguments);
    }

    /**
     * Returns an object for the specified trait.
     *
     * @throws RuntimeException
     */
    public function getObjectForTrait(string $traitName, string $traitClassName = '', bool $callAutoload = true, bool $callOriginalConstructor = false, array $arguments = []): object
    {
        if (!trait_exists($traitName, $callAutoload)) {
            throw new RuntimeException(
                sprintf(
                    'Trait "%s" does not exist.',
                    $traitName
                )
            );
        }

        $className = $this->generateClassName(
            $traitName,
            $traitClassName,
            'Trait_'
        );

        $classTemplate = $this->getTemplate('trait_class.tpl');

        $classTemplate->setVar(
            [
                'prologue'   => '',
                'class_name' => $className['className'],
                'trait_name' => $traitName,
            ]
        );

        return $this->getObject(
            new MockTrait(
                $classTemplate->render(),
                $className['className']
            ),
            '',
            $callOriginalConstructor,
            $callAutoload,
            $arguments
        );
    }

    public function generate($type, array $methods = null, string $mockClassName = '', bool $callOriginalClone = true, bool $callAutoload = true, bool $cloneArguments = true, bool $callOriginalMethods = false): MockClass
    {
        if (is_array($type)) {
            sort($type);
        }

        if ($mockClassName !== '') {
            return $this->generateMock(
                $type,
                $methods,
                $mockClassName,
                $callOriginalClone,
                $callAutoload,
                $cloneArguments,
                $callOriginalMethods
            );
        }

        $key = md5(
            is_array($type) ? implode('_', $type) : $type .
            serialize($methods) .
            serialize($callOriginalClone) .
            serialize($cloneArguments) .
            serialize($callOriginalMethods)
        );

        if (!isset(self::$cache[$key])) {
            self::$cache[$key] = $this->generateMock(
                $type,
                $methods,
                $mockClassName,
                $callOriginalClone,
                $callAutoload,
                $cloneArguments,
                $callOriginalMethods
            );
        }

        return self::$cache[$key];
    }

    /**
     * @throws RuntimeException
     */
    public function generateClassFromWsdl(string $wsdlFile, string $className, array $methods = [], array $options = []): string
    {
        if (!extension_loaded('soap')) {
            throw new RuntimeException(
                'The SOAP extension is required to generate a mock object from WSDL.'
            );
        }

        $options = array_merge($options, ['cache_wsdl' => WSDL_CACHE_NONE]);

        try {
            $client   = new SoapClient($wsdlFile, $options);
            $_methods = array_unique($client->__getFunctions());
            unset($client);
        } catch (SoapFault $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        sort($_methods);

        $methodTemplate = $this->getTemplate('wsdl_method.tpl');
        $methodsBuffer  = '';

        foreach ($_methods as $method) {
            preg_match_all('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(/', $method, $matches, PREG_OFFSET_CAPTURE);
            $lastFunction = array_pop($matches[0]);
            $nameStart    = $lastFunction[1];
            $nameEnd      = $nameStart + strlen($lastFunction[0]) - 1;
            $name         = str_replace('(', '', $lastFunction[0]);

            if (empty($methods) || in_array($name, $methods, true)) {
                $args = explode(
                    ',',
                    str_replace(')', '', substr($method, $nameEnd + 1))
                );

                foreach (range(0, count($args) - 1) as $i) {
                    $parameterStart = strpos($args[$i], '$');

                    if (!$parameterStart) {
                        continue;
                    }

                    $args[$i] = substr($args[$i], $parameterStart);
                }

                $methodTemplate->setVar(
                    [
                        'method_name' => $name,
                        'arguments'   => implode(', ', $args),
                    ]
                );

                $methodsBuffer .= $methodTemplate->render();
            }
        }

        $optionsBuffer = '[';

        foreach ($options as $key => $value) {
            $optionsBuffer .= $key . ' => ' . $value;
        }

        $optionsBuffer .= ']';

        $classTemplate = $this->getTemplate('wsdl_class.tpl');
        $namespace     = '';

        if (strpos($className, '\\') !== false) {
            $parts     = explode('\\', $className);
            $className = array_pop($parts);
            $namespace = 'namespace ' . implode('\\', $parts) . ';' . "\n\n";
        }

        $classTemplate->setVar(
            [
                'namespace'  => $namespace,
                'class_name' => $className,
                'wsdl'       => $wsdlFile,
                'options'    => $optionsBuffer,
                'methods'    => $methodsBuffer,
            ]
        );

        return $classTemplate->render();
    }

    /**
     * @throws RuntimeException
     *
     * @return string[]
     */
    public function getClassMethods(string $className): array
    {
        try {
            $class = new ReflectionClass($className);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $methods = [];

        foreach ($class->getMethods() as $method) {
            if ($method->isPublic() || $method->isAbstract()) {
                $methods[] = $method->getName();
            }
        }

        return $methods;
    }

    /**
     * @throws RuntimeException
     *
     * @return MockMethod[]
     */
    public function mockClassMethods(string $className, bool $callOriginalMethods, bool $cloneArguments): array
    {
        try {
            $class = new ReflectionClass($className);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $methods = [];

        foreach ($class->getMethods() as $method) {
            if (($method->isPublic() || $method->isAbstract()) && $this->canMockMethod($method)) {
                $methods[] = MockMethod::fromReflection($method, $callOriginalMethods, $cloneArguments);
            }
        }

        return $methods;
    }

    /**
     * @throws RuntimeException
     *
     * @return MockMethod[]
     */
    public function mockInterfaceMethods(string $interfaceName, bool $cloneArguments): array
    {
        try {
            $class = new ReflectionClass($interfaceName);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $methods = [];

        foreach ($class->getMethods() as $method) {
            $methods[] = MockMethod::fromReflection($method, false, $cloneArguments);
        }

        return $methods;
    }

    /**
     * @psalm-param class-string $interfaceName
     *
     * @return ReflectionMethod[]
     */
    private function userDefinedInterfaceMethods(string $interfaceName): array
    {
        try {
            // @codeCoverageIgnoreStart
            $interface = new ReflectionClass($interfaceName);
        } catch (ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $methods = [];

        foreach ($interface->getMethods() as $method) {
            if (!$method->isUserDefined()) {
                continue;
            }

            $methods[] = $method;
        }

        return $methods;
    }

    private function getObject(MockType $mockClass, $type = '', bool $callOriginalConstructor = false, bool $callAutoload = false, array $arguments = [], bool $callOriginalMethods = false, object $proxyTarget = null, bool $returnValueGeneration = true)
    {
        $className = $mockClass->generate();

        if ($callOriginalConstructor) {
            if (count($arguments) === 0) {
                $object = new $className;
            } else {
                try {
                    $class = new ReflectionClass($className);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new RuntimeException(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                $object = $class->newInstanceArgs($arguments);
            }
        } else {
            try {
                $object = (new Instantiator)->instantiate($className);
            } catch (InstantiatorException $exception) {
                throw new RuntimeException($exception->getMessage());
            }
        }

        if ($callOriginalMethods) {
            if (!is_object($proxyTarget)) {
                if (count($arguments) === 0) {
                    $proxyTarget = new $type;
                } else {
                    try {
                        $class = new ReflectionClass($type);
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new RuntimeException(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    $proxyTarget = $class->newInstanceArgs($arguments);
                }
            }

            $object->__phpunit_setOriginalObject($proxyTarget);
        }

        if ($object instanceof MockObject) {
            $object->__phpunit_setReturnValueGeneration($returnValueGeneration);
        }

        return $object;
    }

    /**
     * @param array|string $type
     *
     * @throws RuntimeException
     */
    private function generateMock($type, ?array $explicitMethods, string $mockClassName, bool $callOriginalClone, bool $callAutoload, bool $cloneArguments, bool $callOriginalMethods): MockClass
    {
        $classTemplate        = $this->getTemplate('mocked_class.tpl');
        $additionalInterfaces = [];
        $mockedCloneMethod    = false;
        $unmockedCloneMethod  = false;
        $isClass              = false;
        $isInterface          = false;
        $class                = null;
        $mockMethods          = new MockMethodSet;

        if (is_array($type)) {
            $interfaceMethods = [];

            foreach ($type as $_type) {
                if (!interface_exists($_type, $callAutoload)) {
                    throw new RuntimeException(
                        sprintf(
                            'Interface "%s" does not exist.',
                            $_type
                        )
                    );
                }

                $additionalInterfaces[] = $_type;

                try {
                    $typeClass = new ReflectionClass($_type);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new RuntimeException(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                foreach ($this->getClassMethods($_type) as $method) {
                    if (in_array($method, $interfaceMethods, true)) {
                        throw new RuntimeException(
                            sprintf(
                                'Duplicate method "%s" not allowed.',
                                $method
                            )
                        );
                    }

                    try {
                        $methodReflection = $typeClass->getMethod($method);
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new RuntimeException(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    if ($this->canMockMethod($methodReflection)) {
                        $mockMethods->addMethods(
                            MockMethod::fromReflection($methodReflection, $callOriginalMethods, $cloneArguments)
                        );

                        $interfaceMethods[] = $method;
                    }
                }
            }

            unset($interfaceMethods);
        }

        $mockClassName = $this->generateClassName(
            $type,
            $mockClassName,
            'Mock_'
        );

        if (class_exists($mockClassName['fullClassName'], $callAutoload)) {
            $isClass = true;
        } elseif (interface_exists($mockClassName['fullClassName'], $callAutoload)) {
            $isInterface = true;
        }

        if (!$isClass && !$isInterface) {
            $prologue = 'class ' . $mockClassName['originalClassName'] . "\n{\n}\n\n";

            if (!empty($mockClassName['namespaceName'])) {
                $prologue = 'namespace ' . $mockClassName['namespaceName'] .
                            " {\n\n" . $prologue . "}\n\n" .
                            "namespace {\n\n";

                $epilogue = "\n\n}";
            }

            $mockedCloneMethod = true;
        } else {
            try {
                $class = new ReflectionClass($mockClassName['fullClassName']);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new RuntimeException(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if ($class->isFinal()) {
                throw new RuntimeException(
                    sprintf(
                        'Class "%s" is declared "final" and cannot be mocked.',
                        $mockClassName['fullClassName']
                    )
                );
            }

            // @see https://github.com/sebastianbergmann/phpunit/issues/2995
            if ($isInterface && $class->implementsInterface(Throwable::class)) {
                $actualClassName        = Exception::class;
                $additionalInterfaces[] = $class->getName();
                $isInterface            = false;

                try {
                    $class = new ReflectionClass($actualClassName);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new RuntimeException(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                foreach ($this->userDefinedInterfaceMethods($mockClassName['fullClassName']) as $method) {
                    $methodName = $method->getName();

                    if ($class->hasMethod($methodName)) {
                        try {
                            $classMethod = $class->getMethod($methodName);
                            // @codeCoverageIgnoreStart
                        } catch (ReflectionException $e) {
                            throw new RuntimeException(
                                $e->getMessage(),
                                $e->getCode(),
                                $e
                            );
                        }
                        // @codeCoverageIgnoreEnd

                        if (!$this->canMockMethod($classMethod)) {
                            continue;
                        }
                    }

                    $mockMethods->addMethods(
                        MockMethod::fromReflection($method, $callOriginalMethods, $cloneArguments)
                    );
                }

                $mockClassName = $this->generateClassName(
                    $actualClassName,
                    $mockClassName['className'],
                    'Mock_'
                );
            }

            // @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/103
            if ($isInterface && $class->implementsInterface(Traversable::class) &&
                !$class->implementsInterface(Iterator::class) &&
                !$class->implementsInterface(IteratorAggregate::class)) {
                $additionalInterfaces[] = Iterator::class;

                $mockMethods->addMethods(
                    ...$this->mockClassMethods(Iterator::class, $callOriginalMethods, $cloneArguments)
                );
            }

            if ($class->hasMethod('__clone')) {
                try {
                    $cloneMethod = $class->getMethod('__clone');
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new RuntimeException(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if (!$cloneMethod->isFinal()) {
                    if ($callOriginalClone && !$isInterface) {
                        $unmockedCloneMethod = true;
                    } else {
                        $mockedCloneMethod = true;
                    }
                }
            } else {
                $mockedCloneMethod = true;
            }
        }

        if ($isClass && $explicitMethods === []) {
            $mockMethods->addMethods(
                ...$this->mockClassMethods($mockClassName['fullClassName'], $callOriginalMethods, $cloneArguments)
            );
        }

        if ($isInterface && ($explicitMethods === [] || $explicitMethods === null)) {
            $mockMethods->addMethods(
                ...$this->mockInterfaceMethods($mockClassName['fullClassName'], $cloneArguments)
            );
        }

        if (is_array($explicitMethods)) {
            foreach ($explicitMethods as $methodName) {
                if ($class !== null && $class->hasMethod($methodName)) {
                    try {
                        $method = $class->getMethod($methodName);
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new RuntimeException(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    if ($this->canMockMethod($method)) {
                        $mockMethods->addMethods(
                            MockMethod::fromReflection($method, $callOriginalMethods, $cloneArguments)
                        );
                    }
                } else {
                    $mockMethods->addMethods(
                        MockMethod::fromName(
                            $mockClassName['fullClassName'],
                            $methodName,
                            $cloneArguments
                        )
                    );
                }
            }
        }

        $mockedMethods = '';
        $configurable  = [];

        foreach ($mockMethods->asArray() as $mockMethod) {
            $mockedMethods .= $mockMethod->generateCode();
            $configurable[] = new ConfigurableMethod($mockMethod->getName(), $mockMethod->getReturnType());
        }

        $method = '';

        if (!$mockMethods->hasMethod('method') && (!isset($class) || !$class->hasMethod('method'))) {
            $method = PHP_EOL . '    use \PHPUnit\Framework\MockObject\Method;';
        }

        $cloneTrait = '';

        if ($mockedCloneMethod) {
            $cloneTrait = $this->mockedCloneMethod();
        }

        if ($unmockedCloneMethod) {
            $cloneTrait = $this->unmockedCloneMethod();
        }

        $classTemplate->setVar(
            [
                'prologue'          => $prologue ?? '',
                'epilogue'          => $epilogue ?? '',
                'class_declaration' => $this->generateMockClassDeclaration(
                    $mockClassName,
                    $isInterface,
                    $additionalInterfaces
                ),
                'clone'             => $cloneTrait,
                'mock_class_name'   => $mockClassName['className'],
                'mocked_methods'    => $mockedMethods,
                'method'            => $method,
            ]
        );

        return new MockClass(
            $classTemplate->render(),
            $mockClassName['className'],
            $configurable
        );
    }

    /**
     * @param array|string $type
     */
    private function generateClassName($type, string $className, string $prefix): array
    {
        if (is_array($type)) {
            $type = implode('_', $type);
        }

        if ($type[0] === '\\') {
            $type = substr($type, 1);
        }

        $classNameParts = explode('\\', $type);

        if (count($classNameParts) > 1) {
            $type          = array_pop($classNameParts);
            $namespaceName = implode('\\', $classNameParts);
            $fullClassName = $namespaceName . '\\' . $type;
        } else {
            $namespaceName = '';
            $fullClassName = $type;
        }

        if ($className === '') {
            do {
                $className = $prefix . $type . '_' .
                             substr(md5((string) mt_rand()), 0, 8);
            } while (class_exists($className, false));
        }

        return [
            'className'         => $className,
            'originalClassName' => $type,
            'fullClassName'     => $fullClassName,
            'namespaceName'     => $namespaceName,
        ];
    }

    private function generateMockClassDeclaration(array $mockClassName, bool $isInterface, array $additionalInterfaces = []): string
    {
        $buffer = 'class ';

        $additionalInterfaces[] = MockObject::class;
        $interfaces             = implode(', ', $additionalInterfaces);

        if ($isInterface) {
            $buffer .= sprintf(
                '%s implements %s',
                $mockClassName['className'],
                $interfaces
            );

            if (!in_array($mockClassName['originalClassName'], $additionalInterfaces, true)) {
                $buffer .= ', ';

                if (!empty($mockClassName['namespaceName'])) {
                    $buffer .= $mockClassName['namespaceName'] . '\\';
                }

                $buffer .= $mockClassName['originalClassName'];
            }
        } else {
            $buffer .= sprintf(
                '%s extends %s%s implements %s',
                $mockClassName['className'],
                !empty($mockClassName['namespaceName']) ? $mockClassName['namespaceName'] . '\\' : '',
                $mockClassName['originalClassName'],
                $interfaces
            );
        }

        return $buffer;
    }

    private function canMockMethod(ReflectionMethod $method): bool
    {
        return !($this->isConstructor($method) || $method->isFinal() || $method->isPrivate() || $this->isMethodNameBlacklisted($method->getName()));
    }

    private function isMethodNameBlacklisted(string $name): bool
    {
        return isset(self::BLACKLISTED_METHOD_NAMES[$name]);
    }

    private function getTemplate(string $template): Text_Template
    {
        $filename = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR . $template;

        if (!isset(self::$templates[$filename])) {
            self::$templates[$filename] = new Text_Template($filename);
        }

        return self::$templates[$filename];
    }

    /**
     * @see https://github.com/sebastianbergmann/phpunit/issues/4139#issuecomment-605409765
     */
    private function isConstructor(ReflectionMethod $method): bool
    {
        $methodName = strtolower($method->getName());

        if ($methodName === '__construct') {
            return true;
        }

        if (PHP_MAJOR_VERSION >= 8) {
            return false;
        }

        $className = strtolower($method->getDeclaringClass()->getName());

        return $methodName === $className;
    }

    private function mockedCloneMethod(): string
    {
        if (PHP_MAJOR_VERSION >= 8) {
            if (!trait_exists('\PHPUnit\Framework\MockObject\MockedCloneMethodWithVoidReturnType')) {
                eval(self::MOCKED_CLONE_METHOD_WITH_VOID_RETURN_TYPE_TRAIT);
            }

            return PHP_EOL . '    use \PHPUnit\Framework\MockObject\MockedCloneMethodWithVoidReturnType;';
        }

        if (!trait_exists('\PHPUnit\Framework\MockObject\MockedCloneMethodWithoutReturnType')) {
            eval(self::MOCKED_CLONE_METHOD_WITHOUT_RETURN_TYPE_TRAIT);
        }

        return PHP_EOL . '    use \PHPUnit\Framework\MockObject\MockedCloneMethodWithoutReturnType;';
    }

    private function unmockedCloneMethod(): string
    {
        if (PHP_MAJOR_VERSION >= 8) {
            if (!trait_exists('\PHPUnit\Framework\MockObject\UnmockedCloneMethodWithVoidReturnType')) {
                eval(self::UNMOCKED_CLONE_METHOD_WITH_VOID_RETURN_TYPE_TRAIT);
            }

            return PHP_EOL . '    use \PHPUnit\Framework\MockObject\UnmockedCloneMethodWithVoidReturnType;';
        }

        if (!trait_exists('\PHPUnit\Framework\MockObject\UnmockedCloneMethodWithoutReturnType')) {
            eval(self::UNMOCKED_CLONE_METHOD_WITHOUT_RETURN_TYPE_TRAIT);
        }

        return PHP_EOL . '    use \PHPUnit\Framework\MockObject\UnmockedCloneMethodWithoutReturnType;';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function sprintf;
use function strtolower;
use Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Builder\InvocationMocker;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvocationHandler
{
    /**
     * @var Matcher[]
     */
    private $matchers = [];

    /**
     * @var Matcher[]
     */
    private $matcherMap = [];

    /**
     * @var ConfigurableMethod[]
     */
    private $configurableMethods;

    /**
     * @var bool
     */
    private $returnValueGeneration;

    /**
     * @var Throwable
     */
    private $deferredError;

    public function __construct(array $configurableMethods, bool $returnValueGeneration)
    {
        $this->configurableMethods   = $configurableMethods;
        $this->returnValueGeneration = $returnValueGeneration;
    }

    public function hasMatchers(): bool
    {
        foreach ($this->matchers as $matcher) {
            if ($matcher->hasMatchers()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Looks up the match builder with identification $id and returns it.
     *
     * @param string $id The identification of the match builder
     */
    public function lookupMatcher(string $id): ?Matcher
    {
        if (isset($this->matcherMap[$id])) {
            return $this->matcherMap[$id];
        }

        return null;
    }

    /**
     * Registers a matcher with the identification $id. The matcher can later be
     * looked up using lookupMatcher() to figure out if it has been invoked.
     *
     * @param string  $id      The identification of the matcher
     * @param Matcher $matcher The builder which is being registered
     *
     * @throws RuntimeException
     */
    public function registerMatcher(string $id, Matcher $matcher): void
    {
        if (isset($this->matcherMap[$id])) {
            throw new RuntimeException(
                'Matcher with id <' . $id . '> is already registered.'
            );
        }

        $this->matcherMap[$id] = $matcher;
    }

    public function expects(InvocationOrder $rule): InvocationMocker
    {
        $matcher = new Matcher($rule);
        $this->addMatcher($matcher);

        return new InvocationMocker(
            $this,
            $matcher,
            ...$this->configurableMethods
        );
    }

    /**
     * @throws Exception
     *
     * @return mixed|void
     */
    public function invoke(Invocation $invocation)
    {
        $exception      = null;
        $hasReturnValue = false;
        $returnValue    = null;

        foreach ($this->matchers as $match) {
            try {
                if ($match->matches($invocation)) {
                    $value = $match->invoked($invocation);

                    if (!$hasReturnValue) {
                        $returnValue    = $value;
                        $hasReturnValue = true;
                    }
                }
            } catch (Exception $e) {
                $exception = $e;
            }
        }

        if ($exception !== null) {
            throw $exception;
        }

        if ($hasReturnValue) {
            return $returnValue;
        }

        if (!$this->returnValueGeneration) {
            $exception = new ExpectationFailedException(
                sprintf(
                    'Return value inference disabled and no expectation set up for %s::%s()',
                    $invocation->getClassName(),
                    $invocation->getMethodName()
                )
            );

            if (strtolower($invocation->getMethodName()) === '__tostring') {
                $this->deferredError = $exception;

                return '';
            }

            throw $exception;
        }

        return $invocation->generateReturnValue();
    }

    public function matches(Invocation $invocation): bool
    {
        foreach ($this->matchers as $matcher) {
            if (!$matcher->matches($invocation)) {
                return false;
            }
        }

        return true;
    }

    /**
     * @throws \PHPUnit\Framework\ExpectationFailedException
     */
    public function verify(): void
    {
        foreach ($this->matchers as $matcher) {
            $matcher->verify();
        }

        if ($this->deferredError) {
            throw $this->deferredError;
        }
    }

    private function addMatcher(Matcher $matcher): void
    {
        $this->matchers[] = $matcher;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

use PHPUnit\Framework\MockObject\Stub\Stub;
use Throwable;

interface InvocationStubber
{
    public function will(Stub $stub): Identity;

    /** @return self */
    public function willReturn($value, ...$nextValues)/*: self */;

    /**
     * @param mixed $reference
     *
     * @return self
     */
    public function willReturnReference(&$reference)/*: self */;

    /**
     * @param array<int, array<int, mixed>> $valueMap
     *
     * @return self
     */
    public function willReturnMap(array $valueMap)/*: self */;

    /**
     * @param int $argumentIndex
     *
     * @return self
     */
    public function willReturnArgument($argumentIndex)/*: self */;

    /**
     * @param callable $callback
     *
     * @return self
     */
    public function willReturnCallback($callback)/*: self */;

    /** @return self */
    public function willReturnSelf()/*: self */;

    /**
     * @param mixed $values
     *
     * @return self
     */
    public function willReturnOnConsecutiveCalls(...$values)/*: self */;

    /** @return self */
    public function willThrowException(Throwable $exception)/*: self */;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

use function array_map;
use function array_merge;
use function count;
use function get_class;
use function gettype;
use function in_array;
use function is_object;
use function is_string;
use function sprintf;
use function strtolower;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\MockObject\ConfigurableMethod;
use PHPUnit\Framework\MockObject\IncompatibleReturnValueException;
use PHPUnit\Framework\MockObject\InvocationHandler;
use PHPUnit\Framework\MockObject\Matcher;
use PHPUnit\Framework\MockObject\Rule;
use PHPUnit\Framework\MockObject\RuntimeException;
use PHPUnit\Framework\MockObject\Stub\ConsecutiveCalls;
use PHPUnit\Framework\MockObject\Stub\Exception;
use PHPUnit\Framework\MockObject\Stub\ReturnArgument;
use PHPUnit\Framework\MockObject\Stub\ReturnCallback;
use PHPUnit\Framework\MockObject\Stub\ReturnReference;
use PHPUnit\Framework\MockObject\Stub\ReturnSelf;
use PHPUnit\Framework\MockObject\Stub\ReturnStub;
use PHPUnit\Framework\MockObject\Stub\ReturnValueMap;
use PHPUnit\Framework\MockObject\Stub\Stub;
use Throwable;

final class InvocationMocker implements InvocationStubber, MethodNameMatch
{
    /**
     * @var InvocationHandler
     */
    private $invocationHandler;

    /**
     * @var Matcher
     */
    private $matcher;

    /**
     * @var ConfigurableMethod[]
     */
    private $configurableMethods;

    public function __construct(InvocationHandler $handler, Matcher $matcher, ConfigurableMethod ...$configurableMethods)
    {
        $this->invocationHandler   = $handler;
        $this->matcher             = $matcher;
        $this->configurableMethods = $configurableMethods;
    }

    /**
     * @return $this
     */
    public function id($id): self
    {
        $this->invocationHandler->registerMatcher($id, $this->matcher);

        return $this;
    }

    /**
     * @return $this
     */
    public function will(Stub $stub): Identity
    {
        $this->matcher->setStub($stub);

        return $this;
    }

    public function willReturn($value, ...$nextValues): self
    {
        if (count($nextValues) === 0) {
            $this->ensureTypeOfReturnValues([$value]);

            $stub = $value instanceof Stub ? $value : new ReturnStub($value);
        } else {
            $values = array_merge([$value], $nextValues);

            $this->ensureTypeOfReturnValues($values);

            $stub = new ConsecutiveCalls($values);
        }

        return $this->will($stub);
    }

    public function willReturnReference(&$reference): self
    {
        $stub = new ReturnReference($reference);

        return $this->will($stub);
    }

    public function willReturnMap(array $valueMap): self
    {
        $stub = new ReturnValueMap($valueMap);

        return $this->will($stub);
    }

    public function willReturnArgument($argumentIndex): self
    {
        $stub = new ReturnArgument($argumentIndex);

        return $this->will($stub);
    }

    public function willReturnCallback($callback): self
    {
        $stub = new ReturnCallback($callback);

        return $this->will($stub);
    }

    public function willReturnSelf(): self
    {
        $stub = new ReturnSelf;

        return $this->will($stub);
    }

    public function willReturnOnConsecutiveCalls(...$values): self
    {
        $stub = new ConsecutiveCalls($values);

        return $this->will($stub);
    }

    public function willThrowException(Throwable $exception): self
    {
        $stub = new Exception($exception);

        return $this->will($stub);
    }

    /**
     * @return $this
     */
    public function after($id): self
    {
        $this->matcher->setAfterMatchBuilderId($id);

        return $this;
    }

    /**
     * @throws RuntimeException
     *
     * @return $this
     */
    public function with(...$arguments): self
    {
        $this->canDefineParameters();

        $this->matcher->setParametersRule(new Rule\Parameters($arguments));

        return $this;
    }

    /**
     * @param array ...$arguments
     *
     * @throws RuntimeException
     *
     * @return $this
     */
    public function withConsecutive(...$arguments): self
    {
        $this->canDefineParameters();

        $this->matcher->setParametersRule(new Rule\ConsecutiveParameters($arguments));

        return $this;
    }

    /**
     * @throws RuntimeException
     *
     * @return $this
     */
    public function withAnyParameters(): self
    {
        $this->canDefineParameters();

        $this->matcher->setParametersRule(new Rule\AnyParameters);

        return $this;
    }

    /**
     * @param Constraint|string $constraint
     *
     * @throws RuntimeException
     *
     * @return $this
     */
    public function method($constraint): self
    {
        if ($this->matcher->hasMethodNameRule()) {
            throw new RuntimeException(
                'Rule for method name is already defined, cannot redefine'
            );
        }

        $configurableMethodNames = array_map(
            static function (ConfigurableMethod $configurable)
            {
                return strtolower($configurable->getName());
            },
            $this->configurableMethods
        );

        if (is_string($constraint) && !in_array(strtolower($constraint), $configurableMethodNames, true)) {
            throw new RuntimeException(
                sprintf(
                    'Trying to configure method "%s" which cannot be configured because it does not exist, has not been specified, is final, or is static',
                    $constraint
                )
            );
        }

        $this->matcher->setMethodNameRule(new Rule\MethodName($constraint));

        return $this;
    }

    /**
     * Validate that a parameters rule can be defined, throw exceptions otherwise.
     *
     * @throws RuntimeException
     */
    private function canDefineParameters(): void
    {
        if (!$this->matcher->hasMethodNameRule()) {
            throw new RuntimeException(
                'Rule for method name is not defined, cannot define rule for parameters ' .
                'without one'
            );
        }

        if ($this->matcher->hasParametersRule()) {
            throw new RuntimeException(
                'Rule for parameters is already defined, cannot redefine'
            );
        }
    }

    private function getConfiguredMethod(): ?ConfigurableMethod
    {
        $configuredMethod = null;

        foreach ($this->configurableMethods as $configurableMethod) {
            if ($this->matcher->getMethodNameRule()->matchesName($configurableMethod->getName())) {
                if ($configuredMethod !== null) {
                    return null;
                }

                $configuredMethod = $configurableMethod;
            }
        }

        return $configuredMethod;
    }

    private function ensureTypeOfReturnValues(array $values): void
    {
        $configuredMethod = $this->getConfiguredMethod();

        if ($configuredMethod === null) {
            return;
        }

        foreach ($values as $value) {
            if (!$configuredMethod->mayReturn($value)) {
                throw new IncompatibleReturnValueException(
                    sprintf(
                        'Method %s may not return value of type %s, its return declaration is "%s"',
                        $configuredMethod->getName(),
                        is_object($value) ? get_class($value) : gettype($value),
                        $configuredMethod->getReturnTypeDeclaration()
                    )
                );
            }
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface ParametersMatch extends Match_
{
    /**
     * Sets the parameters to match for, each parameter to this function will
     * be part of match. To perform specific matches or constraints create a
     * new PHPUnit\Framework\Constraint\Constraint and use it for the parameter.
     * If the parameter value is not a constraint it will use the
     * PHPUnit\Framework\Constraint\IsEqual for the value.
     *
     * Some examples:
     * <code>
     * // match first parameter with value 2
     * $b->with(2);
     * // match first parameter with value 'smock' and second identical to 42
     * $b->with('smock', new PHPUnit\Framework\Constraint\IsEqual(42));
     * </code>
     *
     * @return ParametersMatch
     */
    public function with(...$arguments);

    /**
     * Sets a rule which allows any kind of parameters.
     *
     * Some examples:
     * <code>
     * // match any number of parameters
     * $b->withAnyParameters();
     * </code>
     *
     * @return ParametersMatch
     */
    public function withAnyParameters();
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Identity
{
    /**
     * Sets the identification of the expectation to $id.
     *
     * @note The identifier is unique per mock object.
     *
     * @param string $id unique identification of expectation
     */
    public function id($id);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

use PHPUnit\Framework\MockObject\Stub\Stub as BaseStub;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Stub extends Identity
{
    /**
     * Stubs the matching method with the stub object $stub. Any invocations of
     * the matched method will now be handled by the stub instead.
     */
    public function will(BaseStub $stub): Identity;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Match_ extends Stub
{
    /**
     * Defines the expectation which must occur before the current is valid.
     *
     * @param string $id the identification of the expectation that should
     *                   occur before this one
     *
     * @return Stub
     */
    public function after($id);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Builder;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface MethodNameMatch extends ParametersMatch
{
    /**
     * Adds a new method name match and returns the parameter match object for
     * further matching possibilities.
     *
     * @param \PHPUnit\Framework\Constraint\Constraint $constraint Constraint for matching method, if a string is passed it will use the PHPUnit_Framework_Constraint_IsEqual
     *
     * @return ParametersMatch
     */
    public function method($constraint);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ConfigurableMethodsAlreadyInitializedException extends \PHPUnit\Framework\Exception implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class RuntimeException extends \RuntimeException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class IncompatibleReturnValueException extends \PHPUnit\Framework\Exception implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class BadMethodCallException extends \BadMethodCallException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Exception extends Throwable
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use PHPUnit\Framework\ExpectationFailedException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Verifiable
{
    /**
     * Verifies that the current expectation is valid. If everything is OK the
     * code should just return, if not it must throw an exception.
     *
     * @throws ExpectationFailedException
     */
    public function verify(): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject;

use function class_exists;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MockTrait implements MockType
{
    /**
     * @var string
     */
    private $classCode;

    /**
     * @var string
     */
    private $mockName;

    public function __construct(string $classCode, string $mockName)
    {
        $this->classCode = $classCode;
        $this->mockName  = $mockName;
    }

    public function generate(): string
    {
        if (!class_exists($this->mockName, false)) {
            eval($this->classCode);
        }

        return $this->mockName;
    }

    public function getClassCode(): string
    {
        return $this->classCode;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Error;

final class Warning extends Error
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Error;

use PHPUnit\Framework\Exception;

class Error extends Exception
{
    public function __construct(string $message, int $code, string $file, int $line, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);

        $this->file = $file;
        $this->line = $line;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Error;

final class Notice extends Error
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Error;

final class Deprecated extends Error
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use const LC_ALL;
use const LC_COLLATE;
use const LC_CTYPE;
use const LC_MESSAGES;
use const LC_MONETARY;
use const LC_NUMERIC;
use const LC_TIME;
use const PATHINFO_FILENAME;
use const PHP_EOL;
use const PHP_URL_PATH;
use function array_filter;
use function array_flip;
use function array_keys;
use function array_merge;
use function array_unique;
use function array_values;
use function assert;
use function basename;
use function call_user_func;
use function chdir;
use function class_exists;
use function clearstatcache;
use function count;
use function defined;
use function explode;
use function get_class;
use function get_include_path;
use function getcwd;
use function implode;
use function in_array;
use function ini_set;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function libxml_clear_errors;
use function method_exists;
use function ob_end_clean;
use function ob_get_contents;
use function ob_get_level;
use function ob_start;
use function parse_url;
use function pathinfo;
use function preg_replace;
use function serialize;
use function setlocale;
use function sprintf;
use function strlen;
use function strpos;
use function substr;
use function trim;
use function var_export;
use DeepCopy\DeepCopy;
use PHPUnit\Framework\Constraint\Exception as ExceptionConstraint;
use PHPUnit\Framework\Constraint\ExceptionCode;
use PHPUnit\Framework\Constraint\ExceptionMessage;
use PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression;
use PHPUnit\Framework\Constraint\LogicalOr;
use PHPUnit\Framework\Error\Deprecated;
use PHPUnit\Framework\Error\Error;
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning as WarningError;
use PHPUnit\Framework\MockObject\Generator as MockGenerator;
use PHPUnit\Framework\MockObject\MockBuilder;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount as AnyInvokedCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtIndex as InvokedAtIndexMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtLeastCount as InvokedAtLeastCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtLeastOnce as InvokedAtLeastOnceMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedAtMostCount as InvokedAtMostCountMatcher;
use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCountMatcher;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\MockObject\Stub\ConsecutiveCalls as ConsecutiveCallsStub;
use PHPUnit\Framework\MockObject\Stub\Exception as ExceptionStub;
use PHPUnit\Framework\MockObject\Stub\ReturnArgument as ReturnArgumentStub;
use PHPUnit\Framework\MockObject\Stub\ReturnCallback as ReturnCallbackStub;
use PHPUnit\Framework\MockObject\Stub\ReturnSelf as ReturnSelfStub;
use PHPUnit\Framework\MockObject\Stub\ReturnStub;
use PHPUnit\Framework\MockObject\Stub\ReturnValueMap as ReturnValueMapStub;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\Exception as UtilException;
use PHPUnit\Util\GlobalState;
use PHPUnit\Util\PHP\AbstractPhpProcess;
use PHPUnit\Util\Test as TestUtil;
use PHPUnit\Util\Type;
use Prophecy\Exception\Prediction\PredictionException;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophet;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Comparator\Factory as ComparatorFactory;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Exporter\Exporter;
use SebastianBergmann\GlobalState\Blacklist;
use SebastianBergmann\GlobalState\Restorer;
use SebastianBergmann\GlobalState\Snapshot;
use SebastianBergmann\ObjectEnumerator\Enumerator;
use Text_Template;
use Throwable;

abstract class TestCase extends Assert implements SelfDescribing, Test
{
    private const LOCALE_CATEGORIES = [LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME];

    /**
     * @var ?bool
     */
    protected $backupGlobals;

    /**
     * @var string[]
     */
    protected $backupGlobalsBlacklist = [];

    /**
     * @var bool
     */
    protected $backupStaticAttributes;

    /**
     * @var array<string,array<int,string>>
     */
    protected $backupStaticAttributesBlacklist = [];

    /**
     * @var bool
     */
    protected $runTestInSeparateProcess;

    /**
     * @var bool
     */
    protected $preserveGlobalState = true;

    /**
     * @var bool
     */
    private $runClassInSeparateProcess;

    /**
     * @var bool
     */
    private $inIsolation = false;

    /**
     * @var array
     */
    private $data;

    /**
     * @var string
     */
    private $dataName;

    /**
     * @var null|string
     */
    private $expectedException;

    /**
     * @var null|string
     */
    private $expectedExceptionMessage;

    /**
     * @var null|string
     */
    private $expectedExceptionMessageRegExp;

    /**
     * @var null|int|string
     */
    private $expectedExceptionCode;

    /**
     * @var string
     */
    private $name = '';

    /**
     * @var string[]
     */
    private $dependencies = [];

    /**
     * @var array
     */
    private $dependencyInput = [];

    /**
     * @var array<string,string>
     */
    private $iniSettings = [];

    /**
     * @var array
     */
    private $locale = [];

    /**
     * @var MockObject[]
     */
    private $mockObjects = [];

    /**
     * @var MockGenerator
     */
    private $mockObjectGenerator;

    /**
     * @var int
     */
    private $status = BaseTestRunner::STATUS_UNKNOWN;

    /**
     * @var string
     */
    private $statusMessage = '';

    /**
     * @var int
     */
    private $numAssertions = 0;

    /**
     * @var TestResult
     */
    private $result;

    /**
     * @var mixed
     */
    private $testResult;

    /**
     * @var string
     */
    private $output = '';

    /**
     * @var string
     */
    private $outputExpectedRegex;

    /**
     * @var string
     */
    private $outputExpectedString;

    /**
     * @var mixed
     */
    private $outputCallback = false;

    /**
     * @var bool
     */
    private $outputBufferingActive = false;

    /**
     * @var int
     */
    private $outputBufferingLevel;

    /**
     * @var bool
     */
    private $outputRetrievedForAssertion = false;

    /**
     * @var Snapshot
     */
    private $snapshot;

    /**
     * @var \Prophecy\Prophet
     */
    private $prophet;

    /**
     * @var bool
     */
    private $beStrictAboutChangesToGlobalState = false;

    /**
     * @var bool
     */
    private $registerMockObjectsFromTestArgumentsRecursively = false;

    /**
     * @var string[]
     */
    private $warnings = [];

    /**
     * @var string[]
     */
    private $groups = [];

    /**
     * @var bool
     */
    private $doesNotPerformAssertions = false;

    /**
     * @var Comparator[]
     */
    private $customComparators = [];

    /**
     * @var string[]
     */
    private $doubledTypes = [];

    /**
     * @var bool
     */
    private $deprecatedExpectExceptionMessageRegExpUsed = false;

    /**
     * Returns a matcher that matches when the method is executed
     * zero or more times.
     */
    public static function any(): AnyInvokedCountMatcher
    {
        return new AnyInvokedCountMatcher;
    }

    /**
     * Returns a matcher that matches when the method is never executed.
     */
    public static function never(): InvokedCountMatcher
    {
        return new InvokedCountMatcher(0);
    }

    /**
     * Returns a matcher that matches when the method is executed
     * at least N times.
     */
    public static function atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher
    {
        return new InvokedAtLeastCountMatcher(
            $requiredInvocations
        );
    }

    /**
     * Returns a matcher that matches when the method is executed at least once.
     */
    public static function atLeastOnce(): InvokedAtLeastOnceMatcher
    {
        return new InvokedAtLeastOnceMatcher;
    }

    /**
     * Returns a matcher that matches when the method is executed exactly once.
     */
    public static function once(): InvokedCountMatcher
    {
        return new InvokedCountMatcher(1);
    }

    /**
     * Returns a matcher that matches when the method is executed
     * exactly $count times.
     */
    public static function exactly(int $count): InvokedCountMatcher
    {
        return new InvokedCountMatcher($count);
    }

    /**
     * Returns a matcher that matches when the method is executed
     * at most N times.
     */
    public static function atMost(int $allowedInvocations): InvokedAtMostCountMatcher
    {
        return new InvokedAtMostCountMatcher($allowedInvocations);
    }

    /**
     * Returns a matcher that matches when the method is executed
     * at the given index.
     */
    public static function at(int $index): InvokedAtIndexMatcher
    {
        return new InvokedAtIndexMatcher($index);
    }

    public static function returnValue($value): ReturnStub
    {
        return new ReturnStub($value);
    }

    public static function returnValueMap(array $valueMap): ReturnValueMapStub
    {
        return new ReturnValueMapStub($valueMap);
    }

    public static function returnArgument(int $argumentIndex): ReturnArgumentStub
    {
        return new ReturnArgumentStub($argumentIndex);
    }

    public static function returnCallback($callback): ReturnCallbackStub
    {
        return new ReturnCallbackStub($callback);
    }

    /**
     * Returns the current object.
     *
     * This method is useful when mocking a fluent interface.
     */
    public static function returnSelf(): ReturnSelfStub
    {
        return new ReturnSelfStub;
    }

    public static function throwException(Throwable $exception): ExceptionStub
    {
        return new ExceptionStub($exception);
    }

    public static function onConsecutiveCalls(...$args): ConsecutiveCallsStub
    {
        return new ConsecutiveCallsStub($args);
    }

    /**
     * @param string $name
     * @param string $dataName
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        if ($name !== null) {
            $this->setName($name);
        }

        $this->data     = $data;
        $this->dataName = $dataName;
    }

    /**
     * This method is called before the first test of this test class is run.
     */
    public static function setUpBeforeClass(): void
    {
    }

    /**
     * This method is called after the last test of this test class is run.
     */
    public static function tearDownAfterClass(): void
    {
    }

    /**
     * This method is called before each test.
     */
    protected function setUp(): void
    {
    }

    /**
     * Performs assertions shared by all tests of a test case.
     *
     * This method is called between setUp() and test.
     */
    protected function assertPreConditions(): void
    {
    }

    /**
     * Performs assertions shared by all tests of a test case.
     *
     * This method is called between test and tearDown().
     */
    protected function assertPostConditions(): void
    {
    }

    /**
     * This method is called after each test.
     */
    protected function tearDown(): void
    {
    }

    /**
     * Returns a string representation of the test case.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     */
    public function toString(): string
    {
        try {
            $class = new ReflectionClass($this);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        $buffer = sprintf(
            '%s::%s',
            $class->name,
            $this->getName(false)
        );

        return $buffer . $this->getDataSetAsString();
    }

    public function count(): int
    {
        return 1;
    }

    public function getActualOutputForAssertion(): string
    {
        $this->outputRetrievedForAssertion = true;

        return $this->getActualOutput();
    }

    public function expectOutputRegex(string $expectedRegex): void
    {
        $this->outputExpectedRegex = $expectedRegex;
    }

    public function expectOutputString(string $expectedString): void
    {
        $this->outputExpectedString = $expectedString;
    }

    /**
     * @psalm-param class-string<\Throwable> $exception
     */
    public function expectException(string $exception): void
    {
        $this->expectedException = $exception;
    }

    /**
     * @param int|string $code
     */
    public function expectExceptionCode($code): void
    {
        $this->expectedExceptionCode = $code;
    }

    public function expectExceptionMessage(string $message): void
    {
        $this->expectedExceptionMessage = $message;
    }

    public function expectExceptionMessageMatches(string $regularExpression): void
    {
        $this->expectedExceptionMessageRegExp = $regularExpression;
    }

    /**
     * @deprecated Use expectExceptionMessageMatches() instead
     */
    public function expectExceptionMessageRegExp(string $regularExpression): void
    {
        $this->deprecatedExpectExceptionMessageRegExpUsed = true;

        $this->expectExceptionMessageMatches($regularExpression);
    }

    /**
     * Sets up an expectation for an exception to be raised by the code under test.
     * Information for expected exception class, expected exception message, and
     * expected exception code are retrieved from a given Exception object.
     */
    public function expectExceptionObject(\Exception $exception): void
    {
        $this->expectException(get_class($exception));
        $this->expectExceptionMessage($exception->getMessage());
        $this->expectExceptionCode($exception->getCode());
    }

    public function expectNotToPerformAssertions(): void
    {
        $this->doesNotPerformAssertions = true;
    }

    public function expectDeprecation(): void
    {
        $this->expectException(Deprecated::class);
    }

    public function expectDeprecationMessage(string $message): void
    {
        $this->expectExceptionMessage($message);
    }

    public function expectDeprecationMessageMatches(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }

    public function expectNotice(): void
    {
        $this->expectException(Notice::class);
    }

    public function expectNoticeMessage(string $message): void
    {
        $this->expectExceptionMessage($message);
    }

    public function expectNoticeMessageMatches(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }

    public function expectWarning(): void
    {
        $this->expectException(WarningError::class);
    }

    public function expectWarningMessage(string $message): void
    {
        $this->expectExceptionMessage($message);
    }

    public function expectWarningMessageMatches(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }

    public function expectError(): void
    {
        $this->expectException(Error::class);
    }

    public function expectErrorMessage(string $message): void
    {
        $this->expectExceptionMessage($message);
    }

    public function expectErrorMessageMatches(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }

    public function getStatus(): int
    {
        return $this->status;
    }

    public function markAsRisky(): void
    {
        $this->status = BaseTestRunner::STATUS_RISKY;
    }

    public function getStatusMessage(): string
    {
        return $this->statusMessage;
    }

    public function hasFailed(): bool
    {
        $status = $this->getStatus();

        return $status === BaseTestRunner::STATUS_FAILURE || $status === BaseTestRunner::STATUS_ERROR;
    }

    /**
     * Runs the test case and collects the results in a TestResult object.
     * If no TestResult object is passed a new one will be created.
     *
     * @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     * @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
     * @throws \SebastianBergmann\CodeCoverage\RuntimeException
     * @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws CodeCoverageException
     * @throws UtilException
     */
    public function run(TestResult $result = null): TestResult
    {
        if ($result === null) {
            $result = $this->createResult();
        }

        if (!$this instanceof WarningTestCase) {
            $this->setTestResultObject($result);
        }

        if (!$this instanceof WarningTestCase &&
            !$this instanceof SkippedTestCase &&
            !$this->handleDependencies()) {
            return $result;
        }

        if ($this->runInSeparateProcess()) {
            $runEntireClass = $this->runClassInSeparateProcess && !$this->runTestInSeparateProcess;

            try {
                $class = new ReflectionClass($this);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if ($runEntireClass) {
                $template = new Text_Template(
                    __DIR__ . '/../Util/PHP/Template/TestCaseClass.tpl'
                );
            } else {
                $template = new Text_Template(
                    __DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl'
                );
            }

            if ($this->preserveGlobalState) {
                $constants     = GlobalState::getConstantsAsString();
                $globals       = GlobalState::getGlobalsAsString();
                $includedFiles = GlobalState::getIncludedFilesAsString();
                $iniSettings   = GlobalState::getIniSettingsAsString();
            } else {
                $constants = '';

                if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
                    $globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], true) . ";\n";
                } else {
                    $globals = '';
                }

                $includedFiles = '';
                $iniSettings   = '';
            }

            $coverage                                   = $result->getCollectCodeCoverageInformation() ? 'true' : 'false';
            $isStrictAboutTestsThatDoNotTestAnything    = $result->isStrictAboutTestsThatDoNotTestAnything() ? 'true' : 'false';
            $isStrictAboutOutputDuringTests             = $result->isStrictAboutOutputDuringTests() ? 'true' : 'false';
            $enforcesTimeLimit                          = $result->enforcesTimeLimit() ? 'true' : 'false';
            $isStrictAboutTodoAnnotatedTests            = $result->isStrictAboutTodoAnnotatedTests() ? 'true' : 'false';
            $isStrictAboutResourceUsageDuringSmallTests = $result->isStrictAboutResourceUsageDuringSmallTests() ? 'true' : 'false';

            if (defined('PHPUNIT_COMPOSER_INSTALL')) {
                $composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true);
            } else {
                $composerAutoload = '\'\'';
            }

            if (defined('__PHPUNIT_PHAR__')) {
                $phar = var_export(__PHPUNIT_PHAR__, true);
            } else {
                $phar = '\'\'';
            }

            if ($result->getCodeCoverage()) {
                $codeCoverageFilter = $result->getCodeCoverage()->filter();
            } else {
                $codeCoverageFilter = null;
            }

            $data               = var_export(serialize($this->data), true);
            $dataName           = var_export($this->dataName, true);
            $dependencyInput    = var_export(serialize($this->dependencyInput), true);
            $includePath        = var_export(get_include_path(), true);
            $codeCoverageFilter = var_export(serialize($codeCoverageFilter), true);
            // must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC
            // the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences
            $data               = "'." . $data . ".'";
            $dataName           = "'.(" . $dataName . ").'";
            $dependencyInput    = "'." . $dependencyInput . ".'";
            $includePath        = "'." . $includePath . ".'";
            $codeCoverageFilter = "'." . $codeCoverageFilter . ".'";

            $configurationFilePath = $GLOBALS['__PHPUNIT_CONFIGURATION_FILE'] ?? '';

            $var = [
                'composerAutoload'                           => $composerAutoload,
                'phar'                                       => $phar,
                'filename'                                   => $class->getFileName(),
                'className'                                  => $class->getName(),
                'collectCodeCoverageInformation'             => $coverage,
                'data'                                       => $data,
                'dataName'                                   => $dataName,
                'dependencyInput'                            => $dependencyInput,
                'constants'                                  => $constants,
                'globals'                                    => $globals,
                'include_path'                               => $includePath,
                'included_files'                             => $includedFiles,
                'iniSettings'                                => $iniSettings,
                'isStrictAboutTestsThatDoNotTestAnything'    => $isStrictAboutTestsThatDoNotTestAnything,
                'isStrictAboutOutputDuringTests'             => $isStrictAboutOutputDuringTests,
                'enforcesTimeLimit'                          => $enforcesTimeLimit,
                'isStrictAboutTodoAnnotatedTests'            => $isStrictAboutTodoAnnotatedTests,
                'isStrictAboutResourceUsageDuringSmallTests' => $isStrictAboutResourceUsageDuringSmallTests,
                'codeCoverageFilter'                         => $codeCoverageFilter,
                'configurationFilePath'                      => $configurationFilePath,
                'name'                                       => $this->getName(false),
            ];

            if (!$runEntireClass) {
                $var['methodName'] = $this->name;
            }

            $template->setVar($var);

            $php = AbstractPhpProcess::factory();
            $php->runTestJob($template->render(), $this, $result);
        } else {
            $result->run($this);
        }

        $this->result = null;

        return $result;
    }

    /**
     * Returns a builder object to create mock objects using a fluent interface.
     *
     * @param string|string[] $className
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string[] $className
     *
     * @psalm-return MockBuilder<RealInstanceType>
     */
    public function getMockBuilder($className): MockBuilder
    {
        if (!is_string($className)) {
            $this->addWarning('Passing an array of interface names to getMockBuilder() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
        }

        $this->recordDoubledType($className);

        return new MockBuilder($this, $className);
    }

    public function registerComparator(Comparator $comparator): void
    {
        ComparatorFactory::getInstance()->register($comparator);

        $this->customComparators[] = $comparator;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     *
     * @deprecated Invoking this method has no effect; it will be removed in PHPUnit 9
     */
    public function setUseErrorHandler(bool $useErrorHandler): void
    {
    }

    /**
     * @return string[]
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function doubledTypes(): array
    {
        return array_unique($this->doubledTypes);
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getGroups(): array
    {
        return $this->groups;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setGroups(array $groups): void
    {
        $this->groups = $groups;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getAnnotations(): array
    {
        return TestUtil::parseTestMethodAnnotations(
            static::class,
            $this->name
        );
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getName(bool $withDataSet = true): string
    {
        if ($withDataSet) {
            return $this->name . $this->getDataSetAsString(false);
        }

        return $this->name;
    }

    /**
     * Returns the size of the test.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getSize(): int
    {
        return TestUtil::getSize(
            static::class,
            $this->getName(false)
        );
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function hasSize(): bool
    {
        return $this->getSize() !== TestUtil::UNKNOWN;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function isSmall(): bool
    {
        return $this->getSize() === TestUtil::SMALL;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function isMedium(): bool
    {
        return $this->getSize() === TestUtil::MEDIUM;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function isLarge(): bool
    {
        return $this->getSize() === TestUtil::LARGE;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getActualOutput(): string
    {
        if (!$this->outputBufferingActive) {
            return $this->output;
        }

        return (string) ob_get_contents();
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function hasOutput(): bool
    {
        if ($this->output === '') {
            return false;
        }

        if ($this->hasExpectationOnOutput()) {
            return false;
        }

        return true;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function doesNotPerformAssertions(): bool
    {
        return $this->doesNotPerformAssertions;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function hasExpectationOnOutput(): bool
    {
        return is_string($this->outputExpectedString) || is_string($this->outputExpectedRegex) || $this->outputRetrievedForAssertion;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getExpectedException(): ?string
    {
        return $this->expectedException;
    }

    /**
     * @return null|int|string
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getExpectedExceptionCode()
    {
        return $this->expectedExceptionCode;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getExpectedExceptionMessage(): ?string
    {
        return $this->expectedExceptionMessage;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getExpectedExceptionMessageRegExp(): ?string
    {
        return $this->expectedExceptionMessageRegExp;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): void
    {
        $this->registerMockObjectsFromTestArgumentsRecursively = $flag;
    }

    /**
     * @throws Throwable
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function runBare(): void
    {
        $this->numAssertions = 0;

        $this->snapshotGlobalState();
        $this->startOutputBuffering();
        clearstatcache();
        $currentWorkingDirectory = getcwd();

        $hookMethods = TestUtil::getHookMethods(static::class);

        $hasMetRequirements = false;

        try {
            $this->checkRequirements();
            $hasMetRequirements = true;

            if ($this->inIsolation) {
                foreach ($hookMethods['beforeClass'] as $method) {
                    $this->{$method}();
                }
            }

            $this->setExpectedExceptionFromAnnotation();
            $this->setDoesNotPerformAssertionsFromAnnotation();

            foreach ($hookMethods['before'] as $method) {
                $this->{$method}();
            }

            $this->assertPreConditions();
            $this->testResult = $this->runTest();
            $this->verifyMockObjects();
            $this->assertPostConditions();

            if (!empty($this->warnings)) {
                throw new Warning(
                    implode(
                        "\n",
                        array_unique($this->warnings)
                    )
                );
            }

            $this->status = BaseTestRunner::STATUS_PASSED;
        } catch (IncompleteTest $e) {
            $this->status        = BaseTestRunner::STATUS_INCOMPLETE;
            $this->statusMessage = $e->getMessage();
        } catch (SkippedTest $e) {
            $this->status        = BaseTestRunner::STATUS_SKIPPED;
            $this->statusMessage = $e->getMessage();
        } catch (Warning $e) {
            $this->status        = BaseTestRunner::STATUS_WARNING;
            $this->statusMessage = $e->getMessage();
        } catch (AssertionFailedError $e) {
            $this->status        = BaseTestRunner::STATUS_FAILURE;
            $this->statusMessage = $e->getMessage();
        } catch (PredictionException $e) {
            $this->status        = BaseTestRunner::STATUS_FAILURE;
            $this->statusMessage = $e->getMessage();
        } catch (Throwable $_e) {
            $e                   = $_e;
            $this->status        = BaseTestRunner::STATUS_ERROR;
            $this->statusMessage = $_e->getMessage();
        }

        $this->mockObjects = [];
        $this->prophet     = null;

        // Tear down the fixture. An exception raised in tearDown() will be
        // caught and passed on when no exception was raised before.
        try {
            if ($hasMetRequirements) {
                foreach ($hookMethods['after'] as $method) {
                    $this->{$method}();
                }

                if ($this->inIsolation) {
                    foreach ($hookMethods['afterClass'] as $method) {
                        $this->{$method}();
                    }
                }
            }
        } catch (Throwable $_e) {
            $e = $e ?? $_e;
        }

        try {
            $this->stopOutputBuffering();
        } catch (RiskyTestError $_e) {
            $e = $e ?? $_e;
        }

        if (isset($_e)) {
            $this->status        = BaseTestRunner::STATUS_ERROR;
            $this->statusMessage = $_e->getMessage();
        }

        clearstatcache();

        if ($currentWorkingDirectory !== getcwd()) {
            chdir($currentWorkingDirectory);
        }

        $this->restoreGlobalState();
        $this->unregisterCustomComparators();
        $this->cleanupIniSettings();
        $this->cleanupLocaleSettings();
        libxml_clear_errors();

        // Perform assertion on output.
        if (!isset($e)) {
            try {
                if ($this->outputExpectedRegex !== null) {
                    $this->assertRegExp($this->outputExpectedRegex, $this->output);
                } elseif ($this->outputExpectedString !== null) {
                    $this->assertEquals($this->outputExpectedString, $this->output);
                }
            } catch (Throwable $_e) {
                $e = $_e;
            }
        }

        // Workaround for missing "finally".
        if (isset($e)) {
            if ($e instanceof PredictionException) {
                $e = new AssertionFailedError($e->getMessage());
            }

            $this->onNotSuccessfulTest($e);
        }
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * @param string[] $dependencies
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setDependencies(array $dependencies): void
    {
        $this->dependencies = $dependencies;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function hasDependencies(): bool
    {
        return count($this->dependencies) > 0;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setDependencyInput(array $dependencyInput): void
    {
        $this->dependencyInput = $dependencyInput;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getDependencyInput(): array
    {
        return $this->dependencyInput;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setBeStrictAboutChangesToGlobalState(?bool $beStrictAboutChangesToGlobalState): void
    {
        $this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setBackupGlobals(?bool $backupGlobals): void
    {
        if ($this->backupGlobals === null && $backupGlobals !== null) {
            $this->backupGlobals = $backupGlobals;
        }
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setBackupStaticAttributes(?bool $backupStaticAttributes): void
    {
        if ($this->backupStaticAttributes === null && $backupStaticAttributes !== null) {
            $this->backupStaticAttributes = $backupStaticAttributes;
        }
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setRunTestInSeparateProcess(bool $runTestInSeparateProcess): void
    {
        if ($this->runTestInSeparateProcess === null) {
            $this->runTestInSeparateProcess = $runTestInSeparateProcess;
        }
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setRunClassInSeparateProcess(bool $runClassInSeparateProcess): void
    {
        if ($this->runClassInSeparateProcess === null) {
            $this->runClassInSeparateProcess = $runClassInSeparateProcess;
        }
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setPreserveGlobalState(bool $preserveGlobalState): void
    {
        $this->preserveGlobalState = $preserveGlobalState;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setInIsolation(bool $inIsolation): void
    {
        $this->inIsolation = $inIsolation;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function isInIsolation(): bool
    {
        return $this->inIsolation;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getResult()
    {
        return $this->testResult;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setResult($result): void
    {
        $this->testResult = $result;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setOutputCallback(callable $callback): void
    {
        $this->outputCallback = $callback;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getTestResultObject(): ?TestResult
    {
        return $this->result;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function setTestResultObject(TestResult $result): void
    {
        $this->result = $result;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function registerMockObject(MockObject $mockObject): void
    {
        $this->mockObjects[] = $mockObject;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function addToAssertionCount(int $count): void
    {
        $this->numAssertions += $count;
    }

    /**
     * Returns the number of assertions performed by this test.
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getNumAssertions(): int
    {
        return $this->numAssertions;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function usesDataProvider(): bool
    {
        return !empty($this->data);
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function dataDescription(): string
    {
        return is_string($this->dataName) ? $this->dataName : '';
    }

    /**
     * @return int|string
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function dataName()
    {
        return $this->dataName;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getDataSetAsString(bool $includeData = true): string
    {
        $buffer = '';

        if (!empty($this->data)) {
            if (is_int($this->dataName)) {
                $buffer .= sprintf(' with data set #%d', $this->dataName);
            } else {
                $buffer .= sprintf(' with data set "%s"', $this->dataName);
            }

            if ($includeData) {
                $exporter = new Exporter;

                $buffer .= sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data));
            }
        }

        return $buffer;
    }

    /**
     * Gets the data set of a TestCase.
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function getProvidedData(): array
    {
        return $this->data;
    }

    /**
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    public function addWarning(string $warning): void
    {
        $this->warnings[] = $warning;
    }

    /**
     * Override to run the test and assert its state.
     *
     * @throws \SebastianBergmann\ObjectEnumerator\InvalidArgumentException
     * @throws AssertionFailedError
     * @throws Exception
     * @throws ExpectationFailedException
     * @throws Throwable
     */
    protected function runTest()
    {
        if (trim($this->name) === '') {
            throw new Exception(
                'PHPUnit\Framework\TestCase::$name must be a non-blank string.'
            );
        }

        $testArguments = array_merge($this->data, $this->dependencyInput);

        $this->registerMockObjectsFromTestArguments($testArguments);

        try {
            $testResult = $this->{$this->name}(...array_values($testArguments));
        } catch (Throwable $exception) {
            if (!$this->checkExceptionExpectations($exception)) {
                throw $exception;
            }

            if ($this->expectedException !== null) {
                if ($this->expectedException === Error::class) {
                    $this->assertThat(
                        $exception,
                        LogicalOr::fromConstraints(
                            new ExceptionConstraint(Error::class),
                            new ExceptionConstraint(\Error::class)
                        )
                    );
                } else {
                    $this->assertThat(
                        $exception,
                        new ExceptionConstraint(
                            $this->expectedException
                        )
                    );
                }
            }

            if ($this->expectedExceptionMessage !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessage(
                        $this->expectedExceptionMessage
                    )
                );
            }

            if ($this->expectedExceptionMessageRegExp !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessageRegularExpression(
                        $this->expectedExceptionMessageRegExp
                    )
                );
            }

            if ($this->expectedExceptionCode !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionCode(
                        $this->expectedExceptionCode
                    )
                );
            }

            if ($this->deprecatedExpectExceptionMessageRegExpUsed) {
                $this->addWarning('expectExceptionMessageRegExp() is deprecated in PHPUnit 8 and will be removed in PHPUnit 9. Use expectExceptionMessageMatches() instead.');
            }

            return;
        }

        if ($this->expectedException !== null) {
            $this->assertThat(
                null,
                new ExceptionConstraint(
                    $this->expectedException
                )
            );
        } elseif ($this->expectedExceptionMessage !== null) {
            $this->numAssertions++;

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with message "%s" is thrown',
                    $this->expectedExceptionMessage
                )
            );
        } elseif ($this->expectedExceptionMessageRegExp !== null) {
            $this->numAssertions++;

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with message matching "%s" is thrown',
                    $this->expectedExceptionMessageRegExp
                )
            );
        } elseif ($this->expectedExceptionCode !== null) {
            $this->numAssertions++;

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with code "%s" is thrown',
                    $this->expectedExceptionCode
                )
            );
        }

        return $testResult;
    }

    /**
     * This method is a wrapper for the ini_set() function that automatically
     * resets the modified php.ini setting to its original value after the
     * test is run.
     *
     * @throws Exception
     */
    protected function iniSet(string $varName, string $newValue): void
    {
        $currentValue = ini_set($varName, $newValue);

        if ($currentValue !== false) {
            $this->iniSettings[$varName] = $currentValue;
        } else {
            throw new Exception(
                sprintf(
                    'INI setting "%s" could not be set to "%s".',
                    $varName,
                    $newValue
                )
            );
        }
    }

    /**
     * This method is a wrapper for the setlocale() function that automatically
     * resets the locale to its original value after the test is run.
     *
     * @throws Exception
     */
    protected function setLocale(...$args): void
    {
        if (count($args) < 2) {
            throw new Exception;
        }

        [$category, $locale] = $args;

        if (defined('LC_MESSAGES')) {
            $categories[] = LC_MESSAGES;
        }

        if (!in_array($category, self::LOCALE_CATEGORIES, true)) {
            throw new Exception;
        }

        if (!is_array($locale) && !is_string($locale)) {
            throw new Exception;
        }

        $this->locale[$category] = setlocale($category, 0);

        $result = setlocale(...$args);

        if ($result === false) {
            throw new Exception(
                'The locale functionality is not implemented on your platform, ' .
                'the specified locale does not exist or the category name is ' .
                'invalid.'
            );
        }
    }

    /**
     * Makes configurable stub for the specified class.
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param    class-string<RealInstanceType> $originalClassName
     *
     * @psalm-return   Stub&RealInstanceType
     */
    protected function createStub(string $originalClassName): Stub
    {
        return $this->createMock($originalClassName);
    }

    /**
     * Returns a mock object for the specified class.
     *
     * @param string|string[] $originalClassName
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string[] $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function createMock($originalClassName): MockObject
    {
        if (!is_string($originalClassName)) {
            $this->addWarning('Passing an array of interface names to createMock() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
        }

        return $this->getMockBuilder($originalClassName)
                    ->disableOriginalConstructor()
                    ->disableOriginalClone()
                    ->disableArgumentCloning()
                    ->disallowMockingUnknownTypes()
                    ->getMock();
    }

    /**
     * Returns a configured mock object for the specified class.
     *
     * @param string|string[] $originalClassName
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string[] $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function createConfiguredMock($originalClassName, array $configuration): MockObject
    {
        $o = $this->createMock($originalClassName);

        foreach ($configuration as $method => $return) {
            $o->method($method)->willReturn($return);
        }

        return $o;
    }

    /**
     * Returns a partial mock object for the specified class.
     *
     * @param string|string[] $originalClassName
     * @param string[]        $methods
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string[] $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function createPartialMock($originalClassName, array $methods): MockObject
    {
        if (!is_string($originalClassName)) {
            $this->addWarning('Passing an array of interface names to createPartialMock() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
        }

        $class_names = is_array($originalClassName) ? $originalClassName : [$originalClassName];

        foreach ($class_names as $class_name) {
            $reflection = new ReflectionClass($class_name);

            $mockedMethodsThatDontExist = array_filter(
                $methods,
                static function (string $method) use ($reflection)
                {
                    return !$reflection->hasMethod($method);
                }
            );

            if ($mockedMethodsThatDontExist) {
                $this->addWarning(
                    sprintf(
                        'createPartialMock called with method(s) %s that do not exist in %s. This will not be allowed in future versions of PHPUnit.',
                        implode(', ', $mockedMethodsThatDontExist),
                        $class_name
                    )
                );
            }
        }

        return $this->getMockBuilder($originalClassName)
                    ->disableOriginalConstructor()
                    ->disableOriginalClone()
                    ->disableArgumentCloning()
                    ->disallowMockingUnknownTypes()
                    ->setMethods(empty($methods) ? null : $methods)
                    ->getMock();
    }

    /**
     * Returns a test proxy for the specified class.
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType> $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function createTestProxy(string $originalClassName, array $constructorArguments = []): MockObject
    {
        return $this->getMockBuilder($originalClassName)
                    ->setConstructorArgs($constructorArguments)
                    ->enableProxyingToOriginalMethods()
                    ->getMock();
    }

    /**
     * Mocks the specified class and returns the name of the mocked class.
     *
     * @param string $originalClassName
     * @param array  $methods
     * @param string $mockClassName
     * @param bool   $callOriginalConstructor
     * @param bool   $callOriginalClone
     * @param bool   $callAutoload
     * @param bool   $cloneArguments
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string $originalClassName
     *
     * @psalm-return class-string<MockObject&RealInstanceType>
     */
    protected function getMockClass($originalClassName, $methods = [], array $arguments = [], $mockClassName = '', $callOriginalConstructor = false, $callOriginalClone = true, $callAutoload = true, $cloneArguments = false): string
    {
        $this->recordDoubledType($originalClassName);

        $mock = $this->getMockObjectGenerator()->getMock(
            $originalClassName,
            $methods,
            $arguments,
            $mockClassName,
            $callOriginalConstructor,
            $callOriginalClone,
            $callAutoload,
            $cloneArguments
        );

        return get_class($mock);
    }

    /**
     * Returns a mock object for the specified abstract class with all abstract
     * methods of the class mocked. Concrete methods are not mocked by default.
     * To mock concrete methods, use the 7th parameter ($mockedMethods).
     *
     * @param string $originalClassName
     * @param string $mockClassName
     * @param bool   $callOriginalConstructor
     * @param bool   $callOriginalClone
     * @param bool   $callAutoload
     * @param array  $mockedMethods
     * @param bool   $cloneArguments
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType> $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function getMockForAbstractClass($originalClassName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false): MockObject
    {
        $this->recordDoubledType($originalClassName);

        $mockObject = $this->getMockObjectGenerator()->getMockForAbstractClass(
            $originalClassName,
            $arguments,
            $mockClassName,
            $callOriginalConstructor,
            $callOriginalClone,
            $callAutoload,
            $mockedMethods,
            $cloneArguments
        );

        $this->registerMockObject($mockObject);

        return $mockObject;
    }

    /**
     * Returns a mock object based on the given WSDL file.
     *
     * @param string $wsdlFile
     * @param string $originalClassName
     * @param string $mockClassName
     * @param bool   $callOriginalConstructor
     * @param array  $options                 An array of options passed to SOAPClient::_construct
     *
     * @psalm-template RealInstanceType of object
     *
     * @psalm-param class-string<RealInstanceType>|string $originalClassName
     *
     * @psalm-return MockObject&RealInstanceType
     */
    protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClassName = '', array $methods = [], $callOriginalConstructor = true, array $options = []): MockObject
    {
        $this->recordDoubledType('SoapClient');

        if ($originalClassName === '') {
            $fileName          = pathinfo(basename(parse_url($wsdlFile, PHP_URL_PATH)), PATHINFO_FILENAME);
            $originalClassName = preg_replace('/\W/', '', $fileName);
        }

        if (!class_exists($originalClassName)) {
            eval(
                $this->getMockObjectGenerator()->generateClassFromWsdl(
                    $wsdlFile,
                    $originalClassName,
                    $methods,
                    $options
                )
            );
        }

        $mockObject = $this->getMockObjectGenerator()->getMock(
            $originalClassName,
            $methods,
            ['', $options],
            $mockClassName,
            $callOriginalConstructor,
            false,
            false
        );

        $this->registerMockObject($mockObject);

        return $mockObject;
    }

    /**
     * Returns a mock object for the specified trait with all abstract methods
     * of the trait mocked. Concrete methods to mock can be specified with the
     * `$mockedMethods` parameter.
     *
     * @param string $traitName
     * @param string $mockClassName
     * @param bool   $callOriginalConstructor
     * @param bool   $callOriginalClone
     * @param bool   $callAutoload
     * @param array  $mockedMethods
     * @param bool   $cloneArguments
     */
    protected function getMockForTrait($traitName, array $arguments = [], $mockClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true, $mockedMethods = [], $cloneArguments = false): MockObject
    {
        $this->recordDoubledType($traitName);

        $mockObject = $this->getMockObjectGenerator()->getMockForTrait(
            $traitName,
            $arguments,
            $mockClassName,
            $callOriginalConstructor,
            $callOriginalClone,
            $callAutoload,
            $mockedMethods,
            $cloneArguments
        );

        $this->registerMockObject($mockObject);

        return $mockObject;
    }

    /**
     * Returns an object for the specified trait.
     *
     * @param string $traitName
     * @param string $traitClassName
     * @param bool   $callOriginalConstructor
     * @param bool   $callOriginalClone
     * @param bool   $callAutoload
     *
     * @return object
     */
    protected function getObjectForTrait($traitName, array $arguments = [], $traitClassName = '', $callOriginalConstructor = true, $callOriginalClone = true, $callAutoload = true)/*: object*/
    {
        $this->recordDoubledType($traitName);

        return $this->getMockObjectGenerator()->getObjectForTrait(
            $traitName,
            $traitClassName,
            $callAutoload,
            $callOriginalConstructor,
            $arguments
        );
    }

    /**
     * @param null|string $classOrInterface
     *
     * @throws \Prophecy\Exception\Doubler\ClassNotFoundException
     * @throws \Prophecy\Exception\Doubler\DoubleException
     * @throws \Prophecy\Exception\Doubler\InterfaceNotFoundException
     *
     * @psalm-param class-string|null $classOrInterface
     */
    protected function prophesize($classOrInterface = null): ObjectProphecy
    {
        if (!class_exists(Prophet::class)) {
            throw new Exception('This test uses TestCase::prophesize(), but phpspec/prophecy is not installed. Please run "composer require --dev phpspec/prophecy".');
        }

        if (is_string($classOrInterface)) {
            $this->recordDoubledType($classOrInterface);
        }

        return $this->getProphet()->prophesize($classOrInterface);
    }

    /**
     * Creates a default TestResult object.
     *
     * @internal This method is not covered by the backward compatibility promise for PHPUnit
     */
    protected function createResult(): TestResult
    {
        return new TestResult;
    }

    /**
     * This method is called when a test method did not execute successfully.
     *
     * @throws Throwable
     */
    protected function onNotSuccessfulTest(Throwable $t): void
    {
        throw $t;
    }

    private function setExpectedExceptionFromAnnotation(): void
    {
        if ($this->name === null) {
            return;
        }

        try {
            $expectedException = TestUtil::getExpectedException(
                static::class,
                $this->name
            );

            if ($expectedException !== false) {
                $this->addWarning('The @expectedException, @expectedExceptionCode, @expectedExceptionMessage, and @expectedExceptionMessageRegExp annotations are deprecated. They will be removed in PHPUnit 9. Refactor your test to use expectException(), expectExceptionCode(), expectExceptionMessage(), or expectExceptionMessageMatches() instead.');

                $this->expectException($expectedException['class']);

                if ($expectedException['code'] !== null) {
                    $this->expectExceptionCode($expectedException['code']);
                }

                if ($expectedException['message'] !== '') {
                    $this->expectExceptionMessage($expectedException['message']);
                } elseif ($expectedException['message_regex'] !== '') {
                    $this->expectExceptionMessageMatches($expectedException['message_regex']);
                }
            }
        } catch (UtilException $e) {
        }
    }

    /**
     * @throws SkippedTestError
     * @throws SyntheticSkippedError
     * @throws Warning
     */
    private function checkRequirements(): void
    {
        if (!$this->name || !method_exists($this, $this->name)) {
            return;
        }

        $missingRequirements = TestUtil::getMissingRequirements(
            static::class,
            $this->name
        );

        if (!empty($missingRequirements)) {
            $this->markTestSkipped(implode(PHP_EOL, $missingRequirements));
        }
    }

    /**
     * @throws Throwable
     */
    private function verifyMockObjects(): void
    {
        foreach ($this->mockObjects as $mockObject) {
            if ($mockObject->__phpunit_hasMatchers()) {
                $this->numAssertions++;
            }

            $mockObject->__phpunit_verify(
                $this->shouldInvocationMockerBeReset($mockObject)
            );
        }

        if ($this->prophet !== null) {
            try {
                $this->prophet->checkPredictions();
            } finally {
                foreach ($this->prophet->getProphecies() as $objectProphecy) {
                    foreach ($objectProphecy->getMethodProphecies() as $methodProphecies) {
                        foreach ($methodProphecies as $methodProphecy) {
                            assert($methodProphecy instanceof MethodProphecy);

                            $this->numAssertions += count($methodProphecy->getCheckedPredictions());
                        }
                    }
                }
            }
        }
    }

    private function handleDependencies(): bool
    {
        if (!empty($this->dependencies) && !$this->inIsolation) {
            $passed     = $this->result->passed();
            $passedKeys = array_keys($passed);

            foreach ($passedKeys as $key => $value) {
                $pos = strpos($value, ' with data set');

                if ($pos !== false) {
                    $passedKeys[$key] = substr($value, 0, $pos);
                }
            }

            $passedKeys = array_flip(array_unique($passedKeys));

            foreach ($this->dependencies as $dependency) {
                $deepClone    = false;
                $shallowClone = false;

                if (empty($dependency)) {
                    $this->markSkippedForNotSpecifyingDependency();

                    return false;
                }

                if (strpos($dependency, 'clone ') === 0) {
                    $deepClone  = true;
                    $dependency = substr($dependency, strlen('clone '));
                } elseif (strpos($dependency, '!clone ') === 0) {
                    $deepClone  = false;
                    $dependency = substr($dependency, strlen('!clone '));
                }

                if (strpos($dependency, 'shallowClone ') === 0) {
                    $shallowClone = true;
                    $dependency   = substr($dependency, strlen('shallowClone '));
                } elseif (strpos($dependency, '!shallowClone ') === 0) {
                    $shallowClone = false;
                    $dependency   = substr($dependency, strlen('!shallowClone '));
                }

                if (strpos($dependency, '::') === false) {
                    $dependency = static::class . '::' . $dependency;
                }

                if (!isset($passedKeys[$dependency])) {
                    if (!$this->isCallableTestMethod($dependency)) {
                        $this->warnAboutDependencyThatDoesNotExist($dependency);
                    } else {
                        $this->markSkippedForMissingDependency($dependency);
                    }

                    return false;
                }

                if (isset($passed[$dependency])) {
                    if ($passed[$dependency]['size'] !== TestUtil::UNKNOWN &&
                        $this->getSize() !== TestUtil::UNKNOWN &&
                        $passed[$dependency]['size'] > $this->getSize()) {
                        $this->result->addError(
                            $this,
                            new SkippedTestError(
                                'This test depends on a test that is larger than itself.'
                            ),
                            0
                        );

                        return false;
                    }

                    if ($deepClone) {
                        $deepCopy = new DeepCopy;
                        $deepCopy->skipUncloneable(false);

                        $this->dependencyInput[$dependency] = $deepCopy->copy($passed[$dependency]['result']);
                    } elseif ($shallowClone) {
                        $this->dependencyInput[$dependency] = clone $passed[$dependency]['result'];
                    } else {
                        $this->dependencyInput[$dependency] = $passed[$dependency]['result'];
                    }
                } else {
                    $this->dependencyInput[$dependency] = null;
                }
            }
        }

        return true;
    }

    private function markSkippedForNotSpecifyingDependency(): void
    {
        $this->status = BaseTestRunner::STATUS_SKIPPED;

        $this->result->startTest($this);

        $this->result->addError(
            $this,
            new SkippedTestError(
                'This method has an invalid @depends annotation.'
            ),
            0
        );

        $this->result->endTest($this, 0);
    }

    private function markSkippedForMissingDependency(string $dependency): void
    {
        $this->status = BaseTestRunner::STATUS_SKIPPED;

        $this->result->startTest($this);

        $this->result->addError(
            $this,
            new SkippedTestError(
                sprintf(
                    'This test depends on "%s" to pass.',
                    $dependency
                )
            ),
            0
        );

        $this->result->endTest($this, 0);
    }

    private function warnAboutDependencyThatDoesNotExist(string $dependency): void
    {
        $this->status = BaseTestRunner::STATUS_WARNING;

        $this->result->startTest($this);

        $this->result->addWarning(
            $this,
            new Warning(
                sprintf(
                    'This test depends on "%s" which does not exist.',
                    $dependency
                )
            ),
            0
        );

        $this->result->endTest($this, 0);
    }

    /**
     * Get the mock object generator, creating it if it doesn't exist.
     */
    private function getMockObjectGenerator(): MockGenerator
    {
        if ($this->mockObjectGenerator === null) {
            $this->mockObjectGenerator = new MockGenerator;
        }

        return $this->mockObjectGenerator;
    }

    private function startOutputBuffering(): void
    {
        ob_start();

        $this->outputBufferingActive = true;
        $this->outputBufferingLevel  = ob_get_level();
    }

    /**
     * @throws RiskyTestError
     */
    private function stopOutputBuffering(): void
    {
        if (ob_get_level() !== $this->outputBufferingLevel) {
            while (ob_get_level() >= $this->outputBufferingLevel) {
                ob_end_clean();
            }

            throw new RiskyTestError(
                'Test code or tested code did not (only) close its own output buffers'
            );
        }

        $this->output = ob_get_contents();

        if ($this->outputCallback !== false) {
            $this->output = (string) call_user_func($this->outputCallback, $this->output);
        }

        ob_end_clean();

        $this->outputBufferingActive = false;
        $this->outputBufferingLevel  = ob_get_level();
    }

    private function snapshotGlobalState(): void
    {
        if ($this->runTestInSeparateProcess || $this->inIsolation ||
            (!$this->backupGlobals && !$this->backupStaticAttributes)) {
            return;
        }

        $this->snapshot = $this->createGlobalStateSnapshot($this->backupGlobals === true);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws RiskyTestError
     */
    private function restoreGlobalState(): void
    {
        if (!$this->snapshot instanceof Snapshot) {
            return;
        }

        if ($this->beStrictAboutChangesToGlobalState) {
            try {
                $this->compareGlobalStateSnapshots(
                    $this->snapshot,
                    $this->createGlobalStateSnapshot($this->backupGlobals === true)
                );
            } catch (RiskyTestError $rte) {
                // Intentionally left empty
            }
        }

        $restorer = new Restorer;

        if ($this->backupGlobals) {
            $restorer->restoreGlobalVariables($this->snapshot);
        }

        if ($this->backupStaticAttributes) {
            $restorer->restoreStaticAttributes($this->snapshot);
        }

        $this->snapshot = null;

        if (isset($rte)) {
            throw $rte;
        }
    }

    private function createGlobalStateSnapshot(bool $backupGlobals): Snapshot
    {
        $blacklist = new Blacklist;

        foreach ($this->backupGlobalsBlacklist as $globalVariable) {
            $blacklist->addGlobalVariable($globalVariable);
        }

        if (!defined('PHPUNIT_TESTSUITE')) {
            $blacklist->addClassNamePrefix('PHPUnit');
            $blacklist->addClassNamePrefix('SebastianBergmann\CodeCoverage');
            $blacklist->addClassNamePrefix('SebastianBergmann\FileIterator');
            $blacklist->addClassNamePrefix('SebastianBergmann\Invoker');
            $blacklist->addClassNamePrefix('SebastianBergmann\Timer');
            $blacklist->addClassNamePrefix('PHP_Token');
            $blacklist->addClassNamePrefix('Text_Template');
            $blacklist->addClassNamePrefix('Doctrine\Instantiator');
            $blacklist->addClassNamePrefix('Prophecy');
            $blacklist->addStaticAttribute(ComparatorFactory::class, 'instance');

            foreach ($this->backupStaticAttributesBlacklist as $class => $attributes) {
                foreach ($attributes as $attribute) {
                    $blacklist->addStaticAttribute($class, $attribute);
                }
            }
        }

        return new Snapshot(
            $blacklist,
            $backupGlobals,
            (bool) $this->backupStaticAttributes,
            false,
            false,
            false,
            false,
            false,
            false,
            false
        );
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws RiskyTestError
     */
    private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after): void
    {
        $backupGlobals = $this->backupGlobals === null || $this->backupGlobals;

        if ($backupGlobals) {
            $this->compareGlobalStateSnapshotPart(
                $before->globalVariables(),
                $after->globalVariables(),
                "--- Global variables before the test\n+++ Global variables after the test\n"
            );

            $this->compareGlobalStateSnapshotPart(
                $before->superGlobalVariables(),
                $after->superGlobalVariables(),
                "--- Super-global variables before the test\n+++ Super-global variables after the test\n"
            );
        }

        if ($this->backupStaticAttributes) {
            $this->compareGlobalStateSnapshotPart(
                $before->staticAttributes(),
                $after->staticAttributes(),
                "--- Static attributes before the test\n+++ Static attributes after the test\n"
            );
        }
    }

    /**
     * @throws RiskyTestError
     */
    private function compareGlobalStateSnapshotPart(array $before, array $after, string $header): void
    {
        if ($before != $after) {
            $differ   = new Differ($header);
            $exporter = new Exporter;

            $diff = $differ->diff(
                $exporter->export($before),
                $exporter->export($after)
            );

            throw new RiskyTestError(
                $diff
            );
        }
    }

    private function getProphet(): Prophet
    {
        if ($this->prophet === null) {
            $this->prophet = new Prophet;
        }

        return $this->prophet;
    }

    /**
     * @throws \SebastianBergmann\ObjectEnumerator\InvalidArgumentException
     */
    private function shouldInvocationMockerBeReset(MockObject $mock): bool
    {
        $enumerator = new Enumerator;

        foreach ($enumerator->enumerate($this->dependencyInput) as $object) {
            if ($mock === $object) {
                return false;
            }
        }

        if (!is_array($this->testResult) && !is_object($this->testResult)) {
            return true;
        }

        return !in_array($mock, $enumerator->enumerate($this->testResult), true);
    }

    /**
     * @throws \SebastianBergmann\ObjectEnumerator\InvalidArgumentException
     * @throws \SebastianBergmann\ObjectReflector\InvalidArgumentException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function registerMockObjectsFromTestArguments(array $testArguments, array &$visited = []): void
    {
        if ($this->registerMockObjectsFromTestArgumentsRecursively) {
            foreach ((new Enumerator)->enumerate($testArguments) as $object) {
                if ($object instanceof MockObject) {
                    $this->registerMockObject($object);
                }
            }
        } else {
            foreach ($testArguments as $testArgument) {
                if ($testArgument instanceof MockObject) {
                    if (Type::isCloneable($testArgument)) {
                        $testArgument = clone $testArgument;
                    }

                    $this->registerMockObject($testArgument);
                } elseif (is_array($testArgument) && !in_array($testArgument, $visited, true)) {
                    $visited[] = $testArgument;

                    $this->registerMockObjectsFromTestArguments(
                        $testArgument,
                        $visited
                    );
                }
            }
        }
    }

    private function setDoesNotPerformAssertionsFromAnnotation(): void
    {
        $annotations = $this->getAnnotations();

        if (isset($annotations['method']['doesNotPerformAssertions'])) {
            $this->doesNotPerformAssertions = true;
        }
    }

    private function unregisterCustomComparators(): void
    {
        $factory = ComparatorFactory::getInstance();

        foreach ($this->customComparators as $comparator) {
            $factory->unregister($comparator);
        }

        $this->customComparators = [];
    }

    private function cleanupIniSettings(): void
    {
        foreach ($this->iniSettings as $varName => $oldValue) {
            ini_set($varName, $oldValue);
        }

        $this->iniSettings = [];
    }

    private function cleanupLocaleSettings(): void
    {
        foreach ($this->locale as $category => $locale) {
            setlocale($category, $locale);
        }

        $this->locale = [];
    }

    /**
     * @throws Exception
     */
    private function checkExceptionExpectations(Throwable $throwable): bool
    {
        $result = false;

        if ($this->expectedException !== null || $this->expectedExceptionCode !== null || $this->expectedExceptionMessage !== null || $this->expectedExceptionMessageRegExp !== null) {
            $result = true;
        }

        if ($throwable instanceof Exception) {
            $result = false;
        }

        if (is_string($this->expectedException)) {
            try {
                $reflector = new ReflectionClass($this->expectedException);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if ($this->expectedException === 'PHPUnit\Framework\Exception' ||
                $this->expectedException === '\PHPUnit\Framework\Exception' ||
                $reflector->isSubclassOf(Exception::class)) {
                $result = true;
            }
        }

        return $result;
    }

    private function runInSeparateProcess(): bool
    {
        return ($this->runTestInSeparateProcess || $this->runClassInSeparateProcess) &&
            !$this->inIsolation && !$this instanceof PhptTestCase;
    }

    /**
     * @param string|string[] $originalClassName
     */
    private function recordDoubledType($originalClassName): void
    {
        if (is_string($originalClassName)) {
            $this->doubledTypes[] = $originalClassName;
        }

        if (is_array($originalClassName)) {
            foreach ($originalClassName as $_originalClassName) {
                if (is_string($_originalClassName)) {
                    $this->doubledTypes[] = $_originalClassName;
                }
            }
        }
    }

    private function isCallableTestMethod(string $dependency): bool
    {
        [$className, $methodName] = explode('::', $dependency);

        if (!class_exists($className)) {
            return false;
        }

        try {
            $class = new ReflectionClass($className);
        } catch (ReflectionException $e) {
            return false;
        }

        if (!$class->isSubclassOf(__CLASS__)) {
            return false;
        }

        if (!$class->hasMethod($methodName)) {
            return false;
        }

        try {
            $method = $class->getMethod($methodName);
        } catch (ReflectionException $e) {
            return false;
        }

        return TestUtil::isTestMethod($method);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Warning extends Exception implements SelfDescribing
{
    /**
     * Wrapper for getMessage() which is declared as final.
     */
    public function toString(): string
    {
        return $this->getMessage();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class UnintentionallyCoveredCodeError extends RiskyTestError
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use Exception;
use SebastianBergmann\Comparator\ComparisonFailure;

/**
 * Exception for expectations which failed their check.
 *
 * The exception contains the error message and optionally a
 * SebastianBergmann\Comparator\ComparisonFailure which is used to
 * generate diff output of the failed expectations.
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ExpectationFailedException extends AssertionFailedError
{
    /**
     * @var ComparisonFailure
     */
    protected $comparisonFailure;

    public function __construct(string $message, ComparisonFailure $comparisonFailure = null, Exception $previous = null)
    {
        $this->comparisonFailure = $comparisonFailure;

        parent::__construct($message, 0, $previous);
    }

    public function getComparisonFailure(): ?ComparisonFailure
    {
        return $this->comparisonFailure;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class SyntheticSkippedError extends SyntheticError implements SkippedTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class SkippedTestSuiteError extends AssertionFailedError implements SkippedTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class OutputError extends AssertionFailedError
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class IncompleteTestError extends AssertionFailedError implements IncompleteTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class RiskyTestError extends AssertionFailedError
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class SkippedTestError extends AssertionFailedError implements SkippedTest
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class SyntheticError extends AssertionFailedError
{
    /**
     * The synthetic file.
     *
     * @var string
     */
    protected $syntheticFile = '';

    /**
     * The synthetic line number.
     *
     * @var int
     */
    protected $syntheticLine = 0;

    /**
     * The synthetic trace.
     *
     * @var array
     */
    protected $syntheticTrace = [];

    public function __construct(string $message, int $code, string $file, int $line, array $trace)
    {
        parent::__construct($message, $code);

        $this->syntheticFile  = $file;
        $this->syntheticLine  = $line;
        $this->syntheticTrace = $trace;
    }

    public function getSyntheticFile(): string
    {
        return $this->syntheticFile;
    }

    public function getSyntheticLine(): int
    {
        return $this->syntheticLine;
    }

    public function getSyntheticTrace(): array
    {
        return $this->syntheticTrace;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class PHPTAssertionFailedError extends SyntheticError
{
    /**
     * @var string
     */
    private $diff;

    public function __construct(string $message, int $code, string $file, int $line, array $trace, string $diff)
    {
        parent::__construct($message, $code, $file, $line, $trace);
        $this->diff = $diff;
    }

    public function getDiff(): string
    {
        return $this->diff;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class CodeCoverageException extends Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class CoveredCodeNotExecutedException extends RiskyTestError
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function debug_backtrace;
use function in_array;
use function lcfirst;
use function sprintf;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvalidArgumentException extends Exception
{
    public static function create(int $argument, string $type): self
    {
        $stack    = debug_backtrace();
        $function = $stack[1]['function'];

        if (isset($stack[1]['class'])) {
            $function = sprintf('%s::%s', $stack[1]['class'], $stack[1]['function']);
        }

        return new self(
            sprintf(
                'Argument #%d of %s() must be %s %s',
                $argument,
                $function,
                in_array(lcfirst($type)[0], ['a', 'e', 'i', 'o', 'u'], true) ? 'an' : 'a',
                $type
            )
        );
    }

    private function __construct(string $message = '', int $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class NoChildTestSuiteException extends Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvalidDataProviderException extends Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class InvalidCoversTargetException extends CodeCoverageException
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MissingCoversAnnotationException extends RiskyTestError
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function array_keys;
use function get_object_vars;
use PHPUnit\Util\Filter;
use RuntimeException;
use Throwable;

/**
 * Base class for all PHPUnit Framework exceptions.
 *
 * Ensures that exceptions thrown during a test run do not leave stray
 * references behind.
 *
 * Every Exception contains a stack trace. Each stack frame contains the 'args'
 * of the called function. The function arguments can contain references to
 * instantiated objects. The references prevent the objects from being
 * destructed (until test results are eventually printed), so memory cannot be
 * freed up.
 *
 * With enabled process isolation, test results are serialized in the child
 * process and unserialized in the parent process. The stack trace of Exceptions
 * may contain objects that cannot be serialized or unserialized (e.g., PDO
 * connections). Unserializing user-space objects from the child process into
 * the parent would break the intended encapsulation of process isolation.
 *
 * @see http://fabien.potencier.org/article/9/php-serialization-stack-traces-and-exceptions
 *
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class Exception extends RuntimeException implements \PHPUnit\Exception
{
    /**
     * @var array
     */
    protected $serializableTrace;

    public function __construct($message = '', $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);

        $this->serializableTrace = $this->getTrace();

        foreach (array_keys($this->serializableTrace) as $key) {
            unset($this->serializableTrace[$key]['args']);
        }
    }

    public function __toString(): string
    {
        $string = TestFailure::exceptionToString($this);

        if ($trace = Filter::getFilteredStacktrace($this)) {
            $string .= "\n" . $trace;
        }

        return $string;
    }

    public function __sleep(): array
    {
        return array_keys(get_object_vars($this));
    }

    /**
     * Returns the serializable trace (without 'args').
     */
    public function getSerializableTrace(): array
    {
        return $this->serializableTrace;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
class AssertionFailedError extends Exception implements SelfDescribing
{
    /**
     * Wrapper for getMessage() which is declared as final.
     */
    public function toString(): string
    {
        return $this->getMessage();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class WarningTestCase extends TestCase
{
    /**
     * @var bool
     */
    protected $backupGlobals = false;

    /**
     * @var bool
     */
    protected $backupStaticAttributes = false;

    /**
     * @var bool
     */
    protected $runTestInSeparateProcess = false;

    /**
     * @var string
     */
    private $message;

    public function __construct(string $message = '')
    {
        $this->message = $message;

        parent::__construct('Warning');
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    /**
     * Returns a string representation of the test case.
     */
    public function toString(): string
    {
        return 'Warning';
    }

    /**
     * @throws Exception
     *
     * @psalm-return never-return
     */
    protected function runTest(): void
    {
        throw new Warning($this->message);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function preg_match;
use function sprintf;

/**
 * Constraint that asserts that the string it is evaluated for matches
 * a regular expression.
 *
 * Checks a given value using the Perl Compatible Regular Expression extension
 * in PHP. The pattern is matched by executing preg_match().
 *
 * The pattern string passed in the constructor.
 */
class RegularExpression extends Constraint
{
    /**
     * @var string
     */
    private $pattern;

    public function __construct(string $pattern)
    {
        $this->pattern = $pattern;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'matches PCRE pattern "%s"',
            $this->pattern
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return preg_match($this->pattern, $other) > 0;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use ReflectionClass;
use ReflectionException;

/**
 * Constraint that asserts that the object it is evaluated for is an instance
 * of a given class.
 *
 * The expected class name is passed in the constructor.
 */
final class IsInstanceOf extends Constraint
{
    /**
     * @var string
     */
    private $className;

    public function __construct(string $className)
    {
        $this->className = $className;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'is instance of %s "%s"',
            $this->getType(),
            $this->className
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $other instanceof $this->className;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s is an instance of %s "%s"',
            $this->exporter()->shortenedExport($other),
            $this->getType(),
            $this->className
        );
    }

    private function getType(): string
    {
        try {
            $reflection = new ReflectionClass($this->className);

            if ($reflection->isInterface()) {
                return 'interface';
            }
        } catch (ReflectionException $e) {
        }

        return 'class';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_array;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;

/**
 * Constraint that asserts that the Traversable it is applied to contains
 * a given value (using strict comparison).
 */
final class TraversableContainsIdentical extends Constraint
{
    /**
     * @var mixed
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        if (is_string($this->value) && strpos($this->value, "\n") !== false) {
            return 'contains "' . $this->value . '"';
        }

        return 'contains ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ($other instanceof SplObjectStorage) {
            return $other->contains($this->value);
        }

        foreach ($other as $element) {
            if ($this->value === $element) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s %s',
            is_array($other) ? 'an array' : 'a traversable',
            $this->toString()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_readable;
use function sprintf;

/**
 * Constraint that checks if the file/dir(name) that it is evaluated for is readable.
 *
 * The file path to check is passed as $other in evaluate().
 */
final class IsReadable extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is readable';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_readable($other);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '"%s" is readable',
            $other
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that accepts false.
 */
final class IsFalse extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is false';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $other === false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that asserts that the value it is evaluated for is less than
 * a given value.
 */
final class LessThan extends Constraint
{
    /**
     * @var float|int
     */
    private $value;

    /**
     * @param float|int $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'is less than ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $this->value > $other;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use Exception;
use PHPUnit\Util\RegularExpression as RegularExpressionUtil;

final class ExceptionMessageRegularExpression extends Constraint
{
    /**
     * @var string
     */
    private $expectedMessageRegExp;

    public function __construct(string $expected)
    {
        $this->expectedMessageRegExp = $expected;
    }

    public function toString(): string
    {
        return 'exception message matches ';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param \PHPUnit\Framework\Exception $other
     *
     * @throws \PHPUnit\Framework\Exception
     * @throws Exception
     */
    protected function matches($other): bool
    {
        $match = RegularExpressionUtil::safeMatch($this->expectedMessageRegExp, $other->getMessage());

        if ($match === false) {
            throw new \PHPUnit\Framework\Exception(
                "Invalid expected exception message regex given: '{$this->expectedMessageRegExp}'"
            );
        }

        return $match === 1;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            "exception message '%s' matches '%s'",
            $other->getMessage(),
            $this->expectedMessageRegExp
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_dir;
use function sprintf;

/**
 * Constraint that checks if the directory(name) that it is evaluated for exists.
 *
 * The file path to check is passed as $other in evaluate().
 */
final class DirectoryExists extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'directory exists';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_dir($other);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            'directory "%s" exists',
            $other
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * Logical OR.
 */
final class LogicalOr extends Constraint
{
    /**
     * @var Constraint[]
     */
    private $constraints = [];

    public static function fromConstraints(Constraint ...$constraints): self
    {
        $constraint = new self;

        $constraint->constraints = array_values($constraints);

        return $constraint;
    }

    /**
     * @param Constraint[] $constraints
     */
    public function setConstraints(array $constraints): void
    {
        $this->constraints = [];

        foreach ($constraints as $constraint) {
            if (!($constraint instanceof Constraint)) {
                $constraint = new IsEqual(
                    $constraint
                );
            }

            $this->constraints[] = $constraint;
        }
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = false;

        foreach ($this->constraints as $constraint) {
            if ($constraint->evaluate($other, $description, true)) {
                $success = true;

                break;
            }
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        $text = '';

        foreach ($this->constraints as $key => $constraint) {
            if ($key > 0) {
                $text .= ' or ';
            }

            $text .= $constraint->toString();
        }

        return $text;
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        $count = 0;

        foreach ($this->constraints as $constraint) {
            $count += count($constraint);
        }

        return $count;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\ExpectationFailedException;

/**
 * Constraint that accepts any input value.
 */
final class IsAnything extends Constraint
{
    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        return $returnResult ? true : null;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is anything';
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        return 0;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use function strpos;
use Throwable;

final class ExceptionMessage extends Constraint
{
    /**
     * @var string
     */
    private $expectedMessage;

    public function __construct(string $expected)
    {
        $this->expectedMessage = $expected;
    }

    public function toString(): string
    {
        if ($this->expectedMessage === '') {
            return 'exception message is empty';
        }

        return 'exception message contains ';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param Throwable $other
     */
    protected function matches($other): bool
    {
        if ($this->expectedMessage === '') {
            return $other->getMessage() === '';
        }

        return strpos((string) $other->getMessage(), $this->expectedMessage) !== false;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        if ($this->expectedMessage === '') {
            return sprintf(
                "exception message is empty but is '%s'",
                $other->getMessage()
            );
        }

        return sprintf(
            "exception message '%s' contains '%s'",
            $other->getMessage(),
            $this->expectedMessage
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\ExpectationFailedException;

/**
 * Constraint that asserts that the Traversable it is applied to contains
 * only values of a given type.
 */
final class TraversableContainsOnly extends Constraint
{
    /**
     * @var Constraint
     */
    private $constraint;

    /**
     * @var string
     */
    private $type;

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct(string $type, bool $isNativeType = true)
    {
        if ($isNativeType) {
            $this->constraint = new IsType($type);
        } else {
            $this->constraint = new IsInstanceOf(
                $type
            );
        }

        $this->type = $type;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = true;

        foreach ($other as $item) {
            if (!$this->constraint->evaluate($item, '', true)) {
                $success = false;

                break;
            }
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'contains only values of type "' . $this->type . '"';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;

/**
 * Constraint that asserts that the class it is evaluated for has a given
 * static attribute.
 *
 * The attribute name is passed in the constructor.
 */
final class ClassHasStaticAttribute extends ClassHasAttribute
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'has static attribute "%s"',
            $this->attributeName()
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        try {
            $class = new ReflectionClass($other);

            if ($class->hasProperty($this->attributeName())) {
                return $class->getProperty($this->attributeName())->isStatic();
            }
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd

        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that accepts true.
 */
final class IsTrue extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is true';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $other === true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * Logical AND.
 */
final class LogicalAnd extends Constraint
{
    /**
     * @var Constraint[]
     */
    private $constraints = [];

    public static function fromConstraints(Constraint ...$constraints): self
    {
        $constraint = new self;

        $constraint->constraints = array_values($constraints);

        return $constraint;
    }

    /**
     * @param Constraint[] $constraints
     *
     * @throws \PHPUnit\Framework\Exception
     */
    public function setConstraints(array $constraints): void
    {
        $this->constraints = [];

        foreach ($constraints as $constraint) {
            if (!($constraint instanceof Constraint)) {
                throw new \PHPUnit\Framework\Exception(
                    'All parameters to ' . __CLASS__ .
                    ' must be a constraint object.'
                );
            }

            $this->constraints[] = $constraint;
        }
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = true;

        foreach ($this->constraints as $constraint) {
            if (!$constraint->evaluate($other, $description, true)) {
                $success = false;

                break;
            }
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        $text = '';

        foreach ($this->constraints as $key => $constraint) {
            if ($key > 0) {
                $text .= ' and ';
            }

            $text .= $constraint->toString();
        }

        return $text;
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        $count = 0;

        foreach ($this->constraints as $constraint) {
            $count += count($constraint);
        }

        return $count;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function array_key_exists;
use function is_array;
use ArrayAccess;

/**
 * Constraint that asserts that the array it is evaluated for has a given key.
 *
 * Uses array_key_exists() to check if the key is found in the input array, if
 * not found the evaluation fails.
 *
 * The array key is passed in the constructor.
 */
final class ArrayHasKey extends Constraint
{
    /**
     * @var int|string
     */
    private $key;

    /**
     * @param int|string $key
     */
    public function __construct($key)
    {
        $this->key = $key;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'has the key ' . $this->exporter()->export($this->key);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if (is_array($other)) {
            return array_key_exists($this->key, $other);
        }

        if ($other instanceof ArrayAccess) {
            return $other->offsetExists($this->key);
        }

        return false;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return 'an array ' . $this->toString();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function count;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
 *
 * @codeCoverageIgnore
 */
abstract class Composite extends Constraint
{
    /**
     * @var Constraint
     */
    private $innerConstraint;

    public function __construct(Constraint $innerConstraint)
    {
        $this->innerConstraint = $innerConstraint;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        try {
            return $this->innerConstraint->evaluate(
                $other,
                $description,
                $returnResult
            );
        } catch (ExpectationFailedException $e) {
            $this->fail($other, $description, $e->getComparisonFailure());
        }
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        return count($this->innerConstraint);
    }

    protected function innerConstraint(): Constraint
    {
        return $this->innerConstraint;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function strlen;
use function strpos;
use PHPUnit\Framework\InvalidArgumentException;

/**
 * Constraint that asserts that the string it is evaluated for begins with a
 * given prefix.
 */
final class StringStartsWith extends Constraint
{
    /**
     * @var string
     */
    private $prefix;

    public function __construct(string $prefix)
    {
        if (strlen($prefix) === 0) {
            throw InvalidArgumentException::create(1, 'non-empty string');
        }

        $this->prefix = $prefix;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'starts with "' . $this->prefix . '"';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return strpos((string) $other, $this->prefix) === 0;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function json_decode;
use function json_last_error;
use function sprintf;

/**
 * Constraint that asserts that a string is valid JSON.
 */
final class IsJson extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is valid JSON';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ($other === '') {
            return false;
        }

        json_decode($other);

        if (json_last_error()) {
            return false;
        }

        return true;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        if ($other === '') {
            return 'an empty string is valid JSON';
        }

        json_decode($other);
        $error = JsonMatchesErrorMessageProvider::determineJsonError(
            (string) json_last_error()
        );

        return sprintf(
            '%s is valid JSON (%s)',
            $this->exporter()->shortenedExport($other),
            $error
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function json_decode;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Util\Json;
use SebastianBergmann\Comparator\ComparisonFailure;

/**
 * Asserts whether or not two JSON objects are equal.
 */
final class JsonMatches extends Constraint
{
    /**
     * @var string
     */
    private $value;

    public function __construct(string $value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the object.
     */
    public function toString(): string
    {
        return sprintf(
            'matches JSON string "%s"',
            $this->value
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * This method can be overridden to implement the evaluation algorithm.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        [$error, $recodedOther] = Json::canonicalize($other);

        if ($error) {
            return false;
        }

        [$error, $recodedValue] = Json::canonicalize($this->value);

        if ($error) {
            return false;
        }

        return $recodedOther == $recodedValue;
    }

    /**
     * Throws an exception for the given compared value and test description.
     *
     * @param mixed             $other             evaluated value or object
     * @param string            $description       Additional information about the test
     * @param ComparisonFailure $comparisonFailure
     *
     * @throws \PHPUnit\Framework\Exception
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-return never-return
     */
    protected function fail($other, $description, ComparisonFailure $comparisonFailure = null): void
    {
        if ($comparisonFailure === null) {
            [$error, $recodedOther] = Json::canonicalize($other);

            if ($error) {
                parent::fail($other, $description);
            }

            [$error, $recodedValue] = Json::canonicalize($this->value);

            if ($error) {
                parent::fail($other, $description);
            }

            $comparisonFailure = new ComparisonFailure(
                json_decode($this->value),
                json_decode($other),
                Json::prettify($recodedValue),
                Json::prettify($recodedOther),
                false,
                'Failed asserting that two json values are equal.'
            );
        }

        parent::fail($other, $description, $comparisonFailure);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338
 *
 * @codeCoverageIgnore
 */
final class Attribute extends Composite
{
    /**
     * @var string
     */
    private $attributeName;

    public function __construct(Constraint $constraint, string $attributeName)
    {
        parent::__construct($constraint);

        $this->attributeName = $attributeName;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \PHPUnit\Framework\Exception
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        return parent::evaluate(
            Assert::readAttribute(
                $other,
                $this->attributeName
            ),
            $description,
            $returnResult
        );
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'attribute "' . $this->attributeName . '" ' . $this->innerConstraint()->toString();
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return $this->toString();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * Logical XOR.
 */
final class LogicalXor extends Constraint
{
    /**
     * @var Constraint[]
     */
    private $constraints = [];

    public static function fromConstraints(Constraint ...$constraints): self
    {
        $constraint = new self;

        $constraint->constraints = array_values($constraints);

        return $constraint;
    }

    /**
     * @param Constraint[] $constraints
     */
    public function setConstraints(array $constraints): void
    {
        $this->constraints = [];

        foreach ($constraints as $constraint) {
            if (!($constraint instanceof Constraint)) {
                $constraint = new IsEqual(
                    $constraint
                );
            }

            $this->constraints[] = $constraint;
        }
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success    = true;
        $lastResult = null;

        foreach ($this->constraints as $constraint) {
            $result = $constraint->evaluate($other, $description, true);

            if ($result === $lastResult) {
                $success = false;

                break;
            }

            $lastResult = $result;
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        $text = '';

        foreach ($this->constraints as $key => $constraint) {
            if ($key > 0) {
                $text .= ' xor ';
            }

            $text .= $constraint->toString();
        }

        return $text;
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        $count = 0;

        foreach ($this->constraints as $constraint) {
            $count += count($constraint);
        }

        return $count;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function get_resource_type;
use function is_array;
use function is_bool;
use function is_callable;
use function is_float;
use function is_int;
use function is_iterable;
use function is_numeric;
use function is_object;
use function is_resource;
use function is_scalar;
use function is_string;
use function sprintf;
use TypeError;

/**
 * Constraint that asserts that the value it is evaluated for is of a
 * specified type.
 *
 * The expected value is passed in the constructor.
 */
final class IsType extends Constraint
{
    /**
     * @var string
     */
    public const TYPE_ARRAY = 'array';

    /**
     * @var string
     */
    public const TYPE_BOOL = 'bool';

    /**
     * @var string
     */
    public const TYPE_FLOAT = 'float';

    /**
     * @var string
     */
    public const TYPE_INT = 'int';

    /**
     * @var string
     */
    public const TYPE_NULL = 'null';

    /**
     * @var string
     */
    public const TYPE_NUMERIC = 'numeric';

    /**
     * @var string
     */
    public const TYPE_OBJECT = 'object';

    /**
     * @var string
     */
    public const TYPE_RESOURCE = 'resource';

    /**
     * @var string
     */
    public const TYPE_STRING = 'string';

    /**
     * @var string
     */
    public const TYPE_SCALAR = 'scalar';

    /**
     * @var string
     */
    public const TYPE_CALLABLE = 'callable';

    /**
     * @var string
     */
    public const TYPE_ITERABLE = 'iterable';

    /**
     * @var array<string,bool>
     */
    private const KNOWN_TYPES = [
        'array'    => true,
        'boolean'  => true,
        'bool'     => true,
        'double'   => true,
        'float'    => true,
        'integer'  => true,
        'int'      => true,
        'null'     => true,
        'numeric'  => true,
        'object'   => true,
        'real'     => true,
        'resource' => true,
        'string'   => true,
        'scalar'   => true,
        'callable' => true,
        'iterable' => true,
    ];

    /**
     * @var string
     */
    private $type;

    /**
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct(string $type)
    {
        if (!isset(self::KNOWN_TYPES[$type])) {
            throw new \PHPUnit\Framework\Exception(
                sprintf(
                    'Type specified for PHPUnit\Framework\Constraint\IsType <%s> ' .
                    'is not a valid type.',
                    $type
                )
            );
        }

        $this->type = $type;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'is of type "%s"',
            $this->type
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        switch ($this->type) {
            case 'numeric':
                return is_numeric($other);

            case 'integer':
            case 'int':
                return is_int($other);

            case 'double':
            case 'float':
            case 'real':
                return is_float($other);

            case 'string':
                return is_string($other);

            case 'boolean':
            case 'bool':
                return is_bool($other);

            case 'null':
                return null === $other;

            case 'array':
                return is_array($other);

            case 'object':
                return is_object($other);

            case 'resource':
                if (is_resource($other)) {
                    return true;
                }

                try {
                    $resource = @get_resource_type($other);

                    if (is_string($resource)) {
                        return true;
                    }
                } catch (TypeError $e) {
                }

                return false;

            case 'scalar':
                return is_scalar($other);

            case 'callable':
                return is_callable($other);

            case 'iterable':
                return is_iterable($other);
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function count;
use function gettype;
use function sprintf;
use function strpos;
use Countable;
use EmptyIterator;

/**
 * Constraint that checks whether a variable is empty().
 */
final class IsEmpty extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is empty';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ($other instanceof EmptyIterator) {
            return true;
        }

        if ($other instanceof Countable) {
            return count($other) === 0;
        }

        return empty($other);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        $type = gettype($other);

        return sprintf(
            '%s %s %s',
            strpos($type, 'a') === 0 || strpos($type, 'o') === 0 ? 'an' : 'a',
            $type,
            $this->toString()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_array;
use function is_object;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;

/**
 * Constraint that asserts that the Traversable it is applied to contains
 * a given value.
 *
 * @deprecated Use TraversableContainsEqual or TraversableContainsIdentical instead
 */
final class TraversableContains extends Constraint
{
    /**
     * @var bool
     */
    private $checkForObjectIdentity;

    /**
     * @var bool
     */
    private $checkForNonObjectIdentity;

    /**
     * @var mixed
     */
    private $value;

    public function __construct($value, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false)
    {
        $this->checkForObjectIdentity    = $checkForObjectIdentity;
        $this->checkForNonObjectIdentity = $checkForNonObjectIdentity;
        $this->value                     = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        if (is_string($this->value) && strpos($this->value, "\n") !== false) {
            return 'contains "' . $this->value . '"';
        }

        return 'contains ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ($other instanceof SplObjectStorage) {
            return $other->contains($this->value);
        }

        if (is_object($this->value)) {
            foreach ($other as $element) {
                if ($this->checkForObjectIdentity && $element === $this->value) {
                    return true;
                }

                /* @noinspection TypeUnsafeComparisonInspection */
                if (!$this->checkForObjectIdentity && $element == $this->value) {
                    return true;
                }
            }
        } else {
            foreach ($other as $element) {
                if ($this->checkForNonObjectIdentity && $element === $this->value) {
                    return true;
                }

                /* @noinspection TypeUnsafeComparisonInspection */
                if (!$this->checkForNonObjectIdentity && $element == $this->value) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s %s',
            is_array($other) ? 'an array' : 'a traversable',
            $this->toString()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_string;
use function sprintf;
use function strpos;
use function trim;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;
use SebastianBergmann\Comparator\Factory as ComparatorFactory;

/**
 * Constraint that checks if one value is equal to another.
 *
 * Equality is checked with PHP's == operator, the operator is explained in
 * detail at {@url https://php.net/manual/en/types.comparisons.php}.
 * Two values are equal if they have the same value disregarding type.
 *
 * The expected value is passed in the constructor.
 */
final class IsEqual extends Constraint
{
    /**
     * @var mixed
     */
    private $value;

    /**
     * @var float
     */
    private $delta;

    /**
     * @var bool
     */
    private $canonicalize;

    /**
     * @var bool
     */
    private $ignoreCase;

    public function __construct($value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false)
    {
        $this->value        = $value;
        $this->delta        = $delta;
        $this->canonicalize = $canonicalize;
        $this->ignoreCase   = $ignoreCase;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        // If $this->value and $other are identical, they are also equal.
        // This is the most common path and will allow us to skip
        // initialization of all the comparators.
        if ($this->value === $other) {
            return true;
        }

        $comparatorFactory = ComparatorFactory::getInstance();

        try {
            $comparator = $comparatorFactory->getComparatorFor(
                $this->value,
                $other
            );

            $comparator->assertEquals(
                $this->value,
                $other,
                $this->delta,
                $this->canonicalize,
                $this->ignoreCase
            );
        } catch (ComparisonFailure $f) {
            if ($returnResult) {
                return false;
            }

            throw new ExpectationFailedException(
                trim($description . "\n" . $f->getMessage()),
                $f
            );
        }

        return true;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        $delta = '';

        if (is_string($this->value)) {
            if (strpos($this->value, "\n") !== false) {
                return 'is equal to <text>';
            }

            return sprintf(
                "is equal to '%s'",
                $this->value
            );
        }

        if ($this->delta != 0) {
            $delta = sprintf(
                ' with delta <%F>',
                $this->delta
            );
        }

        return sprintf(
            'is equal to %s%s',
            $this->exporter()->export($this->value),
            $delta
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use const DIRECTORY_SEPARATOR;
use function explode;
use function implode;
use function preg_match;
use function preg_quote;
use function preg_replace;
use function strtr;
use SebastianBergmann\Diff\Differ;

/**
 * ...
 */
final class StringMatchesFormatDescription extends RegularExpression
{
    /**
     * @var string
     */
    private $string;

    public function __construct(string $string)
    {
        parent::__construct(
            $this->createPatternFromFormat(
                $this->convertNewlines($string)
            )
        );

        $this->string = $string;
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return parent::matches(
            $this->convertNewlines($other)
        );
    }

    protected function failureDescription($other): string
    {
        return 'string matches format description';
    }

    protected function additionalFailureDescription($other): string
    {
        $from = explode("\n", $this->string);
        $to   = explode("\n", $this->convertNewlines($other));

        foreach ($from as $index => $line) {
            if (isset($to[$index]) && $line !== $to[$index]) {
                $line = $this->createPatternFromFormat($line);

                if (preg_match($line, $to[$index]) > 0) {
                    $from[$index] = $to[$index];
                }
            }
        }

        $this->string = implode("\n", $from);
        $other        = implode("\n", $to);

        return (new Differ("--- Expected\n+++ Actual\n"))->diff($this->string, $other);
    }

    private function createPatternFromFormat(string $string): string
    {
        $string = strtr(
            preg_quote($string, '/'),
            [
                '%%' => '%',
                '%e' => '\\' . DIRECTORY_SEPARATOR,
                '%s' => '[^\r\n]+',
                '%S' => '[^\r\n]*',
                '%a' => '.+',
                '%A' => '.*',
                '%w' => '\s*',
                '%i' => '[+-]?\d+',
                '%d' => '\d+',
                '%x' => '[0-9a-fA-F]+',
                '%f' => '[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?',
                '%c' => '.',
            ]
        );

        return '/^' . $string . '$/s';
    }

    private function convertNewlines($text): string
    {
        return preg_replace('/\r\n/', "\n", $text);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_nan;

/**
 * Constraint that accepts nan.
 */
final class IsNan extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is nan';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_nan($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function get_class;
use function is_object;
use function sprintf;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;

/**
 * Constraint that asserts that the class it is evaluated for has a given
 * attribute.
 *
 * The attribute name is passed in the constructor.
 */
class ClassHasAttribute extends Constraint
{
    /**
     * @var string
     */
    private $attributeName;

    public function __construct(string $attributeName)
    {
        $this->attributeName = $attributeName;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'has attribute "%s"',
            $this->attributeName
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        try {
            return (new ReflectionClass($other))->hasProperty($this->attributeName);
            // @codeCoverageIgnoreStart
        } catch (ReflectionException $e) {
            throw new Exception(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%sclass "%s" %s',
            is_object($other) ? 'object of ' : '',
            is_object($other) ? get_class($other) : $other,
            $this->toString()
        );
    }

    protected function attributeName(): string
    {
        return $this->attributeName;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use Countable;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\SelfDescribing;
use SebastianBergmann\Comparator\ComparisonFailure;
use SebastianBergmann\Exporter\Exporter;

/**
 * Abstract base class for constraints which can be applied to any value.
 */
abstract class Constraint implements Countable, SelfDescribing
{
    /**
     * @var Exporter
     */
    private $exporter;

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = false;

        if ($this->matches($other)) {
            $success = true;
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        return 1;
    }

    protected function exporter(): Exporter
    {
        if ($this->exporter === null) {
            $this->exporter = new Exporter;
        }

        return $this->exporter;
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * This method can be overridden to implement the evaluation algorithm.
     *
     * @param mixed $other value or object to evaluate
     *
     * @codeCoverageIgnore
     */
    protected function matches($other): bool
    {
        return false;
    }

    /**
     * Throws an exception for the given compared value and test description.
     *
     * @param mixed             $other             evaluated value or object
     * @param string            $description       Additional information about the test
     * @param ComparisonFailure $comparisonFailure
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     *
     * @psalm-return never-return
     */
    protected function fail($other, $description, ComparisonFailure $comparisonFailure = null): void
    {
        $failureDescription = sprintf(
            'Failed asserting that %s.',
            $this->failureDescription($other)
        );

        $additionalFailureDescription = $this->additionalFailureDescription($other);

        if ($additionalFailureDescription) {
            $failureDescription .= "\n" . $additionalFailureDescription;
        }

        if (!empty($description)) {
            $failureDescription = $description . "\n" . $failureDescription;
        }

        throw new ExpectationFailedException(
            $failureDescription,
            $comparisonFailure
        );
    }

    /**
     * Return additional failure description where needed.
     *
     * The function can be overridden to provide additional failure
     * information like a diff
     *
     * @param mixed $other evaluated value or object
     */
    protected function additionalFailureDescription($other): string
    {
        return '';
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * To provide additional failure information additionalFailureDescription
     * can be used.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return $this->exporter()->export($other) . ' ' . $this->toString();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function count;
use function is_array;
use function iterator_count;
use function sprintf;
use Countable;
use EmptyIterator;
use Generator;
use Iterator;
use IteratorAggregate;
use Traversable;

class Count extends Constraint
{
    /**
     * @var int
     */
    private $expectedCount;

    public function __construct(int $expected)
    {
        $this->expectedCount = $expected;
    }

    public function toString(): string
    {
        return sprintf(
            'count matches %d',
            $this->expectedCount
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     */
    protected function matches($other): bool
    {
        return $this->expectedCount === $this->getCountOf($other);
    }

    /**
     * @param iterable $other
     */
    protected function getCountOf($other): ?int
    {
        if ($other instanceof Countable || is_array($other)) {
            return count($other);
        }

        if ($other instanceof EmptyIterator) {
            return 0;
        }

        if ($other instanceof Traversable) {
            while ($other instanceof IteratorAggregate) {
                $other = $other->getIterator();
            }

            $iterator = $other;

            if ($iterator instanceof Generator) {
                return $this->getCountOfGenerator($iterator);
            }

            if (!$iterator instanceof Iterator) {
                return iterator_count($iterator);
            }

            $key   = $iterator->key();
            $count = iterator_count($iterator);

            // Manually rewind $iterator to previous key, since iterator_count
            // moves pointer.
            if ($key !== null) {
                $iterator->rewind();

                while ($iterator->valid() && $key !== $iterator->key()) {
                    $iterator->next();
                }
            }

            return $count;
        }

        return null;
    }

    /**
     * Returns the total number of iterations from a generator.
     * This will fully exhaust the generator.
     */
    protected function getCountOfGenerator(Generator $generator): int
    {
        for ($count = 0; $generator->valid(); $generator->next()) {
            $count++;
        }

        return $count;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            'actual size %d matches expected size %d',
            $this->getCountOf($other),
            $this->expectedCount
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_array;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;

/**
 * Constraint that asserts that the Traversable it is applied to contains
 * a given value (using non-strict comparison).
 */
final class TraversableContainsEqual extends Constraint
{
    /**
     * @var mixed
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        if (is_string($this->value) && strpos($this->value, "\n") !== false) {
            return 'contains "' . $this->value . '"';
        }

        return 'contains ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ($other instanceof SplObjectStorage) {
            return $other->contains($this->value);
        }

        foreach ($other as $element) {
            /* @noinspection TypeUnsafeComparisonInspection */
            if ($this->value == $element) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s %s',
            is_array($other) ? 'an array' : 'a traversable',
            $this->toString()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use ReflectionObject;

/**
 * Constraint that asserts that the object it is evaluated for has a given
 * attribute.
 *
 * The attribute name is passed in the constructor.
 */
final class ObjectHasAttribute extends ClassHasAttribute
{
    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return (new ReflectionObject($other))->hasProperty($this->attributeName());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_infinite;

/**
 * Constraint that accepts infinite.
 */
final class IsInfinite extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is infinite';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_infinite($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function mb_stripos;
use function mb_strpos;
use function mb_strtolower;
use function sprintf;

/**
 * Constraint that asserts that the string it is evaluated for contains
 * a given string.
 *
 * Uses mb_strpos() to find the position of the string in the input, if not
 * found the evaluation fails.
 *
 * The sub-string is passed in the constructor.
 */
final class StringContains extends Constraint
{
    /**
     * @var string
     */
    private $string;

    /**
     * @var bool
     */
    private $ignoreCase;

    public function __construct(string $string, bool $ignoreCase = false)
    {
        $this->string     = $string;
        $this->ignoreCase = $ignoreCase;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        if ($this->ignoreCase) {
            $string = mb_strtolower($this->string);
        } else {
            $string = $this->string;
        }

        return sprintf(
            'contains "%s"',
            $string
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        if ('' === $this->string) {
            return true;
        }

        if ($this->ignoreCase) {
            return mb_stripos($other, $this->string) !== false;
        }

        return mb_strpos($other, $this->string) !== false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function get_class;
use function is_array;
use function is_object;
use function is_string;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;

/**
 * Constraint that asserts that one value is identical to another.
 *
 * Identical check is performed with PHP's === operator, the operator is
 * explained in detail at
 * {@url https://php.net/manual/en/types.comparisons.php}.
 * Two values are identical if they have the same value and are of the same
 * type.
 *
 * The expected value is passed in the constructor.
 */
final class IsIdentical extends Constraint
{
    /**
     * @var mixed
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = $this->value === $other;

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $f = null;

            // if both values are strings, make sure a diff is generated
            if (is_string($this->value) && is_string($other)) {
                $f = new ComparisonFailure(
                    $this->value,
                    $other,
                    sprintf("'%s'", $this->value),
                    sprintf("'%s'", $other)
                );
            }

            // if both values are array, make sure a diff is generated
            if (is_array($this->value) && is_array($other)) {
                $f = new ComparisonFailure(
                    $this->value,
                    $other,
                    $this->exporter()->export($this->value),
                    $this->exporter()->export($other)
                );
            }

            $this->fail($other, $description, $f);
        }
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        if (is_object($this->value)) {
            return 'is identical to an object of class "' .
                get_class($this->value) . '"';
        }

        return 'is identical to ' . $this->exporter()->export($this->value);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        if (is_object($this->value) && is_object($other)) {
            return 'two variables reference the same object';
        }

        if (is_string($this->value) && is_string($other)) {
            return 'two strings are identical';
        }

        if (is_array($this->value) && is_array($other)) {
            return 'two arrays are identical';
        }

        return parent::failureDescription($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use const JSON_ERROR_CTRL_CHAR;
use const JSON_ERROR_DEPTH;
use const JSON_ERROR_NONE;
use const JSON_ERROR_STATE_MISMATCH;
use const JSON_ERROR_SYNTAX;
use const JSON_ERROR_UTF8;
use function strtolower;

/**
 * Provides human readable messages for each JSON error.
 */
final class JsonMatchesErrorMessageProvider
{
    /**
     * Translates JSON error to a human readable string.
     */
    public static function determineJsonError(string $error, string $prefix = ''): ?string
    {
        switch ($error) {
            case JSON_ERROR_NONE:
                return null;
            case JSON_ERROR_DEPTH:
                return $prefix . 'Maximum stack depth exceeded';
            case JSON_ERROR_STATE_MISMATCH:
                return $prefix . 'Underflow or the modes mismatch';
            case JSON_ERROR_CTRL_CHAR:
                return $prefix . 'Unexpected control character found';
            case JSON_ERROR_SYNTAX:
                return $prefix . 'Syntax error, malformed JSON';
            case JSON_ERROR_UTF8:
                return $prefix . 'Malformed UTF-8 characters, possibly incorrectly encoded';

            default:
                return $prefix . 'Unknown error';
        }
    }

    /**
     * Translates a given type to a human readable message prefix.
     */
    public static function translateTypeToPrefix(string $type): string
    {
        switch (strtolower($type)) {
            case 'expected':
                $prefix = 'Expected value JSON decode error - ';

                break;
            case 'actual':
                $prefix = 'Actual value JSON decode error - ';

                break;

            default:
                $prefix = '';

                break;
        }

        return $prefix;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that accepts null.
 */
final class IsNull extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is null';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $other === null;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function array_replace_recursive;
use function is_array;
use function iterator_to_array;
use function var_export;
use ArrayObject;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;
use Traversable;

/**
 * Constraint that asserts that the array it is evaluated for has a specified subset.
 *
 * Uses array_replace_recursive() to check if a key value subset is part of the
 * subject array.
 *
 * @codeCoverageIgnore
 *
 * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3494
 */
final class ArraySubset extends Constraint
{
    /**
     * @var iterable
     */
    private $subset;

    /**
     * @var bool
     */
    private $strict;

    public function __construct(iterable $subset, bool $strict = false)
    {
        $this->strict = $strict;
        $this->subset = $subset;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        //type cast $other & $this->subset as an array to allow
        //support in standard array functions.
        $other        = $this->toArray($other);
        $this->subset = $this->toArray($this->subset);

        $patched = array_replace_recursive($other, $this->subset);

        if ($this->strict) {
            $result = $other === $patched;
        } else {
            $result = $other == $patched;
        }

        if ($returnResult) {
            return $result;
        }

        if (!$result) {
            $f = new ComparisonFailure(
                $patched,
                $other,
                var_export($patched, true),
                var_export($other, true)
            );

            $this->fail($other, $description, $f);
        }
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'has the subset ' . $this->exporter()->export($this->subset);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return 'an array ' . $this->toString();
    }

    private function toArray(iterable $other): array
    {
        if (is_array($other)) {
            return $other;
        }

        if ($other instanceof ArrayObject) {
            return $other->getArrayCopy();
        }

        if ($other instanceof Traversable) {
            return iterator_to_array($other);
        }

        // Keep BC even if we know that array would not be the expected one
        return (array) $other;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

final class SameSize extends Count
{
    public function __construct(iterable $expected)
    {
        parent::__construct($this->getCountOf($expected));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function get_class;
use function sprintf;
use PHPUnit\Util\Filter;
use Throwable;

final class Exception extends Constraint
{
    /**
     * @var string
     */
    private $className;

    public function __construct(string $className)
    {
        $this->className = $className;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return sprintf(
            'exception of type "%s"',
            $this->className
        );
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $other instanceof $this->className;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        if ($other !== null) {
            $message = '';

            if ($other instanceof Throwable) {
                $message = '. Message was: "' . $other->getMessage() . '" at'
                    . "\n" . Filter::getFilteredStacktrace($other);
            }

            return sprintf(
                'exception of type "%s" matches expected exception "%s"%s',
                get_class($other),
                $this->className,
                $message
            );
        }

        return sprintf(
            'exception of type "%s" is thrown',
            $this->className
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_writable;
use function sprintf;

/**
 * Constraint that checks if the file/dir(name) that it is evaluated for is writable.
 *
 * The file path to check is passed as $other in evaluate().
 */
final class IsWritable extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is writable';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_writable($other);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '"%s" is writable',
            $other
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function sprintf;
use Throwable;

final class ExceptionCode extends Constraint
{
    /**
     * @var int|string
     */
    private $expectedCode;

    /**
     * @param int|string $expected
     */
    public function __construct($expected)
    {
        $this->expectedCode = $expected;
    }

    public function toString(): string
    {
        return 'exception code is ';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param Throwable $other
     */
    protected function matches($other): bool
    {
        return (string) $other->getCode() === (string) $this->expectedCode;
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s is equal to expected exception code %s',
            $this->exporter()->export($other->getCode()),
            $this->exporter()->export($this->expectedCode)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that evaluates against a specified closure.
 *
 * @psalm-template CallbackInput of mixed
 */
final class Callback extends Constraint
{
    /**
     * @var callable
     *
     * @psalm-var callable(CallbackInput $input): bool
     */
    private $callback;

    /** @psalm-param callable(CallbackInput $input): bool $callback */
    public function __construct(callable $callback)
    {
        $this->callback = $callback;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is accepted by specified callback';
    }

    /**
     * Evaluates the constraint for parameter $value. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     *
     * @psalm-param CallbackInput $other
     */
    protected function matches($other): bool
    {
        return ($this->callback)($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function count;
use function get_class;
use function preg_match;
use function str_replace;
use PHPUnit\Framework\ExpectationFailedException;

/**
 * Logical NOT.
 */
final class LogicalNot extends Constraint
{
    /**
     * @var Constraint
     */
    private $constraint;

    public static function negate(string $string): string
    {
        $positives = [
            'contains ',
            'exists',
            'has ',
            'is ',
            'are ',
            'matches ',
            'starts with ',
            'ends with ',
            'reference ',
            'not not ',
        ];

        $negatives = [
            'does not contain ',
            'does not exist',
            'does not have ',
            'is not ',
            'are not ',
            'does not match ',
            'starts not with ',
            'ends not with ',
            'don\'t reference ',
            'not ',
        ];

        preg_match('/(\'[\w\W]*\')([\w\W]*)("[\w\W]*")/i', $string, $matches);

        if (count($matches) > 0) {
            $nonInput = $matches[2];

            $negatedString = str_replace(
                $nonInput,
                str_replace(
                    $positives,
                    $negatives,
                    $nonInput
                ),
                $string
            );
        } else {
            $negatedString = str_replace(
                $positives,
                $negatives,
                $string
            );
        }

        return $negatedString;
    }

    /**
     * @param Constraint|mixed $constraint
     */
    public function __construct($constraint)
    {
        if (!($constraint instanceof Constraint)) {
            $constraint = new IsEqual($constraint);
        }

        $this->constraint = $constraint;
    }

    /**
     * Evaluates the constraint for parameter $other.
     *
     * If $returnResult is set to false (the default), an exception is thrown
     * in case of a failure. null is returned otherwise.
     *
     * If $returnResult is true, the result of the evaluation is returned as
     * a boolean value instead: true in case of success, false in case of a
     * failure.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws ExpectationFailedException
     */
    public function evaluate($other, string $description = '', bool $returnResult = false)
    {
        $success = !$this->constraint->evaluate($other, $description, true);

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        switch (get_class($this->constraint)) {
            case LogicalAnd::class:
            case self::class:
            case LogicalOr::class:
                return 'not( ' . $this->constraint->toString() . ' )';

            default:
                return self::negate(
                    $this->constraint->toString()
                );
        }
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        return count($this->constraint);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        switch (get_class($this->constraint)) {
            case LogicalAnd::class:
            case self::class:
            case LogicalOr::class:
                return 'not( ' . $this->constraint->failureDescription($other) . ' )';

            default:
                return self::negate(
                    $this->constraint->failureDescription($other)
                );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

/**
 * Constraint that asserts that the value it is evaluated for is greater
 * than a given value.
 */
final class GreaterThan extends Constraint
{
    /**
     * @var float|int
     */
    private $value;

    /**
     * @param float|int $value
     */
    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'is greater than ' . $this->exporter()->export($this->value);
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return $this->value < $other;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function strlen;
use function substr;

/**
 * Constraint that asserts that the string it is evaluated for ends with a given
 * suffix.
 */
final class StringEndsWith extends Constraint
{
    /**
     * @var string
     */
    private $suffix;

    public function __construct(string $suffix)
    {
        $this->suffix = $suffix;
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'ends with "' . $this->suffix . '"';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return substr($other, 0 - strlen($this->suffix)) === $this->suffix;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function is_finite;

/**
 * Constraint that accepts finite.
 */
final class IsFinite extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'is finite';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return is_finite($other);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\Constraint;

use function file_exists;
use function sprintf;

/**
 * Constraint that checks if the file(name) that it is evaluated for exists.
 *
 * The file path to check is passed as $other in evaluate().
 */
final class FileExists extends Constraint
{
    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        return 'file exists';
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     *
     * @param mixed $other value or object to evaluate
     */
    protected function matches($other): bool
    {
        return file_exists($other);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            'file "%s" exists',
            $other
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class IncompleteTestCase extends TestCase
{
    /**
     * @var bool
     */
    protected $backupGlobals = false;

    /**
     * @var bool
     */
    protected $backupStaticAttributes = false;

    /**
     * @var bool
     */
    protected $runTestInSeparateProcess = false;

    /**
     * @var string
     */
    private $message;

    public function __construct(string $className, string $methodName, string $message = '')
    {
        parent::__construct($className . '::' . $methodName);

        $this->message = $message;
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    /**
     * Returns a string representation of the test case.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return $this->getName();
    }

    /**
     * @throws Exception
     */
    protected function runTest(): void
    {
        $this->markTestIncomplete($this->message);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function get_class;
use function sprintf;
use function trim;
use PHPUnit\Framework\Error\Error;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestFailure
{
    /**
     * @var null|Test
     */
    private $failedTest;

    /**
     * @var Throwable
     */
    private $thrownException;

    /**
     * @var string
     */
    private $testName;

    /**
     * Returns a description for an exception.
     */
    public static function exceptionToString(Throwable $e): string
    {
        if ($e instanceof SelfDescribing) {
            $buffer = $e->toString();

            if ($e instanceof ExpectationFailedException && $e->getComparisonFailure()) {
                $buffer .= $e->getComparisonFailure()->getDiff();
            }

            if ($e instanceof PHPTAssertionFailedError) {
                $buffer .= $e->getDiff();
            }

            if (!empty($buffer)) {
                $buffer = trim($buffer) . "\n";
            }

            return $buffer;
        }

        if ($e instanceof Error) {
            return $e->getMessage() . "\n";
        }

        if ($e instanceof ExceptionWrapper) {
            return $e->getClassName() . ': ' . $e->getMessage() . "\n";
        }

        return get_class($e) . ': ' . $e->getMessage() . "\n";
    }

    /**
     * Constructs a TestFailure with the given test and exception.
     *
     * @param Throwable $t
     */
    public function __construct(Test $failedTest, $t)
    {
        if ($failedTest instanceof SelfDescribing) {
            $this->testName = $failedTest->toString();
        } else {
            $this->testName = get_class($failedTest);
        }

        if (!$failedTest instanceof TestCase || !$failedTest->isInIsolation()) {
            $this->failedTest = $failedTest;
        }

        $this->thrownException = $t;
    }

    /**
     * Returns a short description of the failure.
     */
    public function toString(): string
    {
        return sprintf(
            '%s: %s',
            $this->testName,
            $this->thrownException->getMessage()
        );
    }

    /**
     * Returns a description for the thrown exception.
     */
    public function getExceptionAsString(): string
    {
        return self::exceptionToString($this->thrownException);
    }

    /**
     * Returns the name of the failing test (including data set, if any).
     */
    public function getTestName(): string
    {
        return $this->testName;
    }

    /**
     * Returns the failing test.
     *
     * Note: The test object is not set when the test is executed in process
     * isolation.
     *
     * @see Exception
     */
    public function failedTest(): ?Test
    {
        return $this->failedTest;
    }

    /**
     * Gets the thrown exception.
     */
    public function thrownException(): Throwable
    {
        return $this->thrownException;
    }

    /**
     * Returns the exception's message.
     */
    public function exceptionMessage(): string
    {
        return $this->thrownException()->getMessage();
    }

    /**
     * Returns true if the thrown exception
     * is of type AssertionFailedError.
     */
    public function isFailure(): bool
    {
        return $this->thrownException() instanceof AssertionFailedError;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class SkippedTestCase extends TestCase
{
    /**
     * @var bool
     */
    protected $backupGlobals = false;

    /**
     * @var bool
     */
    protected $backupStaticAttributes = false;

    /**
     * @var bool
     */
    protected $runTestInSeparateProcess = false;

    /**
     * @var string
     */
    private $message;

    public function __construct(string $className, string $methodName, string $message = '')
    {
        parent::__construct($className . '::' . $methodName);

        $this->message = $message;
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    /**
     * Returns a string representation of the test case.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return $this->getName();
    }

    /**
     * @throws Exception
     */
    protected function runTest(): void
    {
        $this->markTestSkipped($this->message);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface TestResultCache
{
    public function setState(string $testName, int $state): void;

    public function getState(string $testName): int;

    public function setTime(string $testName, float $time): void;

    public function getTime(string $testName): float;

    public function load(): void;

    public function persist(): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use function is_dir;
use function is_file;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestSuite;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
abstract class BaseTestRunner
{
    /**
     * @var int
     */
    public const STATUS_UNKNOWN = -1;

    /**
     * @var int
     */
    public const STATUS_PASSED = 0;

    /**
     * @var int
     */
    public const STATUS_SKIPPED = 1;

    /**
     * @var int
     */
    public const STATUS_INCOMPLETE = 2;

    /**
     * @var int
     */
    public const STATUS_FAILURE = 3;

    /**
     * @var int
     */
    public const STATUS_ERROR = 4;

    /**
     * @var int
     */
    public const STATUS_RISKY = 5;

    /**
     * @var int
     */
    public const STATUS_WARNING = 6;

    /**
     * @var string
     */
    public const SUITE_METHODNAME = 'suite';

    /**
     * Returns the loader to be used.
     */
    public function getLoader(): TestSuiteLoader
    {
        return new StandardTestSuiteLoader;
    }

    /**
     * Returns the Test corresponding to the given suite.
     * This is a template method, subclasses override
     * the runFailed() and clearStatus() methods.
     *
     * @param string|string[] $suffixes
     *
     * @throws Exception
     */
    public function getTest(string $suiteClassName, string $suiteClassFile = '', $suffixes = ''): ?Test
    {
        if (empty($suiteClassFile) && is_dir($suiteClassName) && !is_file($suiteClassName . '.php')) {
            /** @var string[] $files */
            $files = (new FileIteratorFacade)->getFilesAsArray(
                $suiteClassName,
                $suffixes
            );

            $suite = new TestSuite($suiteClassName);
            $suite->addTestFiles($files);

            return $suite;
        }

        try {
            $testClass = $this->loadSuiteClass(
                $suiteClassName,
                $suiteClassFile
            );
        } catch (Exception $e) {
            $this->runFailed($e->getMessage());

            return null;
        }

        try {
            $suiteMethod = $testClass->getMethod(self::SUITE_METHODNAME);

            if (!$suiteMethod->isStatic()) {
                $this->runFailed(
                    'suite() method must be static.'
                );

                return null;
            }

            $test = $suiteMethod->invoke(null, $testClass->getName());
        } catch (ReflectionException $e) {
            try {
                $test = new TestSuite($testClass);
            } catch (Exception $e) {
                $test = new TestSuite;
                $test->setName($suiteClassName);
            }
        }

        $this->clearStatus();

        return $test;
    }

    /**
     * Returns the loaded ReflectionClass for a suite name.
     */
    protected function loadSuiteClass(string $suiteClassName, string $suiteClassFile = ''): ReflectionClass
    {
        return $this->getLoader()->load($suiteClassName, $suiteClassFile);
    }

    /**
     * Clears the status message.
     */
    protected function clearStatus(): void
    {
    }

    /**
     * Override to define how to handle a failed loading of
     * a test suite.
     */
    abstract protected function runFailed(string $message): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use function preg_match;
use function round;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTestHook, AfterRiskyTestHook, AfterSkippedTestHook, AfterSuccessfulTestHook, AfterTestErrorHook, AfterTestFailureHook, AfterTestWarningHook
{
    /**
     * @var TestResultCache
     */
    private $cache;

    public function __construct(TestResultCache $cache)
    {
        $this->cache = $cache;
    }

    public function flush(): void
    {
        $this->cache->persist();
    }

    public function executeAfterSuccessfulTest(string $test, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
    }

    public function executeAfterIncompleteTest(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_INCOMPLETE);
    }

    public function executeAfterRiskyTest(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_RISKY);
    }

    public function executeAfterSkippedTest(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_SKIPPED);
    }

    public function executeAfterTestError(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_ERROR);
    }

    public function executeAfterTestFailure(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_FAILURE);
    }

    public function executeAfterTestWarning(string $test, string $message, float $time): void
    {
        $testName = $this->getTestName($test);

        $this->cache->setTime($testName, round($time, 3));
        $this->cache->setState($testName, BaseTestRunner::STATUS_WARNING);
    }

    public function executeAfterLastTest(): void
    {
        $this->flush();
    }

    /**
     * @param string $test A long description format of the current test
     *
     * @return string The test name without TestSuiteClassName:: and @dataprovider details
     */
    private function getTestName(string $test): string
    {
        $matches = [];

        if (preg_match('/^(?<name>\S+::\S+)(?:(?<dataname> with data set (?:#\d+|"[^"]+"))\s\()?/', $test, $matches)) {
            $test = $matches['name'] . ($matches['dataname'] ?? '');
        }

        return $test;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use const DEBUG_BACKTRACE_IGNORE_ARGS;
use const DIRECTORY_SEPARATOR;
use function array_merge;
use function basename;
use function debug_backtrace;
use function defined;
use function dirname;
use function explode;
use function extension_loaded;
use function file;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function is_array;
use function is_file;
use function is_readable;
use function is_string;
use function ltrim;
use function phpversion;
use function preg_match;
use function preg_replace;
use function preg_split;
use function realpath;
use function rtrim;
use function sprintf;
use function str_replace;
use function strncasecmp;
use function strpos;
use function substr;
use function trim;
use function unlink;
use function unserialize;
use function var_export;
use function version_compare;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\IncompleteTestError;
use PHPUnit\Framework\PHPTAssertionFailedError;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\SkippedTestError;
use PHPUnit\Framework\SyntheticSkippedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestResult;
use PHPUnit\Util\PHP\AbstractPhpProcess;
use SebastianBergmann\Timer\Timer;
use Text_Template;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class PhptTestCase implements SelfDescribing, Test
{
    /**
     * @var string
     */
    private $filename;

    /**
     * @var AbstractPhpProcess
     */
    private $phpUtil;

    /**
     * @var string
     */
    private $output = '';

    /**
     * Constructs a test case with the given filename.
     *
     * @throws Exception
     */
    public function __construct(string $filename, AbstractPhpProcess $phpUtil = null)
    {
        if (!is_file($filename)) {
            throw new Exception(
                sprintf(
                    'File "%s" does not exist.',
                    $filename
                )
            );
        }

        $this->filename = $filename;
        $this->phpUtil  = $phpUtil ?: AbstractPhpProcess::factory();
    }

    /**
     * Counts the number of test cases executed by run(TestResult result).
     */
    public function count(): int
    {
        return 1;
    }

    /**
     * Runs a test and collects its result in a TestResult instance.
     *
     * @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     * @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
     * @throws \SebastianBergmann\CodeCoverage\RuntimeException
     * @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     */
    public function run(TestResult $result = null): TestResult
    {
        if ($result === null) {
            $result = new TestResult;
        }

        try {
            $sections = $this->parse();
        } catch (Exception $e) {
            $result->startTest($this);
            $result->addFailure($this, new SkippedTestError($e->getMessage()), 0);
            $result->endTest($this, 0);

            return $result;
        }

        $code     = $this->render($sections['FILE']);
        $xfail    = false;
        $settings = $this->parseIniSection($this->settings($result->getCollectCodeCoverageInformation()));

        $result->startTest($this);

        if (isset($sections['INI'])) {
            $settings = $this->parseIniSection($sections['INI'], $settings);
        }

        if (isset($sections['ENV'])) {
            $env = $this->parseEnvSection($sections['ENV']);
            $this->phpUtil->setEnv($env);
        }

        $this->phpUtil->setUseStderrRedirection(true);

        if ($result->enforcesTimeLimit()) {
            $this->phpUtil->setTimeout($result->getTimeoutForLargeTests());
        }

        $skip = $this->runSkip($sections, $result, $settings);

        if ($skip) {
            return $result;
        }

        if (isset($sections['XFAIL'])) {
            $xfail = trim($sections['XFAIL']);
        }

        if (isset($sections['STDIN'])) {
            $this->phpUtil->setStdin($sections['STDIN']);
        }

        if (isset($sections['ARGS'])) {
            $this->phpUtil->setArgs($sections['ARGS']);
        }

        if ($result->getCollectCodeCoverageInformation()) {
            $this->renderForCoverage($code);
        }

        Timer::start();

        $jobResult    = $this->phpUtil->runJob($code, $this->stringifyIni($settings));
        $time         = Timer::stop();
        $this->output = $jobResult['stdout'] ?? '';

        if ($result->getCollectCodeCoverageInformation() && ($coverage = $this->cleanupForCoverage())) {
            $result->getCodeCoverage()->append($coverage, $this, true, [], [], true);
        }

        try {
            $this->assertPhptExpectation($sections, $this->output);
        } catch (AssertionFailedError $e) {
            $failure = $e;

            if ($xfail !== false) {
                $failure = new IncompleteTestError($xfail, 0, $e);
            } elseif ($e instanceof ExpectationFailedException) {
                $comparisonFailure = $e->getComparisonFailure();

                if ($comparisonFailure) {
                    $diff = $comparisonFailure->getDiff();
                } else {
                    $diff = $e->getMessage();
                }

                $hint    = $this->getLocationHintFromDiff($diff, $sections);
                $trace   = array_merge($hint, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
                $failure = new PHPTAssertionFailedError(
                    $e->getMessage(),
                    0,
                    $trace[0]['file'],
                    $trace[0]['line'],
                    $trace,
                    $comparisonFailure ? $diff : ''
                );
            }

            $result->addFailure($this, $failure, $time);
        } catch (Throwable $t) {
            $result->addError($this, $t, $time);
        }

        if ($xfail !== false && $result->allCompletelyImplemented()) {
            $result->addFailure($this, new IncompleteTestError('XFAIL section but test passes'), $time);
        }

        $this->runClean($sections, $result->getCollectCodeCoverageInformation());

        $result->endTest($this, $time);

        return $result;
    }

    /**
     * Returns the name of the test case.
     */
    public function getName(): string
    {
        return $this->toString();
    }

    /**
     * Returns a string representation of the test case.
     */
    public function toString(): string
    {
        return $this->filename;
    }

    public function usesDataProvider(): bool
    {
        return false;
    }

    public function getNumAssertions(): int
    {
        return 1;
    }

    public function getActualOutput(): string
    {
        return $this->output;
    }

    public function hasOutput(): bool
    {
        return !empty($this->output);
    }

    /**
     * Parse --INI-- section key value pairs and return as array.
     *
     * @param array|string
     */
    private function parseIniSection($content, $ini = []): array
    {
        if (is_string($content)) {
            $content = explode("\n", trim($content));
        }

        foreach ($content as $setting) {
            if (strpos($setting, '=') === false) {
                continue;
            }

            $setting = explode('=', $setting, 2);
            $name    = trim($setting[0]);
            $value   = trim($setting[1]);

            if ($name === 'extension' || $name === 'zend_extension') {
                if (!isset($ini[$name])) {
                    $ini[$name] = [];
                }

                $ini[$name][] = $value;

                continue;
            }

            $ini[$name] = $value;
        }

        return $ini;
    }

    private function parseEnvSection(string $content): array
    {
        $env = [];

        foreach (explode("\n", trim($content)) as $e) {
            $e = explode('=', trim($e), 2);

            if (!empty($e[0]) && isset($e[1])) {
                $env[$e[0]] = $e[1];
            }
        }

        return $env;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     * @throws ExpectationFailedException
     */
    private function assertPhptExpectation(array $sections, string $output): void
    {
        $assertions = [
            'EXPECT'      => 'assertEquals',
            'EXPECTF'     => 'assertStringMatchesFormat',
            'EXPECTREGEX' => 'assertRegExp',
        ];

        $actual = preg_replace('/\r\n/', "\n", trim($output));

        foreach ($assertions as $sectionName => $sectionAssertion) {
            if (isset($sections[$sectionName])) {
                $sectionContent = preg_replace('/\r\n/', "\n", trim($sections[$sectionName]));
                $expected       = $sectionName === 'EXPECTREGEX' ? "/{$sectionContent}/" : $sectionContent;

                if ($expected === null) {
                    throw new Exception('No PHPT expectation found');
                }

                Assert::$sectionAssertion($expected, $actual);

                return;
            }
        }

        throw new Exception('No PHPT assertion found');
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function runSkip(array &$sections, TestResult $result, array $settings): bool
    {
        if (!isset($sections['SKIPIF'])) {
            return false;
        }

        $skipif    = $this->render($sections['SKIPIF']);
        $jobResult = $this->phpUtil->runJob($skipif, $this->stringifyIni($settings));

        if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) {
            $message = '';

            if (preg_match('/^\s*skip\s*(.+)\s*/i', $jobResult['stdout'], $skipMatch)) {
                $message = substr($skipMatch[1], 2);
            }

            $hint  = $this->getLocationHint($message, $sections, 'SKIPIF');
            $trace = array_merge($hint, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
            $result->addFailure(
                $this,
                new SyntheticSkippedError($message, 0, $trace[0]['file'], $trace[0]['line'], $trace),
                0
            );
            $result->endTest($this, 0);

            return true;
        }

        return false;
    }

    private function runClean(array &$sections, bool $collectCoverage): void
    {
        $this->phpUtil->setStdin('');
        $this->phpUtil->setArgs('');

        if (isset($sections['CLEAN'])) {
            $cleanCode = $this->render($sections['CLEAN']);

            $this->phpUtil->runJob($cleanCode, $this->settings($collectCoverage));
        }
    }

    /**
     * @throws Exception
     */
    private function parse(): array
    {
        $sections = [];
        $section  = '';

        $unsupportedSections = [
            'CGI',
            'COOKIE',
            'DEFLATE_POST',
            'EXPECTHEADERS',
            'EXTENSIONS',
            'GET',
            'GZIP_POST',
            'HEADERS',
            'PHPDBG',
            'POST',
            'POST_RAW',
            'PUT',
            'REDIRECTTEST',
            'REQUEST',
        ];

        $lineNr = 0;

        foreach (file($this->filename) as $line) {
            $lineNr++;

            if (preg_match('/^--([_A-Z]+)--/', $line, $result)) {
                $section                        = $result[1];
                $sections[$section]             = '';
                $sections[$section . '_offset'] = $lineNr;

                continue;
            }

            if (empty($section)) {
                throw new Exception('Invalid PHPT file: empty section header');
            }

            $sections[$section] .= $line;
        }

        if (isset($sections['FILEEOF'])) {
            $sections['FILE'] = rtrim($sections['FILEEOF'], "\r\n");
            unset($sections['FILEEOF']);
        }

        $this->parseExternal($sections);

        if (!$this->validate($sections)) {
            throw new Exception('Invalid PHPT file');
        }

        foreach ($unsupportedSections as $section) {
            if (isset($sections[$section])) {
                throw new Exception(
                    "PHPUnit does not support PHPT {$section} sections"
                );
            }
        }

        return $sections;
    }

    /**
     * @throws Exception
     */
    private function parseExternal(array &$sections): void
    {
        $allowSections = [
            'FILE',
            'EXPECT',
            'EXPECTF',
            'EXPECTREGEX',
        ];
        $testDirectory = dirname($this->filename) . DIRECTORY_SEPARATOR;

        foreach ($allowSections as $section) {
            if (isset($sections[$section . '_EXTERNAL'])) {
                $externalFilename = trim($sections[$section . '_EXTERNAL']);

                if (!is_file($testDirectory . $externalFilename) ||
                    !is_readable($testDirectory . $externalFilename)) {
                    throw new Exception(
                        sprintf(
                            'Could not load --%s-- %s for PHPT file',
                            $section . '_EXTERNAL',
                            $testDirectory . $externalFilename
                        )
                    );
                }

                $sections[$section] = file_get_contents($testDirectory . $externalFilename);
            }
        }
    }

    private function validate(array &$sections): bool
    {
        $requiredSections = [
            'FILE',
            [
                'EXPECT',
                'EXPECTF',
                'EXPECTREGEX',
            ],
        ];

        foreach ($requiredSections as $section) {
            if (is_array($section)) {
                $foundSection = false;

                foreach ($section as $anySection) {
                    if (isset($sections[$anySection])) {
                        $foundSection = true;

                        break;
                    }
                }

                if (!$foundSection) {
                    return false;
                }

                continue;
            }

            if (!isset($sections[$section])) {
                return false;
            }
        }

        return true;
    }

    private function render(string $code): string
    {
        return str_replace(
            [
                '__DIR__',
                '__FILE__',
            ],
            [
                "'" . dirname($this->filename) . "'",
                "'" . $this->filename . "'",
            ],
            $code
        );
    }

    private function getCoverageFiles(): array
    {
        $baseDir  = dirname(realpath($this->filename)) . DIRECTORY_SEPARATOR;
        $basename = basename($this->filename, 'phpt');

        return [
            'coverage' => $baseDir . $basename . 'coverage',
            'job'      => $baseDir . $basename . 'php',
        ];
    }

    private function renderForCoverage(string &$job): void
    {
        $files = $this->getCoverageFiles();

        $template = new Text_Template(
            __DIR__ . '/../Util/PHP/Template/PhptTestCase.tpl'
        );

        $composerAutoload = '\'\'';

        if (defined('PHPUNIT_COMPOSER_INSTALL')) {
            $composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true);
        }

        $phar = '\'\'';

        if (defined('__PHPUNIT_PHAR__')) {
            $phar = var_export(__PHPUNIT_PHAR__, true);
        }

        $globals = '';

        if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
            $globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export(
                $GLOBALS['__PHPUNIT_BOOTSTRAP'],
                true
            ) . ";\n";
        }

        $template->setVar(
            [
                'composerAutoload' => $composerAutoload,
                'phar'             => $phar,
                'globals'          => $globals,
                'job'              => $files['job'],
                'coverageFile'     => $files['coverage'],
            ]
        );

        file_put_contents($files['job'], $job);
        $job = $template->render();
    }

    private function cleanupForCoverage(): array
    {
        $coverage = [];
        $files    = $this->getCoverageFiles();

        if (file_exists($files['coverage'])) {
            $buffer = @file_get_contents($files['coverage']);

            if ($buffer !== false) {
                $coverage = @unserialize($buffer);

                if ($coverage === false) {
                    $coverage = [];
                }
            }
        }

        foreach ($files as $file) {
            @unlink($file);
        }

        return $coverage;
    }

    private function stringifyIni(array $ini): array
    {
        $settings = [];

        foreach ($ini as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $val) {
                    $settings[] = $key . '=' . $val;
                }

                continue;
            }

            $settings[] = $key . '=' . $value;
        }

        return $settings;
    }

    private function getLocationHintFromDiff(string $message, array $sections): array
    {
        $needle       = '';
        $previousLine = '';
        $block        = 'message';

        foreach (preg_split('/\r\n|\r|\n/', $message) as $line) {
            $line = trim($line);

            if ($block === 'message' && $line === '--- Expected') {
                $block = 'expected';
            }

            if ($block === 'expected' && $line === '@@ @@') {
                $block = 'diff';
            }

            if ($block === 'diff') {
                if (strpos($line, '+') === 0) {
                    $needle = $this->getCleanDiffLine($previousLine);

                    break;
                }

                if (strpos($line, '-') === 0) {
                    $needle = $this->getCleanDiffLine($line);

                    break;
                }
            }

            if (!empty($line)) {
                $previousLine = $line;
            }
        }

        return $this->getLocationHint($needle, $sections);
    }

    private function getCleanDiffLine(string $line): string
    {
        if (preg_match('/^[\-+]([\'\"]?)(.*)\1$/', $line, $matches)) {
            $line = $matches[2];
        }

        return $line;
    }

    private function getLocationHint(string $needle, array $sections, ?string $sectionName = null): array
    {
        $needle = trim($needle);

        if (empty($needle)) {
            return [[
                'file' => realpath($this->filename),
                'line' => 1,
            ]];
        }

        if ($sectionName) {
            $search = [$sectionName];
        } else {
            $search = [
                // 'FILE',
                'EXPECT',
                'EXPECTF',
                'EXPECTREGEX',
            ];
        }

        foreach ($search as $section) {
            if (!isset($sections[$section])) {
                continue;
            }

            if (isset($sections[$section . '_EXTERNAL'])) {
                $externalFile = trim($sections[$section . '_EXTERNAL']);

                return [
                    [
                        'file' => realpath(dirname($this->filename) . DIRECTORY_SEPARATOR . $externalFile),
                        'line' => 1,
                    ],
                    [
                        'file' => realpath($this->filename),
                        'line' => ($sections[$section . '_EXTERNAL_offset'] ?? 0) + 1,
                    ],
                ];
            }

            $sectionOffset = $sections[$section . '_offset'] ?? 0;
            $offset        = $sectionOffset + 1;

            foreach (preg_split('/\r\n|\r|\n/', $sections[$section]) as $line) {
                if (strpos($line, $needle) !== false) {
                    return [[
                        'file' => realpath($this->filename),
                        'line' => $offset,
                    ]];
                }
                $offset++;
            }
        }

        if ($sectionName) {
            // String not found in specified section, show user the start of the named section
            return [[
                'file' => realpath($this->filename),
                'line' => $sectionOffset,
            ]];
        }

        // No section specified, show user start of code
        return [[
            'file' => realpath($this->filename),
            'line' => 1,
        ]];
    }

    /**
     * @psalm-return list<string>
     */
    private function settings(bool $collectCoverage): array
    {
        $settings = [
            'allow_url_fopen=1',
            'auto_append_file=',
            'auto_prepend_file=',
            'disable_functions=',
            'display_errors=1',
            'docref_ext=.html',
            'docref_root=',
            'error_append_string=',
            'error_prepend_string=',
            'error_reporting=-1',
            'html_errors=0',
            'log_errors=0',
            'open_basedir=',
            'output_buffering=Off',
            'output_handler=',
            'report_memleaks=0',
            'report_zend_debug=0',
        ];

        if (extension_loaded('pcov')) {
            if ($collectCoverage) {
                $settings[] = 'pcov.enabled=1';
            } else {
                $settings[] = 'pcov.enabled=0';
            }
        }

        if (extension_loaded('xdebug')) {
            if (version_compare(phpversion('xdebug'), '3', '>=')) {
                if ($collectCoverage) {
                    $settings[] = 'xdebug.mode=coverage';
                } else {
                    $settings[] = 'xdebug.mode=off';
                }
            } else {
                $settings[] = 'xdebug.default_enable=0';

                if ($collectCoverage) {
                    $settings[] = 'xdebug.coverage_enable=1';
                }
            }
        }

        return $settings;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use function array_diff;
use function array_values;
use function class_exists;
use function get_declared_classes;
use function realpath;
use function sprintf;
use function str_replace;
use function strlen;
use function substr;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\FileLoader;
use PHPUnit\Util\Filesystem;
use ReflectionClass;
use ReflectionException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class StandardTestSuiteLoader implements TestSuiteLoader
{
    /**
     * @throws \PHPUnit\Framework\Exception
     * @throws Exception
     */
    public function load(string $suiteClassName, string $suiteClassFile = ''): ReflectionClass
    {
        $suiteClassName = str_replace('.php', '', $suiteClassName);
        $filename       = null;

        if (empty($suiteClassFile)) {
            $suiteClassFile = Filesystem::classNameToFilename(
                $suiteClassName
            );
        }

        if (!class_exists($suiteClassName, false)) {
            $loadedClasses = get_declared_classes();

            $filename = FileLoader::checkAndLoad($suiteClassFile);

            $loadedClasses = array_values(
                array_diff(get_declared_classes(), $loadedClasses)
            );
        }

        if (!empty($loadedClasses) && !class_exists($suiteClassName, false)) {
            $offset = 0 - strlen($suiteClassName);

            foreach ($loadedClasses as $loadedClass) {
                try {
                    $class = new ReflectionClass($loadedClass);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                if (substr($loadedClass, $offset) === $suiteClassName &&
                    $class->getFileName() == $filename) {
                    $suiteClassName = $loadedClass;

                    break;
                }
            }
        }

        if (!empty($loadedClasses) && !class_exists($suiteClassName, false)) {
            $testCaseClass = TestCase::class;

            foreach ($loadedClasses as $loadedClass) {
                try {
                    $class = new ReflectionClass($loadedClass);
                    // @codeCoverageIgnoreStart
                } catch (ReflectionException $e) {
                    throw new Exception(
                        $e->getMessage(),
                        $e->getCode(),
                        $e
                    );
                }
                // @codeCoverageIgnoreEnd

                $classFile = $class->getFileName();

                if ($class->isSubclassOf($testCaseClass) && !$class->isAbstract()) {
                    $suiteClassName = $loadedClass;
                    $testCaseClass  = $loadedClass;

                    if ($classFile == realpath($suiteClassFile)) {
                        break;
                    }
                }

                if ($class->hasMethod('suite')) {
                    try {
                        $method = $class->getMethod('suite');
                        // @codeCoverageIgnoreStart
                    } catch (ReflectionException $e) {
                        throw new Exception(
                            $e->getMessage(),
                            $e->getCode(),
                            $e
                        );
                    }
                    // @codeCoverageIgnoreEnd

                    if (!$method->isAbstract() && $method->isPublic() && $method->isStatic()) {
                        $suiteClassName = $loadedClass;

                        if ($classFile == realpath($suiteClassFile)) {
                            break;
                        }
                    }
                }
            }
        }

        if (class_exists($suiteClassName, false)) {
            try {
                $class = new ReflectionClass($suiteClassName);
                // @codeCoverageIgnoreStart
            } catch (ReflectionException $e) {
                throw new Exception(
                    $e->getMessage(),
                    $e->getCode(),
                    $e
                );
            }
            // @codeCoverageIgnoreEnd

            if ($class->getFileName() == realpath($suiteClassFile)) {
                return $class;
            }
        }

        throw new Exception(
            sprintf(
                "Class '%s' could not be found in '%s'.",
                $suiteClassName,
                $suiteClassFile
            )
        );
    }

    public function reload(ReflectionClass $aClass): ReflectionClass
    {
        return $aClass;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use function array_slice;
use function dirname;
use function explode;
use function implode;
use function strpos;
use SebastianBergmann\Version as VersionId;

final class Version
{
    /**
     * @var string
     */
    private static $pharVersion = '';

    /**
     * @var string
     */
    private static $version = '';

    /**
     * Returns the current version of PHPUnit.
     */
    public static function id(): string
    {
        if (self::$pharVersion !== '') {
            return self::$pharVersion;
        }

        if (self::$version === '') {
            self::$version = (new VersionId('8.5.32', dirname(__DIR__, 2)))->getVersion();
        }

        return self::$version;
    }

    public static function series(): string
    {
        if (strpos(self::id(), '-')) {
            $version = explode('-', self::id())[0];
        } else {
            $version = self::id();
        }

        return implode('.', array_slice(explode('.', $version), 0, 2));
    }

    public static function getVersionString(): string
    {
        return 'PHPUnit ' . self::id() . ' by Sebastian Bergmann and contributors.';
    }

    public static function getReleaseChannel(): string
    {
        if (strpos(self::$pharVersion, '-') !== false) {
            return '-snapshot';
        }

        return '';
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use ReflectionClass;

/**
 * An interface to define how a test suite should be loaded.
 */
interface TestSuiteLoader
{
    public function load(string $suiteClassName, string $suiteClassFile = ''): ReflectionClass;

    public function reload(ReflectionClass $aClass): ReflectionClass;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use const DIRECTORY_SEPARATOR;
use const LOCK_EX;
use function assert;
use function dirname;
use function file_get_contents;
use function file_put_contents;
use function in_array;
use function is_array;
use function is_dir;
use function is_file;
use function json_decode;
use function json_encode;
use function sprintf;
use PHPUnit\Util\Filesystem;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class DefaultTestResultCache implements TestResultCache
{
    /**
     * @var int
     */
    private const VERSION = 1;

    /**
     * @psalm-var list<int>
     */
    private const ALLOWED_TEST_STATUSES = [
        BaseTestRunner::STATUS_SKIPPED,
        BaseTestRunner::STATUS_INCOMPLETE,
        BaseTestRunner::STATUS_FAILURE,
        BaseTestRunner::STATUS_ERROR,
        BaseTestRunner::STATUS_RISKY,
        BaseTestRunner::STATUS_WARNING,
    ];

    /**
     * @var string
     */
    private const DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache';

    /**
     * @var string
     */
    private $cacheFilename;

    /**
     * @psalm-var array<string, int>
     */
    private $defects = [];

    /**
     * @psalm-var array<string, float>
     */
    private $times = [];

    public function __construct(?string $filepath = null)
    {
        if ($filepath !== null && is_dir($filepath)) {
            $filepath .= DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME;
        }

        $this->cacheFilename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_RESULT_CACHE_FILENAME;
    }

    public function setState(string $testName, int $state): void
    {
        if (!in_array($state, self::ALLOWED_TEST_STATUSES, true)) {
            return;
        }

        $this->defects[$testName] = $state;
    }

    public function getState(string $testName): int
    {
        return $this->defects[$testName] ?? BaseTestRunner::STATUS_UNKNOWN;
    }

    public function setTime(string $testName, float $time): void
    {
        $this->times[$testName] = $time;
    }

    public function getTime(string $testName): float
    {
        return $this->times[$testName] ?? 0.0;
    }

    public function load(): void
    {
        if (!is_file($this->cacheFilename)) {
            return;
        }

        $data = json_decode(
            file_get_contents($this->cacheFilename),
            true
        );

        if ($data === null) {
            return;
        }

        if (!isset($data['version'])) {
            return;
        }

        if ($data['version'] !== self::VERSION) {
            return;
        }

        assert(isset($data['defects']) && is_array($data['defects']));
        assert(isset($data['times']) && is_array($data['times']));

        $this->defects = $data['defects'];
        $this->times   = $data['times'];
    }

    /**
     * @throws Exception
     */
    public function persist(): void
    {
        if (!Filesystem::createDirectory(dirname($this->cacheFilename))) {
            throw new Exception(
                sprintf(
                    'Cannot create directory "%s" for result cache file',
                    $this->cacheFilename
                )
            );
        }

        file_put_contents(
            $this->cacheFilename,
            json_encode(
                [
                    'version' => self::VERSION,
                    'defects' => $this->defects,
                    'times'   => $this->times,
                ]
            ),
            LOCK_EX
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use function array_intersect;
use function array_map;
use function array_merge;
use function array_reduce;
use function array_reverse;
use function array_splice;
use function count;
use function get_class;
use function in_array;
use function max;
use function shuffle;
use function strpos;
use function substr;
use function usort;
use PHPUnit\Framework\DataProviderTestSuite;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Util\Test as TestUtil;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestSuiteSorter
{
    /**
     * @var int
     */
    public const ORDER_DEFAULT = 0;

    /**
     * @var int
     */
    public const ORDER_RANDOMIZED = 1;

    /**
     * @var int
     */
    public const ORDER_REVERSED = 2;

    /**
     * @var int
     */
    public const ORDER_DEFECTS_FIRST = 3;

    /**
     * @var int
     */
    public const ORDER_DURATION = 4;

    /**
     * Order tests by @size annotation 'small', 'medium', 'large'.
     *
     * @var int
     */
    public const ORDER_SIZE = 5;

    /**
     * List of sorting weights for all test result codes. A higher number gives higher priority.
     */
    private const DEFECT_SORT_WEIGHT = [
        BaseTestRunner::STATUS_ERROR      => 6,
        BaseTestRunner::STATUS_FAILURE    => 5,
        BaseTestRunner::STATUS_WARNING    => 4,
        BaseTestRunner::STATUS_INCOMPLETE => 3,
        BaseTestRunner::STATUS_RISKY      => 2,
        BaseTestRunner::STATUS_SKIPPED    => 1,
        BaseTestRunner::STATUS_UNKNOWN    => 0,
    ];

    private const SIZE_SORT_WEIGHT = [
        TestUtil::SMALL   => 1,
        TestUtil::MEDIUM  => 2,
        TestUtil::LARGE   => 3,
        TestUtil::UNKNOWN => 4,
    ];

    /**
     * @var array<string, int> Associative array of (string => DEFECT_SORT_WEIGHT) elements
     */
    private $defectSortOrder = [];

    /**
     * @var TestResultCache
     */
    private $cache;

    /**
     * @var string[] A list of normalized names of tests before reordering
     */
    private $originalExecutionOrder = [];

    /**
     * @var string[] A list of normalized names of tests affected by reordering
     */
    private $executionOrder = [];

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public static function getTestSorterUID(Test $test): string
    {
        if ($test instanceof PhptTestCase) {
            return $test->getName();
        }

        if ($test instanceof TestCase) {
            $testName = $test->getName(true);

            if (strpos($testName, '::') === false) {
                $testName = get_class($test) . '::' . $testName;
            }

            return $testName;
        }

        return $test->getName();
    }

    public function __construct(?TestResultCache $cache = null)
    {
        $this->cache = $cache ?? new NullTestResultCache;
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws Exception
     */
    public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDependencies, int $orderDefects, bool $isRootTestSuite = true): void
    {
        $allowedOrders = [
            self::ORDER_DEFAULT,
            self::ORDER_REVERSED,
            self::ORDER_RANDOMIZED,
            self::ORDER_DURATION,
            self::ORDER_SIZE,
        ];

        if (!in_array($order, $allowedOrders, true)) {
            throw new Exception(
                '$order must be one of TestSuiteSorter::ORDER_[DEFAULT|REVERSED|RANDOMIZED|DURATION|SIZE]'
            );
        }

        $allowedOrderDefects = [
            self::ORDER_DEFAULT,
            self::ORDER_DEFECTS_FIRST,
        ];

        if (!in_array($orderDefects, $allowedOrderDefects, true)) {
            throw new Exception(
                '$orderDefects must be one of TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_DEFECTS_FIRST'
            );
        }

        if ($isRootTestSuite) {
            $this->originalExecutionOrder = $this->calculateTestExecutionOrder($suite);
        }

        if ($suite instanceof TestSuite) {
            foreach ($suite as $_suite) {
                $this->reorderTestsInSuite($_suite, $order, $resolveDependencies, $orderDefects, false);
            }

            if ($orderDefects === self::ORDER_DEFECTS_FIRST) {
                $this->addSuiteToDefectSortOrder($suite);
            }

            $this->sort($suite, $order, $resolveDependencies, $orderDefects);
        }

        if ($isRootTestSuite) {
            $this->executionOrder = $this->calculateTestExecutionOrder($suite);
        }
    }

    public function getOriginalExecutionOrder(): array
    {
        return $this->originalExecutionOrder;
    }

    public function getExecutionOrder(): array
    {
        return $this->executionOrder;
    }

    private function sort(TestSuite $suite, int $order, bool $resolveDependencies, int $orderDefects): void
    {
        if (empty($suite->tests())) {
            return;
        }

        if ($order === self::ORDER_REVERSED) {
            $suite->setTests($this->reverse($suite->tests()));
        } elseif ($order === self::ORDER_RANDOMIZED) {
            $suite->setTests($this->randomize($suite->tests()));
        } elseif ($order === self::ORDER_DURATION && $this->cache !== null) {
            $suite->setTests($this->sortByDuration($suite->tests()));
        } elseif ($order === self::ORDER_SIZE) {
            $suite->setTests($this->sortBySize($suite->tests()));
        }

        if ($orderDefects === self::ORDER_DEFECTS_FIRST && $this->cache !== null) {
            $suite->setTests($this->sortDefectsFirst($suite->tests()));
        }

        if ($resolveDependencies && !($suite instanceof DataProviderTestSuite) && $this->suiteOnlyContainsTests($suite)) {
            /** @var TestCase[] $tests */
            $tests = $suite->tests();

            $suite->setTests($this->resolveDependencies($tests));
        }
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function addSuiteToDefectSortOrder(TestSuite $suite): void
    {
        $max = 0;

        foreach ($suite->tests() as $test) {
            $testname = self::getTestSorterUID($test);

            if (!isset($this->defectSortOrder[$testname])) {
                $this->defectSortOrder[$testname] = self::DEFECT_SORT_WEIGHT[$this->cache->getState($testname)];
                $max                              = max($max, $this->defectSortOrder[$testname]);
            }
        }

        $this->defectSortOrder[$suite->getName()] = $max;
    }

    private function suiteOnlyContainsTests(TestSuite $suite): bool
    {
        return array_reduce(
            $suite->tests(),
            static function ($carry, $test)
            {
                return $carry && ($test instanceof TestCase || $test instanceof DataProviderTestSuite);
            },
            true
        );
    }

    private function reverse(array $tests): array
    {
        return array_reverse($tests);
    }

    private function randomize(array $tests): array
    {
        shuffle($tests);

        return $tests;
    }

    private function sortDefectsFirst(array $tests): array
    {
        usort(
            $tests,
            /**
             * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
             */
            function ($left, $right)
            {
                return $this->cmpDefectPriorityAndTime($left, $right);
            }
        );

        return $tests;
    }

    private function sortByDuration(array $tests): array
    {
        usort(
            $tests,
            /**
             * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
             */
            function ($left, $right)
            {
                return $this->cmpDuration($left, $right);
            }
        );

        return $tests;
    }

    private function sortBySize(array $tests): array
    {
        usort(
            $tests,
            /**
             * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
             */
            function ($left, $right)
            {
                return $this->cmpSize($left, $right);
            }
        );

        return $tests;
    }

    /**
     * Comparator callback function to sort tests for "reach failure as fast as possible":
     * 1. sort tests by defect weight defined in self::DEFECT_SORT_WEIGHT
     * 2. when tests are equally defective, sort the fastest to the front
     * 3. do not reorder successful tests.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function cmpDefectPriorityAndTime(Test $a, Test $b): int
    {
        $priorityA = $this->defectSortOrder[self::getTestSorterUID($a)] ?? 0;
        $priorityB = $this->defectSortOrder[self::getTestSorterUID($b)] ?? 0;

        if ($priorityB <=> $priorityA) {
            // Sort defect weight descending
            return $priorityB <=> $priorityA;
        }

        if ($priorityA || $priorityB) {
            return $this->cmpDuration($a, $b);
        }

        // do not change execution order
        return 0;
    }

    /**
     * Compares test duration for sorting tests by duration ascending.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function cmpDuration(Test $a, Test $b): int
    {
        return $this->cache->getTime(self::getTestSorterUID($a)) <=> $this->cache->getTime(self::getTestSorterUID($b));
    }

    /**
     * Compares test size for sorting tests small->medium->large->unknown.
     */
    private function cmpSize(Test $a, Test $b): int
    {
        $sizeA = ($a instanceof TestCase || $a instanceof DataProviderTestSuite)
            ? $a->getSize()
            : TestUtil::UNKNOWN;
        $sizeB = ($b instanceof TestCase || $b instanceof DataProviderTestSuite)
            ? $b->getSize()
            : TestUtil::UNKNOWN;

        return self::SIZE_SORT_WEIGHT[$sizeA] <=> self::SIZE_SORT_WEIGHT[$sizeB];
    }

    /**
     * Reorder Tests within a TestCase in such a way as to resolve as many dependencies as possible.
     * The algorithm will leave the tests in original running order when it can.
     * For more details see the documentation for test dependencies.
     *
     * Short description of algorithm:
     * 1. Pick the next Test from remaining tests to be checked for dependencies.
     * 2. If the test has no dependencies: mark done, start again from the top
     * 3. If the test has dependencies but none left to do: mark done, start again from the top
     * 4. When we reach the end add any leftover tests to the end. These will be marked 'skipped' during execution.
     *
     * @param array<DataProviderTestSuite|TestCase> $tests
     *
     * @return array<DataProviderTestSuite|TestCase>
     */
    private function resolveDependencies(array $tests): array
    {
        $newTestOrder = [];
        $i            = 0;

        do {
            $todoNames = array_map(
                /**
                 * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
                 */
                static function ($test)
                {
                    return self::getTestSorterUID($test);
                },
                $tests
            );

            if (!$tests[$i]->hasDependencies() || empty(array_intersect($this->getNormalizedDependencyNames($tests[$i]), $todoNames))) {
                $newTestOrder = array_merge($newTestOrder, array_splice($tests, $i, 1));
                $i            = 0;
            } else {
                $i++;
            }
        } while (!empty($tests) && ($i < count($tests)));

        return array_merge($newTestOrder, $tests);
    }

    /**
     * @param DataProviderTestSuite|TestCase $test
     *
     * @return array<string> A list of full test names as "TestSuiteClassName::testMethodName"
     */
    private function getNormalizedDependencyNames($test): array
    {
        if ($test instanceof DataProviderTestSuite) {
            $testClass = substr($test->getName(), 0, strpos($test->getName(), '::'));
        } else {
            $testClass = get_class($test);
        }

        return array_map(
            static function ($name) use ($testClass)
            {
                return strpos($name, '::') === false ? $testClass . '::' . $name : $name;
            },
            $test->getDependencies()
        );
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    private function calculateTestExecutionOrder(Test $suite): array
    {
        $tests = [];

        if ($suite instanceof TestSuite) {
            foreach ($suite->tests() as $test) {
                if (!($test instanceof TestSuite)) {
                    $tests[] = self::getTestSorterUID($test);
                } else {
                    $tests = array_merge($tests, $this->calculateTestExecutionOrder($test));
                }
            }
        }

        return $tests;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner\Filter;

use function sprintf;
use FilterIterator;
use InvalidArgumentException;
use Iterator;
use PHPUnit\Framework\TestSuite;
use RecursiveFilterIterator;
use ReflectionClass;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Factory
{
    /**
     * @var array
     */
    private $filters = [];

    /**
     * @throws InvalidArgumentException
     */
    public function addFilter(ReflectionClass $filter, $args): void
    {
        if (!$filter->isSubclassOf(RecursiveFilterIterator::class)) {
            throw new InvalidArgumentException(
                sprintf(
                    'Class "%s" does not extend RecursiveFilterIterator',
                    $filter->name
                )
            );
        }

        $this->filters[] = [$filter, $args];
    }

    public function factory(Iterator $iterator, TestSuite $suite): FilterIterator
    {
        foreach ($this->filters as $filter) {
            [$class, $args] = $filter;
            $iterator       = $class->newInstance($iterator, $args, $suite);
        }

        return $iterator;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner\Filter;

use function in_array;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class IncludeGroupFilterIterator extends GroupFilterIterator
{
    protected function doAccept(string $hash): bool
    {
        return in_array($hash, $this->groupTests, true);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner\Filter;

use function array_map;
use function array_merge;
use function in_array;
use function spl_object_hash;
use PHPUnit\Framework\TestSuite;
use RecursiveFilterIterator;
use RecursiveIterator;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
abstract class GroupFilterIterator extends RecursiveFilterIterator
{
    /**
     * @var string[]
     */
    protected $groupTests = [];

    public function __construct(RecursiveIterator $iterator, array $groups, TestSuite $suite)
    {
        parent::__construct($iterator);

        foreach ($suite->getGroupDetails() as $group => $tests) {
            if (in_array((string) $group, $groups, true)) {
                $testHashes = array_map(
                    'spl_object_hash',
                    $tests
                );

                $this->groupTests = array_merge($this->groupTests, $testHashes);
            }
        }
    }

    public function accept(): bool
    {
        $test = $this->getInnerIterator()->current();

        if ($test instanceof TestSuite) {
            return true;
        }

        return $this->doAccept(spl_object_hash($test));
    }

    abstract protected function doAccept(string $hash);
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner\Filter;

use function end;
use function implode;
use function preg_match;
use function sprintf;
use function str_replace;
use Exception;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\WarningTestCase;
use PHPUnit\Util\RegularExpression;
use RecursiveFilterIterator;
use RecursiveIterator;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class NameFilterIterator extends RecursiveFilterIterator
{
    /**
     * @var string
     */
    private $filter;

    /**
     * @var int
     */
    private $filterMin;

    /**
     * @var int
     */
    private $filterMax;

    /**
     * @throws Exception
     */
    public function __construct(RecursiveIterator $iterator, string $filter)
    {
        parent::__construct($iterator);

        $this->setFilter($filter);
    }

    /**
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function accept(): bool
    {
        $test = $this->getInnerIterator()->current();

        if ($test instanceof TestSuite) {
            return true;
        }

        $tmp = \PHPUnit\Util\Test::describe($test);

        if ($test instanceof WarningTestCase) {
            $name = $test->getMessage();
        } elseif ($tmp[0] !== '') {
            $name = implode('::', $tmp);
        } else {
            $name = $tmp[1];
        }

        $accepted = @preg_match($this->filter, $name, $matches);

        if ($accepted && isset($this->filterMax)) {
            $set      = end($matches);
            $accepted = $set >= $this->filterMin && $set <= $this->filterMax;
        }

        return (bool) $accepted;
    }

    /**
     * @throws Exception
     */
    private function setFilter(string $filter): void
    {
        if (RegularExpression::safeMatch($filter, '') === false) {
            // Handles:
            //  * testAssertEqualsSucceeds#4
            //  * testAssertEqualsSucceeds#4-8
            if (preg_match('/^(.*?)#(\d+)(?:-(\d+))?$/', $filter, $matches)) {
                if (isset($matches[3]) && $matches[2] < $matches[3]) {
                    $filter = sprintf(
                        '%s.*with data set #(\d+)$',
                        $matches[1]
                    );

                    $this->filterMin = (int) $matches[2];
                    $this->filterMax = (int) $matches[3];
                } else {
                    $filter = sprintf(
                        '%s.*with data set #%s$',
                        $matches[1],
                        $matches[2]
                    );
                }
            } // Handles:
            //  * testDetermineJsonError@JSON_ERROR_NONE
            //  * testDetermineJsonError@JSON.*
            elseif (preg_match('/^(.*?)@(.+)$/', $filter, $matches)) {
                $filter = sprintf(
                    '%s.*with data set "%s"$',
                    $matches[1],
                    $matches[2]
                );
            }

            // Escape delimiters in regular expression. Do NOT use preg_quote,
            // to keep magic characters.
            $filter = sprintf(
                '/%s/i',
                str_replace(
                    '/',
                    '\\/',
                    $filter
                )
            );
        }

        $this->filter = $filter;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner\Filter;

use function in_array;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ExcludeGroupFilterIterator extends GroupFilterIterator
{
    protected function doAccept(string $hash): bool
    {
        return !in_array($hash, $this->groupTests, true);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class NullTestResultCache implements TestResultCache
{
    public function setState(string $testName, int $state): void
    {
    }

    public function getState(string $testName): int
    {
        return BaseTestRunner::STATUS_UNKNOWN;
    }

    public function setTime(string $testName, float $time): void
    {
    }

    public function getTime(string $testName): float
    {
        return 0;
    }

    public function load(): void
    {
    }

    public function persist(): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use RuntimeException;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class Exception extends RuntimeException implements \PHPUnit\Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterRiskyTestHook extends TestHook
{
    public function executeAfterRiskyTest(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterSkippedTestHook extends TestHook
{
    public function executeAfterSkippedTest(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterTestErrorHook extends TestHook
{
    public function executeAfterTestError(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface Hook
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface BeforeTestHook extends TestHook
{
    public function executeBeforeTest(string $test): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Test as TestUtil;
use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class TestListenerAdapter implements TestListener
{
    /**
     * @var TestHook[]
     */
    private $hooks = [];

    /**
     * @var bool
     */
    private $lastTestWasNotSuccessful;

    public function add(TestHook $hook): void
    {
        $this->hooks[] = $hook;
    }

    public function startTest(Test $test): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof BeforeTestHook) {
                $hook->executeBeforeTest(TestUtil::describeAsString($test));
            }
        }

        $this->lastTestWasNotSuccessful = false;
    }

    public function addError(Test $test, Throwable $t, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterTestErrorHook) {
                $hook->executeAfterTestError(TestUtil::describeAsString($test), $t->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function addWarning(Test $test, Warning $e, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterTestWarningHook) {
                $hook->executeAfterTestWarning(TestUtil::describeAsString($test), $e->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterTestFailureHook) {
                $hook->executeAfterTestFailure(TestUtil::describeAsString($test), $e->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function addIncompleteTest(Test $test, Throwable $t, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterIncompleteTestHook) {
                $hook->executeAfterIncompleteTest(TestUtil::describeAsString($test), $t->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function addRiskyTest(Test $test, Throwable $t, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterRiskyTestHook) {
                $hook->executeAfterRiskyTest(TestUtil::describeAsString($test), $t->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function addSkippedTest(Test $test, Throwable $t, float $time): void
    {
        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterSkippedTestHook) {
                $hook->executeAfterSkippedTest(TestUtil::describeAsString($test), $t->getMessage(), $time);
            }
        }

        $this->lastTestWasNotSuccessful = true;
    }

    public function endTest(Test $test, float $time): void
    {
        if (!$this->lastTestWasNotSuccessful) {
            foreach ($this->hooks as $hook) {
                if ($hook instanceof AfterSuccessfulTestHook) {
                    $hook->executeAfterSuccessfulTest(TestUtil::describeAsString($test), $time);
                }
            }
        }

        foreach ($this->hooks as $hook) {
            if ($hook instanceof AfterTestHook) {
                $hook->executeAfterTest(TestUtil::describeAsString($test), $time);
            }
        }
    }

    public function startTestSuite(TestSuite $suite): void
    {
    }

    public function endTestSuite(TestSuite $suite): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterTestWarningHook extends TestHook
{
    public function executeAfterTestWarning(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface TestHook extends Hook
{
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterTestHook extends TestHook
{
    /**
     * This hook will fire after any test, regardless of the result.
     *
     * For more fine grained control, have a look at the other hooks
     * that extend PHPUnit\Runner\Hook.
     */
    public function executeAfterTest(string $test, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterLastTestHook extends Hook
{
    public function executeAfterLastTest(): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterTestFailureHook extends TestHook
{
    public function executeAfterTestFailure(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface BeforeFirstTestHook extends Hook
{
    public function executeBeforeFirstTest(): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterIncompleteTestHook extends TestHook
{
    public function executeAfterIncompleteTest(string $test, string $message, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

/**
 * This interface, as well as the associated mechanism for extending PHPUnit,
 * will be removed in PHPUnit 10. There is no alternative available in this
 * version of PHPUnit.
 *
 * @see https://github.com/sebastianbergmann/phpunit/issues/4676
 */
interface AfterSuccessfulTestHook extends TestHook
{
    public function executeAfterSuccessfulTest(string $test, float $time): void;
}
<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit;

use Throwable;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
interface Exception extends Throwable
{
}
Text_Template

Copyright (c) 2009-2015, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Text_Template

## Installation

## Installation

To add this package as a local, per-project dependency to your project, simply add a dependency on `phpunit/php-text-template` to your project's `composer.json` file. Here is a minimal example of a `composer.json` file that just defines a dependency on Text_Template:

    {
        "require": {
            "phpunit/php-text-template": "~1.2"
        }
    }

/composer.lock
/composer.phar
/.idea
/vendor

*.php diff=php
{
    "name": "phpunit/php-text-template",
    "description": "Simple template engine.",
    "type": "library",
    "keywords": [
        "template"
    ],
    "homepage": "https://github.com/sebastianbergmann/php-text-template/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/php-text-template/issues"
    },
    "require": {
        "php": ">=5.3.3"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    }
}

<?php
/*
 * This file is part of the Text_Template package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * A simple template engine.
 *
 * @since Class available since Release 1.0.0
 */
class Text_Template
{
    /**
     * @var string
     */
    protected $template = '';

    /**
     * @var string
     */
    protected $openDelimiter = '{';

    /**
     * @var string
     */
    protected $closeDelimiter = '}';

    /**
     * @var array
     */
    protected $values = array();

    /**
     * Constructor.
     *
     * @param  string                   $file
     * @throws InvalidArgumentException
     */
    public function __construct($file = '', $openDelimiter = '{', $closeDelimiter = '}')
    {
        $this->setFile($file);
        $this->openDelimiter  = $openDelimiter;
        $this->closeDelimiter = $closeDelimiter;
    }

    /**
     * Sets the template file.
     *
     * @param  string                   $file
     * @throws InvalidArgumentException
     */
    public function setFile($file)
    {
        $distFile = $file . '.dist';

        if (file_exists($file)) {
            $this->template = file_get_contents($file);
        }

        else if (file_exists($distFile)) {
            $this->template = file_get_contents($distFile);
        }

        else {
            throw new InvalidArgumentException(
              'Template file could not be loaded.'
            );
        }
    }

    /**
     * Sets one or more template variables.
     *
     * @param array $values
     * @param bool  $merge
     */
    public function setVar(array $values, $merge = TRUE)
    {
        if (!$merge || empty($this->values)) {
            $this->values = $values;
        } else {
            $this->values = array_merge($this->values, $values);
        }
    }

    /**
     * Renders the template and returns the result.
     *
     * @return string
     */
    public function render()
    {
        $keys = array();

        foreach ($this->values as $key => $value) {
            $keys[] = $this->openDelimiter . $key . $this->closeDelimiter;
        }

        return str_replace($keys, $this->values, $this->template);
    }

    /**
     * Renders the template and writes the result to a file.
     *
     * @param string $target
     */
    public function renderTo($target)
    {
        $fp = @fopen($target, 'wt');

        if ($fp) {
            fwrite($fp, $this->render());
            fclose($fp);
        } else {
            $error = error_get_last();

            throw new RuntimeException(
              sprintf(
                'Could not write to %s: %s',
                $target,
                substr(
                  $error['message'],
                  strpos($error['message'], ':') + 2
                )
              )
            );
        }
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
         bootstrap="tests/bootstrap.php"
         backupGlobals="false"
         verbose="true">
    <testsuite name="default">
        <directory suffix="Test.php">tests/tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>

    <php>
        <ini name="serialize_precision" value="14"/>
    </php>
</phpunit>

php-code-coverage

Copyright (c) 2009-2019, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [7.0.15] - 2021-07-26

### Changed

* Bumped required version of php-token-stream

## [7.0.14] - 2020-12-02

### Changed

* [#837](https://github.com/sebastianbergmann/php-code-coverage/issues/837): Allow version 4 of php-token-stream

## [7.0.13] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.2` to `>=7.2` to allow installation of this version of this library on PHP 8. However, this version of this library does not work on PHP 8. PHPUnit 8.5, which uses this version of this library, does not call into this library and instead shows a message that code coverage functionality is not available for PHPUnit 8.5 on PHP 8.

## [7.0.12] - 2020-11-27

### Added

* [#834](https://github.com/sebastianbergmann/php-code-coverage/issues/834): Support `XDEBUG_MODE` environment variable

## [7.0.11] - 2020-11-27

### Added

* Support for Xdebug 3

## [7.0.10] - 2019-11-20

### Fixed

* [#710](https://github.com/sebastianbergmann/php-code-coverage/pull/710): Code Coverage does not work in PhpStorm

## [7.0.9] - 2019-11-20

### Changed

* [#709](https://github.com/sebastianbergmann/php-code-coverage/pull/709): Prioritize PCOV over Xdebug

## [7.0.8] - 2019-09-17

### Changed

* Update HTML report Bootstrap 4.3.1, jQuery 3.4.1, and popper.js 1.15.0

## [7.0.7] - 2019-07-25

### Changed

* Bumped required version of php-token-stream

## [7.0.6] - 2019-07-08

### Changed

* Bumped required version of php-token-stream

## [7.0.5] - 2019-06-06

### Fixed

* [#681](https://github.com/sebastianbergmann/php-code-coverage/pull/681): `use function` statements are not ignored

## [7.0.4] - 2019-05-29

### Fixed

* [#682](https://github.com/sebastianbergmann/php-code-coverage/pull/682): Code that is not executed is reported as being executed when using PCOV

## [7.0.3] - 2019-02-26

### Fixed

* [#671](https://github.com/sebastianbergmann/php-code-coverage/issues/671): `TypeError` when directory name is a number

## [7.0.2] - 2019-02-15

### Changed

* Updated HTML report to Bootstrap 4.3.0

### Fixed

* [#667](https://github.com/sebastianbergmann/php-code-coverage/pull/667): `TypeError` in PHP reporter

## [7.0.1] - 2019-02-01

### Fixed

* [#664](https://github.com/sebastianbergmann/php-code-coverage/issues/664): `TypeError` when whitelisted file does not exist

## [7.0.0] - 2019-02-01

### Added

* Implemented [#663](https://github.com/sebastianbergmann/php-code-coverage/pull/663): Support for PCOV

### Fixed

* [#654](https://github.com/sebastianbergmann/php-code-coverage/issues/654): HTML report fails to load assets
* [#655](https://github.com/sebastianbergmann/php-code-coverage/issues/655): Popin pops in outside of screen

### Removed

* This component is no longer supported on PHP 7.1

## [6.1.4] - 2018-10-31

### Fixed

* [#650](https://github.com/sebastianbergmann/php-code-coverage/issues/650): Wasted screen space in HTML code coverage report

## [6.1.3] - 2018-10-23

### Changed

* Use `^3.1` of `sebastian/environment` again due to [regression](https://github.com/sebastianbergmann/environment/issues/31)

## [6.1.2] - 2018-10-23

### Fixed

* [#645](https://github.com/sebastianbergmann/php-code-coverage/pull/645): Crash that can occur when php-token-stream parses invalid files

## [6.1.1] - 2018-10-18

### Changed

* This component now allows `^4` of `sebastian/environment`

## [6.1.0] - 2018-10-16

### Changed

* Class names are now abbreviated (unqualified name shown, fully qualified name shown on hover) in the file view of the HTML report
* Update HTML report to Bootstrap 4

[7.0.15]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.14...7.0.15
[7.0.14]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.13...7.0.14
[7.0.13]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.12...7.0.13
[7.0.12]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.11...7.0.12
[7.0.11]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.10...7.0.11
[7.0.10]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.9...7.0.10
[7.0.9]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.8...7.0.9
[7.0.8]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.7...7.0.8
[7.0.7]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.6...7.0.7
[7.0.6]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.5...7.0.6
[7.0.5]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.4...7.0.5
[7.0.4]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.3...7.0.4
[7.0.3]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.2...7.0.3
[7.0.2]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.1...7.0.2
[7.0.1]: https://github.com/sebastianbergmann/php-code-coverage/compare/7.0.0...7.0.1
[7.0.0]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.1.4...7.0.0
[6.1.4]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.1.3...6.1.4
[6.1.3]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.1.2...6.1.3
[6.1.2]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.1.1...6.1.2
[6.1.1]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.1.0...6.1.1
[6.1.0]: https://github.com/sebastianbergmann/php-code-coverage/compare/6.0...6.1.0

<?xml version="1.0" encoding="UTF-8"?>
<project name="php-code-coverage" default="setup">
    <target name="setup" depends="clean,install-dependencies"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="install-dependencies" depends="clean" description="Install dependencies with Composer">
        <exec executable="${basedir}/tools/composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>

    <target name="update-tools">
        <exec executable="phive">
            <arg value="--no-progress"/>
            <arg value="update"/>
        </exec>

        <exec executable="${basedir}/tools/composer">
            <arg value="self-update"/>
        </exec>
    </target>
</project>
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;

class FilterTest extends TestCase
{
    /**
     * @var Filter
     */
    private $filter;

    /**
     * @var array
     */
    private $files = [];

    protected function setUp(): void
    {
        $this->filter = \unserialize('O:37:"SebastianBergmann\CodeCoverage\Filter":0:{}');

        $this->files = [
            TEST_FILES_PATH . 'BankAccount.php',
            TEST_FILES_PATH . 'BankAccountTest.php',
            TEST_FILES_PATH . 'CoverageClassExtendedTest.php',
            TEST_FILES_PATH . 'CoverageClassTest.php',
            TEST_FILES_PATH . 'CoverageFunctionParenthesesTest.php',
            TEST_FILES_PATH . 'CoverageFunctionParenthesesWhitespaceTest.php',
            TEST_FILES_PATH . 'CoverageFunctionTest.php',
            TEST_FILES_PATH . 'CoverageMethodOneLineAnnotationTest.php',
            TEST_FILES_PATH . 'CoverageMethodParenthesesTest.php',
            TEST_FILES_PATH . 'CoverageMethodParenthesesWhitespaceTest.php',
            TEST_FILES_PATH . 'CoverageMethodTest.php',
            TEST_FILES_PATH . 'CoverageNoneTest.php',
            TEST_FILES_PATH . 'CoverageNotPrivateTest.php',
            TEST_FILES_PATH . 'CoverageNotProtectedTest.php',
            TEST_FILES_PATH . 'CoverageNotPublicTest.php',
            TEST_FILES_PATH . 'CoverageNothingTest.php',
            TEST_FILES_PATH . 'CoveragePrivateTest.php',
            TEST_FILES_PATH . 'CoverageProtectedTest.php',
            TEST_FILES_PATH . 'CoveragePublicTest.php',
            TEST_FILES_PATH . 'CoverageTwoDefaultClassAnnotations.php',
            TEST_FILES_PATH . 'CoveredClass.php',
            TEST_FILES_PATH . 'CoveredFunction.php',
            TEST_FILES_PATH . 'Crash.php',
            TEST_FILES_PATH . 'NamespaceCoverageClassExtendedTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageClassTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageCoversClassPublicTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageCoversClassTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageMethodTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageNotPrivateTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageNotProtectedTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageNotPublicTest.php',
            TEST_FILES_PATH . 'NamespaceCoveragePrivateTest.php',
            TEST_FILES_PATH . 'NamespaceCoverageProtectedTest.php',
            TEST_FILES_PATH . 'NamespaceCoveragePublicTest.php',
            TEST_FILES_PATH . 'NamespaceCoveredClass.php',
            TEST_FILES_PATH . 'NotExistingCoveredElementTest.php',
            TEST_FILES_PATH . 'source_with_class_and_anonymous_function.php',
            TEST_FILES_PATH . 'source_with_ignore.php',
            TEST_FILES_PATH . 'source_with_namespace.php',
            TEST_FILES_PATH . 'source_with_oneline_annotations.php',
            TEST_FILES_PATH . 'source_with_use_statements.php',
            TEST_FILES_PATH . 'source_without_ignore.php',
            TEST_FILES_PATH . 'source_without_namespace.php',
        ];
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::addFileToWhitelist
     * @covers SebastianBergmann\CodeCoverage\Filter::getWhitelist
     */
    public function testAddingAFileToTheWhitelistWorks(): void
    {
        $this->filter->addFileToWhitelist($this->files[0]);

        $this->assertEquals(
            [$this->files[0]],
            $this->filter->getWhitelist()
        );
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::removeFileFromWhitelist
     * @covers SebastianBergmann\CodeCoverage\Filter::getWhitelist
     */
    public function testRemovingAFileFromTheWhitelistWorks(): void
    {
        $this->filter->addFileToWhitelist($this->files[0]);
        $this->filter->removeFileFromWhitelist($this->files[0]);

        $this->assertEquals([], $this->filter->getWhitelist());
    }

    /**
     * @covers  SebastianBergmann\CodeCoverage\Filter::addDirectoryToWhitelist
     * @covers  SebastianBergmann\CodeCoverage\Filter::getWhitelist
     * @depends testAddingAFileToTheWhitelistWorks
     */
    public function testAddingADirectoryToTheWhitelistWorks(): void
    {
        $this->filter->addDirectoryToWhitelist(TEST_FILES_PATH);

        $whitelist = $this->filter->getWhitelist();
        \sort($whitelist);

        $this->assertEquals($this->files, $whitelist);
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::addFilesToWhitelist
     * @covers SebastianBergmann\CodeCoverage\Filter::getWhitelist
     */
    public function testAddingFilesToTheWhitelistWorks(): void
    {
        $facade = new FileIteratorFacade;

        $files = $facade->getFilesAsArray(
            TEST_FILES_PATH,
            $suffixes = '.php'
        );

        $this->filter->addFilesToWhitelist($files);

        $whitelist = $this->filter->getWhitelist();
        \sort($whitelist);

        $this->assertEquals($this->files, $whitelist);
    }

    /**
     * @covers  SebastianBergmann\CodeCoverage\Filter::removeDirectoryFromWhitelist
     * @covers  SebastianBergmann\CodeCoverage\Filter::getWhitelist
     * @depends testAddingADirectoryToTheWhitelistWorks
     */
    public function testRemovingADirectoryFromTheWhitelistWorks(): void
    {
        $this->filter->addDirectoryToWhitelist(TEST_FILES_PATH);
        $this->filter->removeDirectoryFromWhitelist(TEST_FILES_PATH);

        $this->assertEquals([], $this->filter->getWhitelist());
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::isFile
     */
    public function testIsFile(): void
    {
        $this->assertFalse($this->filter->isFile('vfs://root/a/path'));
        $this->assertFalse($this->filter->isFile('xdebug://debug-eval'));
        $this->assertFalse($this->filter->isFile('eval()\'d code'));
        $this->assertFalse($this->filter->isFile('runtime-created function'));
        $this->assertFalse($this->filter->isFile('assert code'));
        $this->assertFalse($this->filter->isFile('regexp code'));
        $this->assertTrue($this->filter->isFile(__FILE__));
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::isFiltered
     */
    public function testWhitelistedFileIsNotFiltered(): void
    {
        $this->filter->addFileToWhitelist($this->files[0]);
        $this->assertFalse($this->filter->isFiltered($this->files[0]));
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::isFiltered
     */
    public function testNotWhitelistedFileIsFiltered(): void
    {
        $this->filter->addFileToWhitelist($this->files[0]);
        $this->assertTrue($this->filter->isFiltered($this->files[1]));
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::isFiltered
     * @covers SebastianBergmann\CodeCoverage\Filter::isFile
     */
    public function testNonFilesAreFiltered(): void
    {
        $this->assertTrue($this->filter->isFiltered('vfs://root/a/path'));
        $this->assertTrue($this->filter->isFiltered('xdebug://debug-eval'));
        $this->assertTrue($this->filter->isFiltered('eval()\'d code'));
        $this->assertTrue($this->filter->isFiltered('runtime-created function'));
        $this->assertTrue($this->filter->isFiltered('assert code'));
        $this->assertTrue($this->filter->isFiltered('regexp code'));
    }

    /**
     * @covers SebastianBergmann\CodeCoverage\Filter::addFileToWhitelist
     * @covers SebastianBergmann\CodeCoverage\Filter::getWhitelist
     *
     * @ticket https://github.com/sebastianbergmann/php-code-coverage/issues/664
     */
    public function testTryingToAddFileThatDoesNotExistDoesNotChangeFilter(): void
    {
        $filter = new Filter;

        $filter->addFileToWhitelist('does_not_exist');

        $this->assertEmpty($filter->getWhitelistedFiles());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\TestCase;

/**
 * @covers SebastianBergmann\CodeCoverage\Report\Text
 */
class TextTest extends TestCase
{
    public function testTextForBankAccountTest(): void
    {
        $text = new Text(50, 90, false, false);

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'BankAccount-text.txt',
            \str_replace(\PHP_EOL, "\n", $text->process($this->getCoverageForBankAccount()))
        );
    }

    public function testTextForFileWithIgnoredLines(): void
    {
        $text = new Text(50, 90, false, false);

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'ignored-lines-text.txt',
            \str_replace(\PHP_EOL, "\n", $text->process($this->getCoverageForFileWithIgnoredLines()))
        );
    }

    public function testTextForClassWithAnonymousFunction(): void
    {
        $text = new Text(50, 90, false, false);

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'class-with-anonymous-function-text.txt',
            \str_replace(\PHP_EOL, "\n", $text->process($this->getCoverageForClassWithAnonymousFunction()))
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\TestCase;

class HTMLTest extends TestCase
{
    private static $TEST_REPORT_PATH_SOURCE;

    public static function setUpBeforeClass(): void
    {
        parent::setUpBeforeClass();

        self::$TEST_REPORT_PATH_SOURCE = TEST_FILES_PATH . 'Report' . \DIRECTORY_SEPARATOR . 'HTML';
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        $tmpFilesIterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator(self::$TEST_TMP_PATH, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($tmpFilesIterator as $path => $fileInfo) {
            /* @var \SplFileInfo $fileInfo */
            $pathname = $fileInfo->getPathname();
            $fileInfo->isDir() ? \rmdir($pathname) : \unlink($pathname);
        }
    }

    public function testForBankAccountTest(): void
    {
        $expectedFilesPath = self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForBankAccount';

        $report = new Facade;
        $report->process($this->getCoverageForBankAccount(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    public function testForFileWithIgnoredLines(): void
    {
        $expectedFilesPath = self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForFileWithIgnoredLines';

        $report = new Facade;
        $report->process($this->getCoverageForFileWithIgnoredLines(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    public function testForClassWithAnonymousFunction(): void
    {
        $expectedFilesPath =
            self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForClassWithAnonymousFunction';

        $report = new Facade;
        $report->process($this->getCoverageForClassWithAnonymousFunction(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    /**
     * @param string $expectedFilesPath
     * @param string $actualFilesPath
     */
    private function assertFilesEquals($expectedFilesPath, $actualFilesPath): void
    {
        $expectedFilesIterator = new \FilesystemIterator($expectedFilesPath);
        $actualFilesIterator   = new \RegexIterator(new \FilesystemIterator($actualFilesPath), '/.html/');

        $this->assertEquals(
            \iterator_count($expectedFilesIterator),
            \iterator_count($actualFilesIterator),
            'Generated files and expected files not match'
        );

        foreach ($expectedFilesIterator as $path => $fileInfo) {
            /* @var \SplFileInfo $fileInfo */
            $filename = $fileInfo->getFilename();

            $actualFile = $actualFilesPath . \DIRECTORY_SEPARATOR . $filename;

            $this->assertFileExists($actualFile);

            $this->assertStringMatchesFormatFile(
                $fileInfo->getPathname(),
                \str_replace(\PHP_EOL, "\n", \file_get_contents($actualFile)),
                "${filename} not match"
            );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\CodeCoverage\Util
 */
class UtilTest extends TestCase
{
    public function testPercent(): void
    {
        $this->assertEquals(100, Util::percent(100, 0));
        $this->assertEquals(100, Util::percent(100, 100));
        $this->assertEquals(
            '100.00%',
            Util::percent(100, 100, true)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\TestCase;

/**
 * @covers SebastianBergmann\CodeCoverage\Report\Clover
 */
class CloverTest extends TestCase
{
    public function testCloverForBankAccountTest(): void
    {
        $clover = new Clover;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'BankAccount-clover.xml',
            $clover->process($this->getCoverageForBankAccount(), null, 'BankAccount')
        );
    }

    public function testCloverForFileWithIgnoredLines(): void
    {
        $clover = new Clover;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'ignored-lines-clover.xml',
            $clover->process($this->getCoverageForFileWithIgnoredLines())
        );
    }

    public function testCloverForClassWithAnonymousFunction(): void
    {
        $clover = new Clover;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'class-with-anonymous-function-clover.xml',
            $clover->process($this->getCoverageForClassWithAnonymousFunction())
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\Environment\Runtime;

/**
 * @covers SebastianBergmann\CodeCoverage\CodeCoverage
 */
class CodeCoverageTest extends TestCase
{
    /**
     * @var CodeCoverage
     */
    private $coverage;

    protected function setUp(): void
    {
        $runtime = new Runtime;

        if (!$runtime->canCollectCodeCoverage()) {
            $this->markTestSkipped('No code coverage driver available');
        }

        $this->coverage = new CodeCoverage;
    }

    public function testCannotStopWithInvalidSecondArgument(): void
    {
        $this->expectException(Exception::class);

        $this->coverage->stop(true, null);
    }

    public function testCannotAppendWithInvalidArgument(): void
    {
        $this->expectException(Exception::class);

        $this->coverage->append([], null);
    }

    public function testCollect(): void
    {
        $coverage = $this->getCoverageForBankAccount();

        $this->assertEquals(
            $this->getExpectedDataArrayForBankAccount(),
            $coverage->getData()
        );

        $this->assertEquals(
            [
                'BankAccountTest::testBalanceIsInitiallyZero'       => ['size' => 'unknown', 'status' => -1],
                'BankAccountTest::testBalanceCannotBecomeNegative'  => ['size' => 'unknown', 'status' => -1],
                'BankAccountTest::testBalanceCannotBecomeNegative2' => ['size' => 'unknown', 'status' => -1],
                'BankAccountTest::testDepositWithdrawMoney'         => ['size' => 'unknown', 'status' => -1],
            ],
            $coverage->getTests()
        );
    }

    public function testMerge(): void
    {
        $coverage = $this->getCoverageForBankAccountForFirstTwoTests();
        $coverage->merge($this->getCoverageForBankAccountForLastTwoTests());

        $this->assertEquals(
            $this->getExpectedDataArrayForBankAccount(),
            $coverage->getData()
        );
    }

    public function testMergeReverseOrder(): void
    {
        $coverage = $this->getCoverageForBankAccountForLastTwoTests();
        $coverage->merge($this->getCoverageForBankAccountForFirstTwoTests());

        $this->assertEquals(
            $this->getExpectedDataArrayForBankAccountInReverseOrder(),
            $coverage->getData()
        );
    }

    public function testMerge2(): void
    {
        $coverage = new CodeCoverage(
            $this->createMock(Driver::class),
            new Filter
        );

        $coverage->merge($this->getCoverageForBankAccount());

        $this->assertEquals(
            $this->getExpectedDataArrayForBankAccount(),
            $coverage->getData()
        );
    }

    public function testGetLinesToBeIgnored(): void
    {
        $this->assertEquals(
            [
                1,
                3,
                4,
                5,
                7,
                8,
                9,
                10,
                11,
                12,
                13,
                14,
                15,
                16,
                17,
                18,
                19,
                20,
                21,
                22,
                23,
                24,
                25,
                26,
                27,
                28,
                30,
                32,
                33,
                34,
                35,
                36,
                37,
                38,
            ],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_with_ignore.php'
            )
        );
    }

    public function testGetLinesToBeIgnored2(): void
    {
        $this->assertEquals(
            [1, 5],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_without_ignore.php'
            )
        );
    }

    public function testGetLinesToBeIgnored3(): void
    {
        $this->assertEquals(
            [
                1,
                2,
                3,
                4,
                5,
                8,
                11,
                15,
                16,
                19,
                20,
            ],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_with_class_and_anonymous_function.php'
            )
        );
    }

    public function testGetLinesToBeIgnoredOneLineAnnotations(): void
    {
        $this->assertEquals(
            [
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                11,
                14,
                15,
                16,
                18,
                20,
                21,
                23,
                24,
                25,
                27,
                28,
                29,
                30,
                31,
                32,
                33,
                34,
                37,
            ],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_with_oneline_annotations.php'
            )
        );
    }

    public function testGetLinesToBeIgnoredWhenIgnoreIsDisabled(): void
    {
        $this->coverage->setDisableIgnoredLines(true);

        $this->assertEquals(
            [
                7,
                11,
                12,
                13,
                16,
                17,
                18,
                19,
                20,
                21,
                22,
                23,
                26,
                27,
                32,
                33,
                34,
                35,
                36,
                37,
            ],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_with_ignore.php'
            )
        );
    }

    public function testUseStatementsAreIgnored(): void
    {
        $this->assertEquals(
            [
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                13,
                16,
                23,
                24,
            ],
            $this->getLinesToBeIgnored()->invoke(
                $this->coverage,
                TEST_FILES_PATH . 'source_with_use_statements.php'
            )
        );
    }

    public function testAppendThrowsExceptionIfCoveredCodeWasNotExecuted(): void
    {
        $this->coverage->filter()->addDirectoryToWhitelist(TEST_FILES_PATH);
        $this->coverage->setCheckForUnexecutedCoveredCode(true);

        $data = [
            TEST_FILES_PATH . 'BankAccount.php' => [
                29 => -1,
                31 => -1,
            ],
        ];

        $linesToBeCovered = [
            TEST_FILES_PATH . 'BankAccount.php' => [
                22,
                24,
            ],
        ];

        $linesToBeUsed = [];

        $this->expectException(CoveredCodeNotExecutedException::class);

        $this->coverage->append($data, 'File1.php', true, $linesToBeCovered, $linesToBeUsed);
    }

    public function testAppendThrowsExceptionIfUsedCodeWasNotExecuted(): void
    {
        $this->coverage->filter()->addDirectoryToWhitelist(TEST_FILES_PATH);
        $this->coverage->setCheckForUnexecutedCoveredCode(true);

        $data = [
            TEST_FILES_PATH . 'BankAccount.php' => [
                29 => -1,
                31 => -1,
            ],
        ];

        $linesToBeCovered = [
            TEST_FILES_PATH . 'BankAccount.php' => [
                29,
                31,
            ],
        ];

        $linesToBeUsed = [
            TEST_FILES_PATH . 'BankAccount.php' => [
                22,
                24,
            ],
        ];

        $this->expectException(CoveredCodeNotExecutedException::class);

        $this->coverage->append($data, 'File1.php', true, $linesToBeCovered, $linesToBeUsed);
    }

    /**
     * @return \ReflectionMethod
     */
    private function getLinesToBeIgnored()
    {
        $getLinesToBeIgnored = new \ReflectionMethod(
            'SebastianBergmann\CodeCoverage\CodeCoverage',
            'getLinesToBeIgnored'
        );

        $getLinesToBeIgnored->setAccessible(true);

        return $getLinesToBeIgnored;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\TestCase;

/**
 * @covers SebastianBergmann\CodeCoverage\Report\Crap4j
 */
class Crap4jTest extends TestCase
{
    public function testForBankAccountTest(): void
    {
        $crap4j = new Crap4j;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'BankAccount-crap4j.xml',
            $crap4j->process($this->getCoverageForBankAccount(), null, 'BankAccount')
        );
    }

    public function testForFileWithIgnoredLines(): void
    {
        $crap4j = new Crap4j;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'ignored-lines-crap4j.xml',
            $crap4j->process($this->getCoverageForFileWithIgnoredLines(), null, 'CoverageForFileWithIgnoredLines')
        );
    }

    public function testForClassWithAnonymousFunction(): void
    {
        $crap4j = new Crap4j;

        $this->assertStringMatchesFormatFile(
            TEST_FILES_PATH . 'class-with-anonymous-function-crap4j.xml',
            $crap4j->process($this->getCoverageForClassWithAnonymousFunction(), null, 'CoverageForClassWithAnonymousFunction')
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\tests\Exception;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\CodeCoverage\RuntimeException;
use SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException;

final class UnintentionallyCoveredCodeExceptionTest extends TestCase
{
    public function testCanConstructWithEmptyArray(): void
    {
        $unintentionallyCoveredUnits = [];

        $exception = new UnintentionallyCoveredCodeException($unintentionallyCoveredUnits);

        $this->assertInstanceOf(RuntimeException::class, $exception);
        $this->assertSame($unintentionallyCoveredUnits, $exception->getUnintentionallyCoveredUnits());
        $this->assertSame('', $exception->getMessage());
    }

    public function testCanConstructWithNonEmptyArray(): void
    {
        $unintentionallyCoveredUnits = [
            'foo',
            'bar',
            'baz',
        ];

        $exception = new UnintentionallyCoveredCodeException($unintentionallyCoveredUnits);

        $this->assertInstanceOf(RuntimeException::class, $exception);
        $this->assertSame($unintentionallyCoveredUnits, $exception->getUnintentionallyCoveredUnits());

        $expected = <<<TXT
- foo
- bar
- baz

TXT;

        $this->assertSame($expected, $exception->getMessage());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use SebastianBergmann\CodeCoverage\TestCase;

class XmlTest extends TestCase
{
    private static $TEST_REPORT_PATH_SOURCE;

    public static function setUpBeforeClass(): void
    {
        parent::setUpBeforeClass();

        self::$TEST_REPORT_PATH_SOURCE = TEST_FILES_PATH . 'Report' . \DIRECTORY_SEPARATOR . 'XML';
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        $tmpFilesIterator = new \FilesystemIterator(self::$TEST_TMP_PATH);

        foreach ($tmpFilesIterator as $path => $fileInfo) {
            /* @var \SplFileInfo $fileInfo */
            \unlink($fileInfo->getPathname());
        }
    }

    public function testForBankAccountTest(): void
    {
        $expectedFilesPath = self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForBankAccount';

        $xml = new Facade('1.0.0');
        $xml->process($this->getCoverageForBankAccount(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    public function testForFileWithIgnoredLines(): void
    {
        $expectedFilesPath = self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForFileWithIgnoredLines';

        $xml = new Facade('1.0.0');
        $xml->process($this->getCoverageForFileWithIgnoredLines(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    public function testForClassWithAnonymousFunction(): void
    {
        $expectedFilesPath = self::$TEST_REPORT_PATH_SOURCE . \DIRECTORY_SEPARATOR . 'CoverageForClassWithAnonymousFunction';

        $xml = new Facade('1.0.0');
        $xml->process($this->getCoverageForClassWithAnonymousFunction(), self::$TEST_TMP_PATH);

        $this->assertFilesEquals($expectedFilesPath, self::$TEST_TMP_PATH);
    }

    /**
     * @param string $expectedFilesPath
     * @param string $actualFilesPath
     */
    private function assertFilesEquals($expectedFilesPath, $actualFilesPath): void
    {
        $expectedFilesIterator = new \FilesystemIterator($expectedFilesPath);
        $actualFilesIterator   = new \FilesystemIterator($actualFilesPath);

        $this->assertEquals(
            \iterator_count($expectedFilesIterator),
            \iterator_count($actualFilesIterator),
            'Generated files and expected files not match'
        );

        foreach ($expectedFilesIterator as $path => $fileInfo) {
            /* @var \SplFileInfo $fileInfo */
            $filename = $fileInfo->getFilename();

            $actualFile = $actualFilesPath . \DIRECTORY_SEPARATOR . $filename;

            $this->assertFileExists($actualFile);

            $this->assertStringMatchesFormatFile(
                $fileInfo->getPathname(),
                \file_get_contents($actualFile),
                "${filename} not match"
            );
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\Node\Builder;
use SebastianBergmann\CodeCoverage\TestCase;

class BuilderTest extends TestCase
{
    protected $factory;

    protected function setUp(): void
    {
        $this->factory = new Builder;
    }

    public function testSomething(): void
    {
        $root = $this->getCoverageForBankAccount()->getReport();

        $expectedPath = \rtrim(TEST_FILES_PATH, \DIRECTORY_SEPARATOR);
        $this->assertEquals($expectedPath, $root->getName());
        $this->assertEquals($expectedPath, $root->getPath());
        $this->assertEquals(10, $root->getNumExecutableLines());
        $this->assertEquals(5, $root->getNumExecutedLines());
        $this->assertEquals(1, $root->getNumClasses());
        $this->assertEquals(0, $root->getNumTestedClasses());
        $this->assertEquals(4, $root->getNumMethods());
        $this->assertEquals(3, $root->getNumTestedMethods());
        $this->assertEquals('0.00%', $root->getTestedClassesPercent());
        $this->assertEquals('75.00%', $root->getTestedMethodsPercent());
        $this->assertEquals('50.00%', $root->getLineExecutedPercent());
        $this->assertEquals(0, $root->getNumFunctions());
        $this->assertEquals(0, $root->getNumTestedFunctions());
        $this->assertNull($root->getParent());
        $this->assertEquals([], $root->getDirectories());
        #$this->assertEquals(array(), $root->getFiles());
        #$this->assertEquals(array(), $root->getChildNodes());

        $this->assertEquals(
            [
                'BankAccount' => [
                    'methods' => [
                        'getBalance' => [
                            'signature'       => 'getBalance()',
                            'startLine'       => 6,
                            'endLine'         => 9,
                            'executableLines' => 1,
                            'executedLines'   => 1,
                            'ccn'             => 1,
                            'coverage'        => 100,
                            'crap'            => '1',
                            'link'            => 'BankAccount.php.html#6',
                            'methodName'      => 'getBalance',
                            'visibility'      => 'public',
                        ],
                        'setBalance' => [
                            'signature'       => 'setBalance($balance)',
                            'startLine'       => 11,
                            'endLine'         => 18,
                            'executableLines' => 5,
                            'executedLines'   => 0,
                            'ccn'             => 2,
                            'coverage'        => 0,
                            'crap'            => 6,
                            'link'            => 'BankAccount.php.html#11',
                            'methodName'      => 'setBalance',
                            'visibility'      => 'protected',
                        ],
                        'depositMoney' => [
                            'signature'       => 'depositMoney($balance)',
                            'startLine'       => 20,
                            'endLine'         => 25,
                            'executableLines' => 2,
                            'executedLines'   => 2,
                            'ccn'             => 1,
                            'coverage'        => 100,
                            'crap'            => '1',
                            'link'            => 'BankAccount.php.html#20',
                            'methodName'      => 'depositMoney',
                            'visibility'      => 'public',
                        ],
                        'withdrawMoney' => [
                            'signature'       => 'withdrawMoney($balance)',
                            'startLine'       => 27,
                            'endLine'         => 32,
                            'executableLines' => 2,
                            'executedLines'   => 2,
                            'ccn'             => 1,
                            'coverage'        => 100,
                            'crap'            => '1',
                            'link'            => 'BankAccount.php.html#27',
                            'methodName'      => 'withdrawMoney',
                            'visibility'      => 'public',
                        ],
                    ],
                    'startLine'       => 2,
                    'executableLines' => 10,
                    'executedLines'   => 5,
                    'ccn'             => 5,
                    'coverage'        => 50,
                    'crap'            => '8.12',
                    'package'         => [
                        'namespace'   => '',
                        'fullPackage' => '',
                        'category'    => '',
                        'package'     => '',
                        'subpackage'  => '',
                    ],
                    'link'      => 'BankAccount.php.html#2',
                    'className' => 'BankAccount',
                ],
            ],
            $root->getClasses()
        );

        $this->assertEquals([], $root->getFunctions());
    }

    public function testNotCrashParsing(): void
    {
        $coverage = $this->getCoverageForCrashParsing();
        $root     = $coverage->getReport();

        $expectedPath = \rtrim(TEST_FILES_PATH, \DIRECTORY_SEPARATOR);
        $this->assertEquals($expectedPath, $root->getName());
        $this->assertEquals($expectedPath, $root->getPath());
        $this->assertEquals(2, $root->getNumExecutableLines());
        $this->assertEquals(0, $root->getNumExecutedLines());
        $data         = $coverage->getData();
        $expectedFile = $expectedPath . \DIRECTORY_SEPARATOR . 'Crash.php';
        $this->assertSame([$expectedFile => [1 => [], 2 => []]], $data);
    }

    public function testBuildDirectoryStructure(): void
    {
        $s = \DIRECTORY_SEPARATOR;

        $method = new \ReflectionMethod(
            Builder::class,
            'buildDirectoryStructure'
        );

        $method->setAccessible(true);

        $this->assertEquals(
            [
                'src' => [
                    'Money.php/f'    => [],
                    'MoneyBag.php/f' => [],
                    'Foo'            => [
                        'Bar' => [
                            'Baz' => [
                                'Foo.php/f' => [],
                            ],
                        ],
                    ],
                ],
            ],
            $method->invoke(
                $this->factory,
                [
                    "src{$s}Money.php"                    => [],
                    "src{$s}MoneyBag.php"                 => [],
                    "src{$s}Foo{$s}Bar{$s}Baz{$s}Foo.php" => [],
                ]
            )
        );
    }

    /**
     * @dataProvider reducePathsProvider
     */
    public function testReducePaths($reducedPaths, $commonPath, $paths): void
    {
        $method = new \ReflectionMethod(
            Builder::class,
            'reducePaths'
        );

        $method->setAccessible(true);

        $_commonPath = $method->invokeArgs($this->factory, [&$paths]);

        $this->assertEquals($reducedPaths, $paths);
        $this->assertEquals($commonPath, $_commonPath);
    }

    public function reducePathsProvider()
    {
        $s = \DIRECTORY_SEPARATOR;

        yield [
            [],
            '.',
            [],
        ];

        $prefixes = ["C:$s", "$s"];

        foreach ($prefixes as $p) {
            yield [
                [
                    'Money.php' => [],
                ],
                "{$p}home{$s}sb{$s}Money{$s}",
                [
                    "{$p}home{$s}sb{$s}Money{$s}Money.php" => [],
                ],
            ];

            yield [
                [
                    'Money.php'    => [],
                    'MoneyBag.php' => [],
                ],
                "{$p}home{$s}sb{$s}Money",
                [
                    "{$p}home{$s}sb{$s}Money{$s}Money.php"    => [],
                    "{$p}home{$s}sb{$s}Money{$s}MoneyBag.php" => [],
                ],
            ];

            yield [
                [
                    'Money.php'             => [],
                    'MoneyBag.php'          => [],
                    "Cash.phar{$s}Cash.php" => [],
                ],
                "{$p}home{$s}sb{$s}Money",
                [
                    "{$p}home{$s}sb{$s}Money{$s}Money.php"                    => [],
                    "{$p}home{$s}sb{$s}Money{$s}MoneyBag.php"                 => [],
                    "phar://{$p}home{$s}sb{$s}Money{$s}Cash.phar{$s}Cash.php" => [],
                ],
            ];
        }
    }
}
<?php
require __DIR__ . '/../vendor/autoload.php';

define(
    'TEST_FILES_PATH',
    __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR
);
<?xml version="1.0" encoding="UTF-8"?>
<crap_result>
  <project>CoverageForClassWithAnonymousFunction</project>
  <timestamp>%s</timestamp>
  <stats>
    <name>Method Crap Stats</name>
    <methodCount>1</methodCount>
    <crapMethodCount>0</crapMethodCount>
    <crapLoad>0</crapLoad>
    <totalCrap>1</totalCrap>
    <crapMethodPercent>0</crapMethodPercent>
  </stats>
  <methods>
    <method>
      <package>global</package>
      <className>CoveredClassWithAnonymousFunctionInStaticMethod</className>
      <methodName>runAnonymous</methodName>
      <methodSignature>runAnonymous()</methodSignature>
      <fullMethod>runAnonymous()</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>87.5</coverage>
      <crapLoad>0</crapLoad>
    </method>
  </methods>
</crap_result>
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoveragePublicTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<public>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
namespace Foo;

class CoveredParentClass
{
    private function privateMethod()
    {
    }

    protected function protectedMethod()
    {
        $this->privateMethod();
    }

    public function publicMethod()
    {
        $this->protectedMethod();
    }
}

class CoveredClass extends CoveredParentClass
{
    private function privateMethod()
    {
    }

    protected function protectedMethod()
    {
        parent::protectedMethod();
        $this->privateMethod();
    }

    public function publicMethod()
    {
        parent::publicMethod();
        $this->protectedMethod();
    }
}
<?php
namespace bar\baz;

/**
 * Represents foo.
 */
class source_with_namespace
{
}

/**
 * @param mixed $bar
 */
function &foo($bar)
{
    $baz = function () {};
    $a   = true ? true : false;
    $b   = "{$a}";
    $c   = "${b}";
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageMethodParenthesesWhitespaceTest extends TestCase
{
    /**
     * @covers CoveredClass::publicMethod ( )
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageNoneTest extends TestCase
{
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
namespace SebastianBergmann\CodeCoverage\TestFixture;

use stdClass;
use function array_filter;
use const ARRAY_FILTER_USE_BOTH;

class C
{
    public function m(): void
    {
        $o = new stdClass;

        array_filter(
            ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4],
            static function ($v, $k)
            {
                return $k === 'b' || $v === 4;
            },
            ARRAY_FILTER_USE_BOTH
        );
    }
}
<?php
function globalFunction()
{
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageNotProtectedTest extends TestCase
{
    /**
     * @covers CoveredClass::<!protected>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \Foo\CoveredClass
 */
class NamespaceCoverageCoversClassTest extends TestCase
{
    /**
     * @covers ::privateMethod
     * @covers ::protectedMethod
     * @covers ::publicMethod
     * @covers \Foo\CoveredParentClass::privateMethod
     * @covers \Foo\CoveredParentClass::protectedMethod
     * @covers \Foo\CoveredParentClass::publicMethod
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}


Code Coverage Report:   
  %s
                        
 Summary:               
  Classes:  0.00% (0/1) 
  Methods: 75.00% (3/4) 
  Lines:   50.00% (5/10)

BankAccount
  Methods:  75.00% ( 3/ 4)   Lines:  50.00% (  5/ 10)
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageNotProtectedTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<!protected>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoveragePrivateTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<private>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}


Code Coverage Report:  
  %s
                       
 Summary:              
  Classes:  0.00% (0/1)
  Methods:  0.00% (0/1)
  Lines:   87.50% (7/8)

CoveredClassWithAnonymousFunctionInStaticMethod
  Methods:   0.00% ( 0/ 1)   Lines:  87.50% (  7/  8)
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageNotPrivateTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<!private>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php

/** Docblock */
interface FooInterface
{
    public function bar();
}

class Foo
{
    public function bar()
    {
    }
}

function baz()
{
    // a one-line comment
    print '*'; // a one-line comment

    /* a one-line comment */
    print '*'; /* a one-line comment */

    /* a one-line comment
     */
    print '*'; /* a one-line comment
    */

    print '*'; // @codeCoverageIgnore

    print '*'; // @codeCoverageIgnoreStart
    print '*';
    print '*'; // @codeCoverageIgnoreEnd

    print '*';
}
<?php
use PHPUnit\Framework\TestCase;

class CoveragePrivateTest extends TestCase
{
    /**
     * @covers CoveredClass::<private>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class NotExistingCoveredElementTest extends TestCase
{
    /**
     * @covers NotExistingClass
     */
    public function testOne()
    {
    }

    /**
     * @covers NotExistingClass::notExistingMethod
     */
    public function testTwo()
    {
    }

    /**
     * @covers NotExistingClass::<public>
     */
    public function testThree()
    {
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageFunctionParenthesesTest extends TestCase
{
    /**
     * @covers ::globalFunction()
     */
    public function testSomething()
    {
        globalFunction();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoveragePublicTest extends TestCase
{
    /**
     * @covers CoveredClass::<public>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}


Code Coverage Report:%w
  %s
%w
 Summary:%w
  Classes:        (0/0)
  Methods:        (0/0)
  Lines:   50.00% (1/2)

<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageClassExtendedTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass<extended>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageProtectedTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<protected>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<crap_result>
  <project>BankAccount</project>
  <timestamp>%s</timestamp>
  <stats>
    <name>Method Crap Stats</name>
    <methodCount>4</methodCount>
    <crapMethodCount>0</crapMethodCount>
    <crapLoad>0</crapLoad>
    <totalCrap>9</totalCrap>
    <crapMethodPercent>0</crapMethodPercent>
  </stats>
  <methods>
    <method>
      <package>global</package>
      <className>BankAccount</className>
      <methodName>getBalance</methodName>
      <methodSignature>getBalance()</methodSignature>
      <fullMethod>getBalance()</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>100</coverage>
      <crapLoad>0</crapLoad>
    </method>
    <method>
      <package>global</package>
      <className>BankAccount</className>
      <methodName>setBalance</methodName>
      <methodSignature>setBalance($balance)</methodSignature>
      <fullMethod>setBalance($balance)</fullMethod>
      <crap>6</crap>
      <complexity>2</complexity>
      <coverage>0</coverage>
      <crapLoad>0</crapLoad>
    </method>
    <method>
      <package>global</package>
      <className>BankAccount</className>
      <methodName>depositMoney</methodName>
      <methodSignature>depositMoney($balance)</methodSignature>
      <fullMethod>depositMoney($balance)</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>100</coverage>
      <crapLoad>0</crapLoad>
    </method>
    <method>
      <package>global</package>
      <className>BankAccount</className>
      <methodName>withdrawMoney</methodName>
      <methodSignature>withdrawMoney($balance)</methodSignature>
      <fullMethod>withdrawMoney($balance)</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>100</coverage>
      <crapLoad>0</crapLoad>
    </method>
  </methods>
</crap_result>
<?php
/**
 * @coversDefaultClass \NamespaceOne
 * @coversDefaultClass \AnotherDefault\Name\Space\Does\Not\Work
 */
class CoverageTwoDefaultClassAnnotations
{
    /**
     * @covers Foo\CoveredClass::<public>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="%i">
  <project timestamp="%i">
    <file name="%s%esource_with_ignore.php">
      <class name="Foo" namespace="global">
        <metrics complexity="1" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
      </class>
      <class name="Bar" namespace="global">
        <metrics complexity="1" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="0" coveredelements="0"/>
      </class>
      <line num="2" type="stmt" count="1"/>
      <line num="6" type="stmt" count="0"/>
      <metrics loc="37" ncloc="25" classes="0" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="2" coveredstatements="1" elements="2" coveredelements="1"/>
    </file>
    <metrics files="1" loc="37" ncloc="25" classes="0" methods="0" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="2" coveredstatements="1" elements="2" coveredelements="1"/>
  </project>
</coverage>
<?php
use PHPUnit\Framework\TestCase;

class CoverageProtectedTest extends TestCase
{
    /**
     * @covers CoveredClass::<protected>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageNotPrivateTest extends TestCase
{
    /**
     * @covers CoveredClass::<!private>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageNothingTest extends TestCase
{
    /**
     * @covers CoveredClass::publicMethod
     * @coversNothing
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageMethodTest extends TestCase
{
    /**
     * @covers CoveredClass::publicMethod
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageNotPublicTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::<!public>
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
/**
 * Represents foo.
 */
class Foo
{
}

/**
 * @param mixed $bar
 */
function &foo($bar)
{
    $baz = function () {};
    $a   = true ? true : false;
    $b   = "{$a}";
    $c   = "${b}";
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageNotPublicTest extends TestCase
{
    /**
     * @covers CoveredClass::<!public>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageMethodParenthesesTest extends TestCase
{
    /**
     * @covers CoveredClass::publicMethod()
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
class {CLASS}
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="%i">
  <project timestamp="%i" name="BankAccount">
    <file name="%s%eBankAccount.php">
      <class name="BankAccount" namespace="global">
        <metrics complexity="5" methods="4" coveredmethods="3" conditionals="0" coveredconditionals="0" statements="10" coveredstatements="5" elements="14" coveredelements="8"/>
      </class>
      <line num="6" type="method" name="getBalance" visibility="public" complexity="1" crap="1" count="2"/>
      <line num="8" type="stmt" count="2"/>
      <line num="11" type="method" name="setBalance" visibility="protected" complexity="2" crap="6" count="0"/>
      <line num="13" type="stmt" count="0"/>
      <line num="14" type="stmt" count="0"/>
      <line num="15" type="stmt" count="0"/>
      <line num="16" type="stmt" count="0"/>
      <line num="18" type="stmt" count="0"/>
      <line num="20" type="method" name="depositMoney" visibility="public" complexity="1" crap="1" count="2"/>
      <line num="22" type="stmt" count="2"/>
      <line num="24" type="stmt" count="1"/>
      <line num="27" type="method" name="withdrawMoney" visibility="public" complexity="1" crap="1" count="2"/>
      <line num="29" type="stmt" count="2"/>
      <line num="31" type="stmt" count="1"/>
      <metrics loc="33" ncloc="33" classes="1" methods="4" coveredmethods="3" conditionals="0" coveredconditionals="0" statements="10" coveredstatements="5" elements="14" coveredelements="8"/>
    </file>
    <metrics files="1" loc="33" ncloc="33" classes="1" methods="4" coveredmethods="3" conditionals="0" coveredconditionals="0" statements="10" coveredstatements="5" elements="14" coveredelements="8"/>
  </project>
</coverage>
<?php
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \Foo\CoveredClass
 */
class NamespaceCoverageCoversClassPublicTest extends TestCase
{
    /**
     * @covers ::publicMethod
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<crap_result>
  <project>CoverageForFileWithIgnoredLines</project>
  <timestamp>%s</timestamp>
  <stats>
    <name>Method Crap Stats</name>
    <methodCount>2</methodCount>
    <crapMethodCount>0</crapMethodCount>
    <crapLoad>0</crapLoad>
    <totalCrap>2</totalCrap>
    <crapMethodPercent>0</crapMethodPercent>
  </stats>
  <methods>
    <method>
      <package>global</package>
      <className>Foo</className>
      <methodName>bar</methodName>
      <methodSignature>bar()</methodSignature>
      <fullMethod>bar()</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>100</coverage>
      <crapLoad>0</crapLoad>
    </method>
    <method>
      <package>global</package>
      <className>Bar</className>
      <methodName>foo</methodName>
      <methodSignature>foo()</methodSignature>
      <fullMethod>foo()</fullMethod>
      <crap>1</crap>
      <complexity>1</complexity>
      <coverage>100</coverage>
      <crapLoad>0</crapLoad>
    </method>
  </methods>
</crap_result>
<?php
use PHPUnit\Framework\TestCase;

class CoverageClassTest extends TestCase
{
    /**
     * @covers CoveredClass
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageClassExtendedTest extends TestCase
{
    /**
     * @covers CoveredClass<extended>
     */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
if ($neverHappens) {
    print '*';
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageFunctionTest extends TestCase
{
    /**
     * @covers ::globalFunction
     */
    public function testSomething()
    {
        globalFunction();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="%i">
  <project timestamp="%i">
    <file name="%s%esource_with_class_and_anonymous_function.php">
      <class name="CoveredClassWithAnonymousFunctionInStaticMethod" namespace="global">
        <metrics complexity="1" methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="8" coveredstatements="7" elements="9" coveredelements="7"/>
      </class>
      <line num="5" type="method" name="runAnonymous" visibility="public" complexity="1" crap="1.00" count="1"/>
      <line num="7" type="stmt" count="1"/>
      <line num="9" type="stmt" count="1"/>
      <line num="10" type="stmt" count="0"/>
      <line num="12" type="stmt" count="1"/>
      <line num="13" type="stmt" count="1"/>
      <line num="14" type="stmt" count="1"/>
      <line num="17" type="stmt" count="1"/>
      <line num="18" type="stmt" count="1"/>
      <metrics loc="19" ncloc="17" classes="1" methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="8" coveredstatements="7" elements="9" coveredelements="7"/>
    </file>
    <metrics files="1" loc="19" ncloc="17" classes="1" methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="8" coveredstatements="7" elements="9" coveredelements="7"/>
  </project>
</coverage>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item active">%s</li>
         <li class="breadcrumb-item">(<a href="dashboard.html">Dashboard</a>)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
       <td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="danger">Total</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">1&nbsp;/&nbsp;2</div></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>

      <tr>
       <td class="danger"><img src="_icons/file-code.svg" class="octicon" /><a href="source_with_ignore.php.html">source_with_ignore.php</a></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">1&nbsp;/&nbsp;2</div></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="danger"><strong>Low</strong>: 0% to 50%</span>
     <span class="warning"><strong>Medium</strong>: 50% to 90%</span>
     <span class="success"><strong>High</strong>: 90% to 100%</span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Dashboard for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/nv.d3.min.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">(Dashboard)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="row">
    <div class="col-md-12">
     <h2>Classes</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="classCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="classComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-12">
     <h2>Methods</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="methodCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="methodComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <footer>
    <hr/>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/d3.min.js" type="text/javascript"></script>
  <script src="_js/nv.d3.min.js" type="text/javascript"></script>
  <script type="text/javascript">
$(document).ready(function() {
  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#classCoverageDistribution svg')
      .datum(getCoverageDistributionData([0,0,0,0,0,0,0,0,0,0,0,2], "Class Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#methodCoverageDistribution svg')
      .datum(getCoverageDistributionData([0,0,0,0,0,0,0,0,0,0,0,2], "Method Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getCoverageDistributionData(data, label) {
    var labels = [
      '0%',
      '0-10%',
      '10-20%',
      '20-30%',
      '30-40%',
      '40-50%',
      '50-60%',
      '60-70%',
      '70-80%',
      '80-90%',
      '90-100%',
      '100%'
    ];
    var values = [];
    $.each(labels, function(key) {
      values.push({x: labels[key], y: data[key]});
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Cyclomatic Complexity');

    d3.select('#classComplexity svg')
      .datum(getComplexityData([[100,1,"<a href=\"source_with_ignore.php.html#11\">Foo<\/a>"],[100,1,"<a href=\"source_with_ignore.php.html#18\">Bar<\/a>"]], 'Class Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Method Complexity');

    d3.select('#methodComplexity svg')
      .datum(getComplexityData([[100,1,"<a href=\"source_with_ignore.php.html#13\">Foo::bar<\/a>"],[100,1,"<a href=\"source_with_ignore.php.html#23\">Bar::foo<\/a>"]], 'Method Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getComplexityData(data, label) {
    var values = [];
    $.each(data, function(key) {
      var value = Math.round(data[key][0]*100) / 100;
      values.push({
        x: value,
        y: data[key][1],
        class: data[key][2],
        size: 0.05,
        shape: 'diamond'
      });
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
});
  </script>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s%esource_with_ignore.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">source_with_ignore.php</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
       <td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="">Total</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class="success small"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">1&nbsp;/&nbsp;2</div></td>
      </tr>

      <tr>
       <td class="" colspan="4"><a href="#28"><abbr title="baz()">baz</abbr></a></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" small">1</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>

      <tr>
       <td class="">Foo</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" small">1</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>

      <tr>
       <td class="" colspan="4">&nbsp;<a href="#13"><abbr title="bar()">bar</abbr></a></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" small">1</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>

      <tr>
       <td class="">Bar</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" small">1</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>

      <tr>
       <td class="" colspan="4">&nbsp;<a href="#23"><abbr title="foo()">foo</abbr></a></td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
       <td class=" small">1</td>
       <td class=" big"></td>
       <td class=" small"><div align="right">n/a</div></td>
       <td class=" small"><div align="right">0&nbsp;/&nbsp;0</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <table id="code" class="table table-borderless table-condensed">
    <tbody>
     <tr><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><span class="default">&lt;?php</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 2" data-content="&lt;ul&gt;&lt;li&gt;FileWithIgnoredLines&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"><span class="keyword">if</span><span class="default">&nbsp;</span><span class="keyword">(</span><span class="default">$neverHappens</span><span class="keyword">)</span><span class="default">&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="comment">//&nbsp;@codeCoverageIgnoreStart</span></td></tr>
     <tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">print</span><span class="default">&nbsp;</span><span class="default">'*'</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="comment">//&nbsp;@codeCoverageIgnoreEnd</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"><span class="comment">/**</span></td></tr>
     <tr><td><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"><span class="comment">&nbsp;*&nbsp;@codeCoverageIgnore</span></td></tr>
     <tr><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"><span class="comment">&nbsp;*/</span></td></tr>
     <tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"><span class="keyword">class</span><span class="default">&nbsp;</span><span class="default">Foo</span></td></tr>
     <tr><td><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">bar</span><span class="keyword">(</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="14"></a><a href="#14">14</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="15"></a><a href="#15">15</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="16"></a><a href="#16">16</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="17"></a><a href="#17">17</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="18"></a><a href="#18">18</a></div></td><td class="codeLine"><span class="keyword">class</span><span class="default">&nbsp;</span><span class="default">Bar</span></td></tr>
     <tr><td><div align="right"><a name="19"></a><a href="#19">19</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="20"></a><a href="#20">20</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="comment">/**</span></td></tr>
     <tr><td><div align="right"><a name="21"></a><a href="#21">21</a></div></td><td class="codeLine"><span class="comment">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;@codeCoverageIgnore</span></td></tr>
     <tr><td><div align="right"><a name="22"></a><a href="#22">22</a></div></td><td class="codeLine"><span class="comment">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*/</span></td></tr>
     <tr><td><div align="right"><a name="23"></a><a href="#23">23</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">foo</span><span class="keyword">(</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="24"></a><a href="#24">24</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="25"></a><a href="#25">25</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="26"></a><a href="#26">26</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="27"></a><a href="#27">27</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="28"></a><a href="#28">28</a></div></td><td class="codeLine"><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">baz</span><span class="keyword">(</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="29"></a><a href="#29">29</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="30"></a><a href="#30">30</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">print</span><span class="default">&nbsp;</span><span class="default">'*'</span><span class="keyword">;</span><span class="default">&nbsp;</span><span class="comment">//&nbsp;@codeCoverageIgnore</span></td></tr>
     <tr><td><div align="right"><a name="31"></a><a href="#31">31</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="32"></a><a href="#32">32</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="33"></a><a href="#33">33</a></div></td><td class="codeLine"><span class="keyword">interface</span><span class="default">&nbsp;</span><span class="default">Bor</span></td></tr>
     <tr><td><div align="right"><a name="34"></a><a href="#34">34</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="35"></a><a href="#35">35</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">foo</span><span class="keyword">(</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="36"></a><a href="#36">36</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="37"></a><a href="#37">37</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>

    </tbody>
   </table>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="success"><strong>Executed</strong></span>
     <span class="danger"><strong>Not Executed</strong></span>
     <span class="warning"><strong>Dead Code</strong></span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
    <a title="Back to the top" id="toplink" href="#">
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16"><path fill-rule="evenodd" d="M12 11L6 5l-6 6h12z"/></svg>
    </a>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/popper.min.js" type="text/javascript"></script>
  <script src="_js/bootstrap.min.js" type="text/javascript"></script>
  <script src="_js/file.js" type="text/javascript"></script>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item active">%s</li>
         <li class="breadcrumb-item">(<a href="dashboard.html">Dashboard</a>)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
       <td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="danger">Total</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">5&nbsp;/&nbsp;10</div></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="75.00" aria-valuemin="0" aria-valuemax="100" style="width: 75.00%">
           <span class="sr-only">75.00% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">75.00%</div></td>
       <td class="warning small"><div align="right">3&nbsp;/&nbsp;4</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
      </tr>

      <tr>
       <td class="danger"><img src="_icons/file-code.svg" class="octicon" /><a href="BankAccount.php.html">BankAccount.php</a></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">5&nbsp;/&nbsp;10</div></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="75.00" aria-valuemin="0" aria-valuemax="100" style="width: 75.00%">
           <span class="sr-only">75.00% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">75.00%</div></td>
       <td class="warning small"><div align="right">3&nbsp;/&nbsp;4</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="danger"><strong>Low</strong>: 0% to 50%</span>
     <span class="warning"><strong>Medium</strong>: 50% to 90%</span>
     <span class="success"><strong>High</strong>: 90% to 100%</span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Dashboard for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/nv.d3.min.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">(Dashboard)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="row">
    <div class="col-md-12">
     <h2>Classes</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="classCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="classComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="BankAccount.php.html#2">BankAccount</a></td><td class="text-right">50%</td></tr>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="BankAccount.php.html#2">BankAccount</a></td><td class="text-right">8</td></tr>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-12">
     <h2>Methods</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="methodCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="methodComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="BankAccount.php.html#11"><abbr title="BankAccount::setBalance">setBalance</abbr></a></td><td class="text-right">0%</td></tr>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="BankAccount.php.html#11"><abbr title="BankAccount::setBalance">setBalance</abbr></a></td><td class="text-right">6</td></tr>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <footer>
    <hr/>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/d3.min.js" type="text/javascript"></script>
  <script src="_js/nv.d3.min.js" type="text/javascript"></script>
  <script type="text/javascript">
$(document).ready(function() {
  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#classCoverageDistribution svg')
      .datum(getCoverageDistributionData([0,0,0,0,0,0,1,0,0,0,0,0], "Class Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#methodCoverageDistribution svg')
      .datum(getCoverageDistributionData([1,0,0,0,0,0,0,0,0,0,0,3], "Method Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getCoverageDistributionData(data, label) {
    var labels = [
      '0%',
      '0-10%',
      '10-20%',
      '20-30%',
      '30-40%',
      '40-50%',
      '50-60%',
      '60-70%',
      '70-80%',
      '80-90%',
      '90-100%',
      '100%'
    ];
    var values = [];
    $.each(labels, function(key) {
      values.push({x: labels[key], y: data[key]});
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Cyclomatic Complexity');

    d3.select('#classComplexity svg')
      .datum(getComplexityData([[50,5,"<a href=\"BankAccount.php.html#2\">BankAccount<\/a>"]], 'Class Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Method Complexity');

    d3.select('#methodComplexity svg')
      .datum(getComplexityData([[100,1,"<a href=\"BankAccount.php.html#6\">BankAccount::getBalance<\/a>"],[0,2,"<a href=\"BankAccount.php.html#11\">BankAccount::setBalance<\/a>"],[100,1,"<a href=\"BankAccount.php.html#20\">BankAccount::depositMoney<\/a>"],[100,1,"<a href=\"BankAccount.php.html#27\">BankAccount::withdrawMoney<\/a>"]], 'Method Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getComplexityData(data, label) {
    var values = [];
    $.each(data, function(key) {
      var value = Math.round(data[key][0]*100) / 100;
      values.push({
        x: value,
        y: data[key][1],
        class: data[key][2],
        size: 0.05,
        shape: 'diamond'
      });
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
});
  </script>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s%eBankAccount.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">BankAccount.php</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
       <td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="danger">Total</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="75.00" aria-valuemin="0" aria-valuemax="100" style="width: 75.00%">
           <span class="sr-only">75.00% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">75.00%</div></td>
       <td class="warning small"><div align="right">3&nbsp;/&nbsp;4</div></td>
       <td class="warning small"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">5&nbsp;/&nbsp;10</div></td>
      </tr>

      <tr>
       <td class="danger">BankAccount</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="75.00" aria-valuemin="0" aria-valuemax="100" style="width: 75.00%">
           <span class="sr-only">75.00% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">75.00%</div></td>
       <td class="warning small"><div align="right">3&nbsp;/&nbsp;4</div></td>
       <td class="warning small">8.12</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="50.00" aria-valuemin="0" aria-valuemax="100" style="width: 50.00%">
           <span class="sr-only">50.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">50.00%</div></td>
       <td class="danger small"><div align="right">5&nbsp;/&nbsp;10</div></td>
      </tr>

      <tr>
       <td class="success" colspan="4">&nbsp;<a href="#6"><abbr title="getBalance()">getBalance</abbr></a></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class="success small">1</td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
      </tr>

      <tr>
       <td class="danger" colspan="4">&nbsp;<a href="#11"><abbr title="setBalance($balance)">setBalance</abbr></a></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger small">6</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;5</div></td>
      </tr>

      <tr>
       <td class="success" colspan="4">&nbsp;<a href="#20"><abbr title="depositMoney($balance)">depositMoney</abbr></a></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class="success small">1</td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">2&nbsp;/&nbsp;2</div></td>
      </tr>

      <tr>
       <td class="success" colspan="4">&nbsp;<a href="#27"><abbr title="withdrawMoney($balance)">withdrawMoney</abbr></a></td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">1&nbsp;/&nbsp;1</div></td>
       <td class="success small">1</td>
       <td class="success big">       <div class="progress">
         <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%">
           <span class="sr-only">100.00% covered (success)</span>
         </div>
       </div>
</td>
       <td class="success small"><div align="right">100.00%</div></td>
       <td class="success small"><div align="right">2&nbsp;/&nbsp;2</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <table id="code" class="table table-borderless table-condensed">
    <tbody>
     <tr><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><span class="default">&lt;?php</span></td></tr>
     <tr><td><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"><span class="keyword">class</span><span class="default">&nbsp;</span><span class="default">BankAccount</span></td></tr>
     <tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">protected</span><span class="default">&nbsp;</span><span class="default">$balance</span><span class="default">&nbsp;</span><span class="keyword">=</span><span class="default">&nbsp;</span><span class="default">0</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">getBalance</span><span class="keyword">(</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="2 tests cover line 8" data-content="&lt;ul&gt;&lt;li&gt;BankAccountTest::testBalanceIsInitiallyZero&lt;/li&gt;&lt;li&gt;BankAccountTest::testDepositWithdrawMoney&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">return</span><span class="default">&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">balance</span><span class="keyword">;</span></td></tr>
     <tr class="warning"><td><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">protected</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">setBalance</span><span class="keyword">(</span><span class="default">$balance</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">if</span><span class="default">&nbsp;</span><span class="keyword">(</span><span class="default">$balance</span><span class="default">&nbsp;</span><span class="default">&gt;=</span><span class="default">&nbsp;</span><span class="default">0</span><span class="keyword">)</span><span class="default">&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="14"></a><a href="#14">14</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">balance</span><span class="default">&nbsp;</span><span class="keyword">=</span><span class="default">&nbsp;</span><span class="default">$balance</span><span class="keyword">;</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="15"></a><a href="#15">15</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span><span class="default">&nbsp;</span><span class="keyword">else</span><span class="default">&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="16"></a><a href="#16">16</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">throw</span><span class="default">&nbsp;</span><span class="keyword">new</span><span class="default">&nbsp;</span><span class="default">RuntimeException</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="17"></a><a href="#17">17</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="18"></a><a href="#18">18</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="19"></a><a href="#19">19</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="20"></a><a href="#20">20</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">depositMoney</span><span class="keyword">(</span><span class="default">$balance</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="21"></a><a href="#21">21</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="2 tests cover line 22" data-content="&lt;ul&gt;&lt;li&gt;BankAccountTest::testBalanceCannotBecomeNegative2&lt;/li&gt;&lt;li&gt;BankAccountTest::testDepositWithdrawMoney&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="22"></a><a href="#22">22</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">setBalance</span><span class="keyword">(</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">getBalance</span><span class="keyword">(</span><span class="keyword">)</span><span class="default">&nbsp;</span><span class="keyword">+</span><span class="default">&nbsp;</span><span class="default">$balance</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="23"></a><a href="#23">23</a></div></td><td class="codeLine"></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 24" data-content="&lt;ul&gt;&lt;li&gt;BankAccountTest::testDepositWithdrawMoney&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="24"></a><a href="#24">24</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">return</span><span class="default">&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">getBalance</span><span class="keyword">(</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr class="warning"><td><div align="right"><a name="25"></a><a href="#25">25</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="26"></a><a href="#26">26</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="27"></a><a href="#27">27</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">withdrawMoney</span><span class="keyword">(</span><span class="default">$balance</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="28"></a><a href="#28">28</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="2 tests cover line 29" data-content="&lt;ul&gt;&lt;li&gt;BankAccountTest::testBalanceCannotBecomeNegative&lt;/li&gt;&lt;li&gt;BankAccountTest::testDepositWithdrawMoney&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="29"></a><a href="#29">29</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">setBalance</span><span class="keyword">(</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">getBalance</span><span class="keyword">(</span><span class="keyword">)</span><span class="default">&nbsp;</span><span class="keyword">-</span><span class="default">&nbsp;</span><span class="default">$balance</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="30"></a><a href="#30">30</a></div></td><td class="codeLine"></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 31" data-content="&lt;ul&gt;&lt;li&gt;BankAccountTest::testDepositWithdrawMoney&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="31"></a><a href="#31">31</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">return</span><span class="default">&nbsp;</span><span class="default">$this</span><span class="default">-&gt;</span><span class="default">getBalance</span><span class="keyword">(</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr class="warning"><td><div align="right"><a name="32"></a><a href="#32">32</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="33"></a><a href="#33">33</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>

    </tbody>
   </table>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="success"><strong>Executed</strong></span>
     <span class="danger"><strong>Not Executed</strong></span>
     <span class="warning"><strong>Dead Code</strong></span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
    <a title="Back to the top" id="toplink" href="#">
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16"><path fill-rule="evenodd" d="M12 11L6 5l-6 6h12z"/></svg>
    </a>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/popper.min.js" type="text/javascript"></script>
  <script src="_js/bootstrap.min.js" type="text/javascript"></script>
  <script src="_js/file.js" type="text/javascript"></script>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item active">%s</li>
         <li class="breadcrumb-item">(<a href="dashboard.html">Dashboard</a>)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
       <td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="warning">Total</td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
           <span class="sr-only">87.50% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">87.50%</div></td>
       <td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
      </tr>

      <tr>
       <td class="warning"><img src="_icons/file-code.svg" class="octicon" /><a href="source_with_class_and_anonymous_function.php.html">source_with_class_and_anonymous_function.php</a></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
           <span class="sr-only">87.50% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">87.50%</div></td>
       <td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="danger"><strong>Low</strong>: 0% to 50%</span>
     <span class="warning"><strong>Medium</strong>: 50% to 90%</span>
     <span class="success"><strong>High</strong>: 90% to 100%</span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Dashboard for %s</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/nv.d3.min.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">(Dashboard)</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="row">
    <div class="col-md-12">
     <h2>Classes</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="classCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="classComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="source_with_class_and_anonymous_function.php.html#3">CoveredClassWithAnonymousFunctionInStaticMethod</a></td><td class="text-right">87%</td></tr>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-12">
     <h2>Methods</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="methodCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="methodComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
       <tr><td><a href="source_with_class_and_anonymous_function.php.html#5"><abbr title="CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous">runAnonymous</abbr></a></td><td class="text-right">87%</td></tr>

       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>

       </tbody>
      </table>
     </div>
    </div>
   </div>
   <footer>
    <hr/>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/d3.min.js" type="text/javascript"></script>
  <script src="_js/nv.d3.min.js" type="text/javascript"></script>
  <script type="text/javascript">
$(document).ready(function() {
  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#classCoverageDistribution svg')
      .datum(getCoverageDistributionData([0,0,0,0,0,0,0,0,0,1,0,0], "Class Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#methodCoverageDistribution svg')
      .datum(getCoverageDistributionData([0,0,0,0,0,0,0,0,0,1,0,0], "Method Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getCoverageDistributionData(data, label) {
    var labels = [
      '0%',
      '0-10%',
      '10-20%',
      '20-30%',
      '30-40%',
      '40-50%',
      '50-60%',
      '60-70%',
      '70-80%',
      '80-90%',
      '90-100%',
      '100%'
    ];
    var values = [];
    $.each(labels, function(key) {
      values.push({x: labels[key], y: data[key]});
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Cyclomatic Complexity');

    d3.select('#classComplexity svg')
      .datum(getComplexityData([[87.5,1,"<a href=\"source_with_class_and_anonymous_function.php.html#3\">CoveredClassWithAnonymousFunctionInStaticMethod<\/a>"]], 'Class Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Method Complexity');

    d3.select('#methodComplexity svg')
      .datum(getComplexityData([[87.5,1,"<a href=\"source_with_class_and_anonymous_function.php.html#5\">CoveredClassWithAnonymousFunctionInStaticMethod::runAnonymous<\/a>"]], 'Method Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getComplexityData(data, label) {
    var values = [];
    $.each(data, function(key) {
      var value = Math.round(data[key][0]*100) / 100;
      values.push({
        x: value,
        y: data[key][1],
        class: data[key][2],
        size: 0.05,
        shape: 'diamond'
      });
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
});
  </script>
 </body>
</html>
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for %s%esource_with_class_and_anonymous_function.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="_css/style.css" rel="stylesheet" type="text/css">
  <link href="_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
         <li class="breadcrumb-item"><a href="index.html">%s</a></li>
         <li class="breadcrumb-item active">source_with_class_and_anonymous_function.php</li>

       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
       <td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="danger">Total</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger small"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
           <span class="sr-only">87.50% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">87.50%</div></td>
       <td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
      </tr>

      <tr>
       <td class="danger">CoveredClassWithAnonymousFunctionInStaticMethod</td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger small">1.00</td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
           <span class="sr-only">87.50% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">87.50%</div></td>
       <td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
      </tr>

      <tr>
       <td class="danger" colspan="4">&nbsp;<a href="#5"><abbr title="runAnonymous()">runAnonymous</abbr></a></td>
       <td class="danger big">       <div class="progress">
         <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
           <span class="sr-only">0.00% covered (danger)</span>
         </div>
       </div>
</td>
       <td class="danger small"><div align="right">0.00%</div></td>
       <td class="danger small"><div align="right">0&nbsp;/&nbsp;1</div></td>
       <td class="danger small">1.00</td>
       <td class="warning big">       <div class="progress">
         <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="87.50" aria-valuemin="0" aria-valuemax="100" style="width: 87.50%">
           <span class="sr-only">87.50% covered (warning)</span>
         </div>
       </div>
</td>
       <td class="warning small"><div align="right">87.50%</div></td>
       <td class="warning small"><div align="right">7&nbsp;/&nbsp;8</div></td>
      </tr>


     </tbody>
    </table>
   </div>
   <table id="code" class="table table-borderless table-condensed">
    <tbody>
     <tr><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><span class="default">&lt;?php</span></td></tr>
     <tr><td><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"><span class="keyword">class</span><span class="default">&nbsp;</span><span class="default">CoveredClassWithAnonymousFunctionInStaticMethod</span></td></tr>
     <tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
     <tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">public</span><span class="default">&nbsp;</span><span class="keyword">static</span><span class="default">&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="default">runAnonymous</span><span class="keyword">(</span><span class="keyword">)</span></td></tr>
     <tr><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 7" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$filter</span><span class="default">&nbsp;</span><span class="keyword">=</span><span class="default">&nbsp;</span><span class="keyword">[</span><span class="default">'abc124'</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">'abc123'</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">'123'</span><span class="keyword">]</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 9" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">array_walk</span><span class="keyword">(</span></td></tr>
     <tr class="danger"><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$filter</span><span class="keyword">,</span></td></tr>
     <tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">function</span><span class="default">&nbsp;</span><span class="keyword">(</span><span class="keyword">&amp;</span><span class="default">$val</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">$key</span><span class="keyword">)</span><span class="default">&nbsp;</span><span class="keyword">{</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 12" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$val</span><span class="default">&nbsp;</span><span class="keyword">=</span><span class="default">&nbsp;</span><span class="default">preg_replace</span><span class="keyword">(</span><span class="default">'|[^0-9]|'</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">''</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">$val</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 13" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 14" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="14"></a><a href="#14">14</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">)</span><span class="keyword">;</span></td></tr>
     <tr><td><div align="right"><a name="15"></a><a href="#15">15</a></div></td><td class="codeLine"></td></tr>
     <tr><td><div align="right"><a name="16"></a><a href="#16">16</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="comment">//&nbsp;Should&nbsp;be&nbsp;covered</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 17" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="17"></a><a href="#17">17</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="default">$extravar</span><span class="default">&nbsp;</span><span class="keyword">=</span><span class="default">&nbsp;</span><span class="default">true</span><span class="keyword">;</span></td></tr>
     <tr class="covered-by-large-tests popin"><td data-title="1 test covers line 18" data-content="&lt;ul&gt;&lt;li&gt;ClassWithAnonymousFunction&lt;/li&gt;&lt;/ul&gt;" data-placement="top" data-html="true"><div align="right"><a name="18"></a><a href="#18">18</a></div></td><td class="codeLine"><span class="default">&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="keyword">}</span></td></tr>
     <tr><td><div align="right"><a name="19"></a><a href="#19">19</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>

    </tbody>
   </table>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="success"><strong>Executed</strong></span>
     <span class="danger"><strong>Not Executed</strong></span>
     <span class="warning"><strong>Dead Code</strong></span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage %s</a> using <a href="%s" target="_top">%s</a> at %s.</small>
    </p>
    <a title="Back to the top" id="toplink" href="#">
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16"><path fill-rule="evenodd" d="M12 11L6 5l-6 6h12z"/></svg>
    </a>
   </footer>
  </div>
  <script src="_js/jquery.min.js" type="text/javascript"></script>
  <script src="_js/popper.min.js" type="text/javascript"></script>
  <script src="_js/bootstrap.min.js" type="text/javascript"></script>
  <script src="_js/file.js" type="text/javascript"></script>
 </body>
</html>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <build time="%s" phpunit="%s" coverage="%s">
    <runtime name="%s" version="%s" url="%s"/>
    <driver%S/>
  </build>
  <project source="%s">
    <tests>
      <test name="FileWithIgnoredLines" size="unknown" result="-1" status="UNKNOWN"/>
    </tests>
    <directory name="%s">
      <totals>
        <lines total="37" comments="12" code="25" executable="2" executed="1" percent="50.00"/>
        <methods count="0" tested="0" percent="0"/>
        <functions count="1" tested="1" percent="100.00"/>
        <classes count="0" tested="0" percent="0"/>
        <traits count="0" tested="0" percent="0"/>
      </totals>
      <file name="source_with_ignore.php" href="source_with_ignore.php.xml">
        <totals>
          <lines total="37" comments="12" code="25" executable="2" executed="1" percent="50.00"/>
          <methods count="0" tested="0" percent="0"/>
          <functions count="1" tested="1" percent="100.00"/>
          <classes count="0" tested="0" percent="0"/>
          <traits count="0" tested="0" percent="0"/>
        </totals>
      </file>
    </directory>
  </project>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <file name="source_with_ignore.php" path="%e">
    <totals>
      <lines total="37" comments="12" code="25" executable="2" executed="1" percent="50.00"/>
      <methods count="0" tested="0" percent="0"/>
      <functions count="1" tested="1" percent="100.00"/>
      <classes count="0" tested="0" percent="0"/>
      <traits count="0" tested="0" percent="0"/>
    </totals>
    <class name="Foo" start="11" executable="0" executed="0" crap="1">
      <package full="" name="" sub="" category=""/>
      <namespace name=""/>
      <method name="bar" signature="bar()" start="13" end="15" crap="1" executable="0" executed="0" coverage="100"/>
    </class>
    <class name="Bar" start="18" executable="0" executed="0" crap="1">
      <package full="" name="" sub="" category=""/>
      <namespace name=""/>
      <method name="foo" signature="foo()" start="23" end="25" crap="1" executable="0" executed="0" coverage="100"/>
    </class>
    <function name="baz" signature="baz()" start="28" crap="1" executable="0" executed="0" coverage="100"/>
    <coverage>
      <line nr="2">
        <covered by="FileWithIgnoredLines"/>
      </line>
    </coverage>
    <source>
      <line no="1">
        <token name="T_OPEN_TAG">&lt;?php</token>
      </line>
      <line no="2">
        <token name="T_IF">if</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$neverHappens</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="3">
        <token name="T_WHITESPACE">    </token>
        <token name="T_COMMENT">// @codeCoverageIgnoreStart</token>
      </line>
      <line no="4">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PRINT">print</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'*'</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="5">
        <token name="T_WHITESPACE">    </token>
        <token name="T_COMMENT">// @codeCoverageIgnoreEnd</token>
      </line>
      <line no="6">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="7"/>
      <line no="8">
        <token name="T_DOC_COMMENT">/**</token>
      </line>
      <line no="9">
        <token name="T_DOC_COMMENT"> * @codeCoverageIgnore</token>
      </line>
      <line no="10">
        <token name="T_DOC_COMMENT"> */</token>
      </line>
      <line no="11">
        <token name="T_CLASS">class</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">Foo</token>
      </line>
      <line no="12">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="13">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">bar</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="14">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="15">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="16">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="17"/>
      <line no="18">
        <token name="T_CLASS">class</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">Bar</token>
      </line>
      <line no="19">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="20">
        <token name="T_WHITESPACE">    </token>
        <token name="T_DOC_COMMENT">/**</token>
      </line>
      <line no="21">
        <token name="T_DOC_COMMENT">     * @codeCoverageIgnore</token>
      </line>
      <line no="22">
        <token name="T_DOC_COMMENT">     */</token>
      </line>
      <line no="23">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">foo</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="24">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="25">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="26">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="27"/>
      <line no="28">
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">baz</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="29">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="30">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PRINT">print</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'*'</token>
        <token name="T_SEMICOLON">;</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_COMMENT">// @codeCoverageIgnore</token>
      </line>
      <line no="31">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="32"/>
      <line no="33">
        <token name="T_INTERFACE">interface</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">Bor</token>
      </line>
      <line no="34">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="35">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">foo</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="36"/>
      <line no="37">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="38"/>
    </source>
  </file>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <build time="%s" phpunit="%s" coverage="%s">
    <runtime name="%s" version="%s" url="%s"/>
    <driver%S/>
  </build>
  <project source="%s">
    <tests>
      <test name="BankAccountTest::testBalanceIsInitiallyZero" size="unknown" result="-1" status="UNKNOWN"/>
      <test name="BankAccountTest::testBalanceCannotBecomeNegative" size="unknown" result="-1" status="UNKNOWN"/>
      <test name="BankAccountTest::testBalanceCannotBecomeNegative2" size="unknown" result="-1" status="UNKNOWN"/>
      <test name="BankAccountTest::testDepositWithdrawMoney" size="unknown" result="-1" status="UNKNOWN"/>
    </tests>
    <directory name="%s">
      <totals>
        <lines total="33" comments="0" code="33" executable="10" executed="5" percent="50.00"/>
        <methods count="4" tested="3" percent="75.00"/>
        <functions count="0" tested="0" percent="0"/>
        <classes count="1" tested="0" percent="0.00"/>
        <traits count="0" tested="0" percent="0"/>
      </totals>
      <file name="BankAccount.php" href="BankAccount.php.xml">
        <totals>
          <lines total="33" comments="0" code="33" executable="10" executed="5" percent="50.00"/>
          <methods count="4" tested="3" percent="75.00"/>
          <functions count="0" tested="0" percent="0"/>
          <classes count="1" tested="0" percent="0.00"/>
          <traits count="0" tested="0" percent="0"/>
        </totals>
      </file>
    </directory>
  </project>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <file name="BankAccount.php" path="%e">
    <totals>
      <lines total="33" comments="0" code="33" executable="10" executed="5" percent="50.00"/>
      <methods count="4" tested="3" percent="75.00"/>
      <functions count="0" tested="0" percent="0"/>
      <classes count="1" tested="0" percent="0.00"/>
      <traits count="0" tested="0" percent="0"/>
    </totals>
    <class name="BankAccount" start="2" executable="10" executed="5" crap="8.12">
      <package full="" name="" sub="" category=""/>
      <namespace name=""/>
      <method name="getBalance" signature="getBalance()" start="6" end="9" crap="1" executable="1" executed="1" coverage="100"/>
      <method name="setBalance" signature="setBalance($balance)" start="11" end="18" crap="6" executable="5" executed="0" coverage="0"/>
      <method name="depositMoney" signature="depositMoney($balance)" start="20" end="25" crap="1" executable="2" executed="2" coverage="100"/>
      <method name="withdrawMoney" signature="withdrawMoney($balance)" start="27" end="32" crap="1" executable="2" executed="2" coverage="100"/>
    </class>
    <coverage>
      <line nr="8">
        <covered by="BankAccountTest::testBalanceIsInitiallyZero"/>
        <covered by="BankAccountTest::testDepositWithdrawMoney"/>
      </line>
      <line nr="22">
        <covered by="BankAccountTest::testBalanceCannotBecomeNegative2"/>
        <covered by="BankAccountTest::testDepositWithdrawMoney"/>
      </line>
      <line nr="24">
        <covered by="BankAccountTest::testDepositWithdrawMoney"/>
      </line>
      <line nr="29">
        <covered by="BankAccountTest::testBalanceCannotBecomeNegative"/>
        <covered by="BankAccountTest::testDepositWithdrawMoney"/>
      </line>
      <line nr="31">
        <covered by="BankAccountTest::testDepositWithdrawMoney"/>
      </line>
    </coverage>
    <source>
      <line no="1">
        <token name="T_OPEN_TAG">&lt;?php</token>
      </line>
      <line no="2">
        <token name="T_CLASS">class</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">BankAccount</token>
      </line>
      <line no="3">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="4">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PROTECTED">protected</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_EQUAL">=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_LNUMBER">0</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="5"/>
      <line no="6">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">getBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="7">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="8">
        <token name="T_WHITESPACE">        </token>
        <token name="T_RETURN">return</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">balance</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="9">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="10"/>
      <line no="11">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PROTECTED">protected</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">setBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="12">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="13">
        <token name="T_WHITESPACE">        </token>
        <token name="T_IF">if</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_IS_GREATER_OR_EQUAL">&gt;=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_LNUMBER">0</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="14">
        <token name="T_WHITESPACE">            </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">balance</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_EQUAL">=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="15">
        <token name="T_WHITESPACE">        </token>
        <token name="T_CLOSE_CURLY">}</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_ELSE">else</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="16">
        <token name="T_WHITESPACE">            </token>
        <token name="T_THROW">throw</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_NEW">new</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">RuntimeException</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="17">
        <token name="T_WHITESPACE">        </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="18">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="19"/>
      <line no="20">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">depositMoney</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="21">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="22">
        <token name="T_WHITESPACE">        </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">setBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">getBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_PLUS">+</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="23"/>
      <line no="24">
        <token name="T_WHITESPACE">        </token>
        <token name="T_RETURN">return</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">getBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="25">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="26"/>
      <line no="27">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">withdrawMoney</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="28">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="29">
        <token name="T_WHITESPACE">        </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">setBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">getBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_MINUS">-</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$balance</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="30"/>
      <line no="31">
        <token name="T_WHITESPACE">        </token>
        <token name="T_RETURN">return</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$this</token>
        <token name="T_OBJECT_OPERATOR">-&gt;</token>
        <token name="T_STRING">getBalance</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="32">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="33">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="34"/>
    </source>
  </file>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <build time="%s" phpunit="%s" coverage="%s">
    <runtime name="%s" version="%s" url="%s"/>
    <driver%S/>
  </build>
  <project source="%s">
    <tests>
      <test name="ClassWithAnonymousFunction" size="unknown" result="-1" status="UNKNOWN"/>
    </tests>
    <directory name="%s">
      <totals>
        <lines total="19" comments="2" code="17" executable="8" executed="7" percent="87.50"/>
        <methods count="1" tested="0" percent="0.00"/>
        <functions count="0" tested="0" percent="0"/>
        <classes count="1" tested="0" percent="0.00"/>
        <traits count="0" tested="0" percent="0"/>
      </totals>
      <file name="source_with_class_and_anonymous_function.php" href="source_with_class_and_anonymous_function.php.xml">
        <totals>
          <lines total="19" comments="2" code="17" executable="8" executed="7" percent="87.50"/>
          <methods count="1" tested="0" percent="0.00"/>
          <functions count="0" tested="0" percent="0"/>
          <classes count="1" tested="0" percent="0.00"/>
          <traits count="0" tested="0" percent="0"/>
        </totals>
      </file>
    </directory>
  </project>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns="https://schema.phpunit.de/coverage/1.0">
  <file name="source_with_class_and_anonymous_function.php" path="%e">
    <totals>
      <lines total="19" comments="2" code="17" executable="8" executed="7" percent="87.50"/>
      <methods count="1" tested="0" percent="0.00"/>
      <functions count="0" tested="0" percent="0"/>
      <classes count="1" tested="0" percent="0.00"/>
      <traits count="0" tested="0" percent="0"/>
    </totals>
    <class name="CoveredClassWithAnonymousFunctionInStaticMethod" start="3" executable="8" executed="7" crap="1">
      <package full="" name="" sub="" category=""/>
      <namespace name=""/>
      <method name="runAnonymous" signature="runAnonymous()" start="5" end="18" crap="1.00" executable="8" executed="7" coverage="87.5"/>
    </class>
    <coverage>
      <line nr="7">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="9">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="12">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="13">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="14">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="17">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
      <line nr="18">
        <covered by="ClassWithAnonymousFunction"/>
      </line>
    </coverage>
    <source>
      <line no="1">
        <token name="T_OPEN_TAG">&lt;?php</token>
      </line>
      <line no="2"/>
      <line no="3">
        <token name="T_CLASS">class</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">CoveredClassWithAnonymousFunctionInStaticMethod</token>
      </line>
      <line no="4">
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="5">
        <token name="T_WHITESPACE">    </token>
        <token name="T_PUBLIC">public</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STATIC">static</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">runAnonymous</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CLOSE_BRACKET">)</token>
      </line>
      <line no="6">
        <token name="T_WHITESPACE">    </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="7">
        <token name="T_WHITESPACE">        </token>
        <token name="T_VARIABLE">$filter</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_EQUAL">=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_SQUARE">[</token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'abc124'</token>
        <token name="T_COMMA">,</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'abc123'</token>
        <token name="T_COMMA">,</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'123'</token>
        <token name="T_CLOSE_SQUARE">]</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="8"/>
      <line no="9">
        <token name="T_WHITESPACE">        </token>
        <token name="T_STRING">array_walk</token>
        <token name="T_OPEN_BRACKET">(</token>
      </line>
      <line no="10">
        <token name="T_WHITESPACE">            </token>
        <token name="T_VARIABLE">$filter</token>
        <token name="T_COMMA">,</token>
      </line>
      <line no="11">
        <token name="T_WHITESPACE">            </token>
        <token name="T_FUNCTION">function</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_AMPERSAND">&amp;</token>
        <token name="T_VARIABLE">$val</token>
        <token name="T_COMMA">,</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$key</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_OPEN_CURLY">{</token>
      </line>
      <line no="12">
        <token name="T_WHITESPACE">                </token>
        <token name="T_VARIABLE">$val</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_EQUAL">=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">preg_replace</token>
        <token name="T_OPEN_BRACKET">(</token>
        <token name="T_CONSTANT_ENCAPSED_STRING">'|[^0-9]|'</token>
        <token name="T_COMMA">,</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_CONSTANT_ENCAPSED_STRING">''</token>
        <token name="T_COMMA">,</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_VARIABLE">$val</token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="13">
        <token name="T_WHITESPACE">            </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="14">
        <token name="T_WHITESPACE">        </token>
        <token name="T_CLOSE_BRACKET">)</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="15"/>
      <line no="16">
        <token name="T_WHITESPACE">        </token>
        <token name="T_COMMENT">// Should be covered</token>
      </line>
      <line no="17">
        <token name="T_WHITESPACE">        </token>
        <token name="T_VARIABLE">$extravar</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_EQUAL">=</token>
        <token name="T_WHITESPACE"> </token>
        <token name="T_STRING">true</token>
        <token name="T_SEMICOLON">;</token>
      </line>
      <line no="18">
        <token name="T_WHITESPACE">    </token>
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="19">
        <token name="T_CLOSE_CURLY">}</token>
      </line>
      <line no="20"/>
    </source>
  </file>
</phpunit>
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageMethodTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass::publicMethod
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageMethodOneLineAnnotationTest extends TestCase
{
    /** @covers CoveredClass::publicMethod */
    public function testSomething()
    {
        $o = new CoveredClass;
        $o->publicMethod();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class BankAccountTest extends TestCase
{
    protected $ba;

    protected function setUp(): void
    {
        $this->ba = new BankAccount;
    }

    /**
     * @covers BankAccount::getBalance
     */
    public function testBalanceIsInitiallyZero()
    {
        $this->assertEquals(0, $this->ba->getBalance());
    }

    /**
     * @covers BankAccount::withdrawMoney
     */
    public function testBalanceCannotBecomeNegative()
    {
        try {
            $this->ba->withdrawMoney(1);
        } catch (RuntimeException $e) {
            $this->assertEquals(0, $this->ba->getBalance());

            return;
        }

        $this->fail();
    }

    /**
     * @covers BankAccount::depositMoney
     */
    public function testBalanceCannotBecomeNegative2()
    {
        try {
            $this->ba->depositMoney(-1);
        } catch (RuntimeException $e) {
            $this->assertEquals(0, $this->ba->getBalance());

            return;
        }

        $this->fail();
    }

    /**
     * @covers BankAccount::getBalance
     * @covers BankAccount::depositMoney
     * @covers BankAccount::withdrawMoney
     */
    public function testDepositWithdrawMoney()
    {
        $this->assertEquals(0, $this->ba->getBalance());
        $this->ba->depositMoney(1);
        $this->assertEquals(1, $this->ba->getBalance());
        $this->ba->withdrawMoney(1);
        $this->assertEquals(0, $this->ba->getBalance());
    }
}
<?php
use PHPUnit\Framework\TestCase;

class CoverageFunctionParenthesesWhitespaceTest extends TestCase
{
    /**
     * @covers ::globalFunction ( )
     */
    public function testSomething()
    {
        globalFunction();
    }
}
<?php
class BankAccount
{
    protected $balance = 0;

    public function getBalance()
    {
        return $this->balance;
    }

    protected function setBalance($balance)
    {
        if ($balance >= 0) {
            $this->balance = $balance;
        } else {
            throw new RuntimeException;
        }
    }

    public function depositMoney($balance)
    {
        $this->setBalance($this->getBalance() + $balance);

        return $this->getBalance();
    }

    public function withdrawMoney($balance)
    {
        $this->setBalance($this->getBalance() - $balance);

        return $this->getBalance();
    }
}
<?php
use PHPUnit\Framework\TestCase;

class NamespaceCoverageClassTest extends TestCase
{
    /**
     * @covers Foo\CoveredClass
     */
    public function testSomething()
    {
        $o = new Foo\CoveredClass;
        $o->publicMethod();
    }
}
<?php
class CoveredParentClass
{
    private function privateMethod()
    {
    }

    protected function protectedMethod()
    {
        $this->privateMethod();
    }

    public function publicMethod()
    {
        $this->protectedMethod();
    }
}

class CoveredClass extends CoveredParentClass
{
    private function privateMethod()
    {
    }

    protected function protectedMethod()
    {
        parent::protectedMethod();
        $this->privateMethod();
    }

    public function publicMethod()
    {
        parent::publicMethod();
        $this->protectedMethod();
    }
}
<?php
if ($neverHappens) {
    // @codeCoverageIgnoreStart
    print '*';
    // @codeCoverageIgnoreEnd
}

/**
 * @codeCoverageIgnore
 */
class Foo
{
    public function bar()
    {
    }
}

class Bar
{
    /**
     * @codeCoverageIgnore
     */
    public function foo()
    {
    }
}

function baz()
{
    print '*'; // @codeCoverageIgnore
}

interface Bor
{
    public function foo();

}
<?php

class CoveredClassWithAnonymousFunctionInStaticMethod
{
    public static function runAnonymous()
    {
        $filter = ['abc124', 'abc123', '123'];

        array_walk(
            $filter,
            function (&$val, $key) {
                $val = preg_replace('|[^0-9]|', '', $val);
            }
        );

        // Should be covered
        $extravar = true;
    }
}
<?php
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\CodeCoverage;

use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\CodeCoverage\Report\Xml\Coverage;

abstract class TestCase extends \PHPUnit\Framework\TestCase
{
    protected static $TEST_TMP_PATH;

    public static function setUpBeforeClass(): void
    {
        self::$TEST_TMP_PATH = TEST_FILES_PATH . 'tmp';
    }

    protected function getXdebugDataForBankAccount()
    {
        return [
            [
                TEST_FILES_PATH . 'BankAccount.php' => [
                    8  => 1,
                    9  => -2,
                    13 => -1,
                    14 => -1,
                    15 => -1,
                    16 => -1,
                    18 => -1,
                    22 => -1,
                    24 => -1,
                    25 => -2,
                    29 => -1,
                    31 => -1,
                    32 => -2
                ]
            ],
            [
                TEST_FILES_PATH . 'BankAccount.php' => [
                    8  => 1,
                    13 => 1,
                    16 => 1,
                    29 => 1,
                ]
            ],
            [
                TEST_FILES_PATH . 'BankAccount.php' => [
                    8  => 1,
                    13 => 1,
                    16 => 1,
                    22 => 1,
                ]
            ],
            [
                TEST_FILES_PATH . 'BankAccount.php' => [
                    8  => 1,
                    13 => 1,
                    14 => 1,
                    15 => 1,
                    18 => 1,
                    22 => 1,
                    24 => 1,
                    29 => 1,
                    31 => 1,
                ]
            ]
        ];
    }

    protected function getCoverageForBankAccount(): CodeCoverage
    {
        $data = $this->getXdebugDataForBankAccount();

        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->onConsecutiveCalls(
                $data[0],
                $data[1],
                $data[2],
                $data[3]
            ));

        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'BankAccount.php');

        $coverage = new CodeCoverage($stub, $filter);

        $coverage->start(
            new \BankAccountTest('testBalanceIsInitiallyZero'),
            true
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(6, 9)]
        );

        $coverage->start(
            new \BankAccountTest('testBalanceCannotBecomeNegative')
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(27, 32)]
        );

        $coverage->start(
            new \BankAccountTest('testBalanceCannotBecomeNegative2')
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(20, 25)]
        );

        $coverage->start(
            new \BankAccountTest('testDepositWithdrawMoney')
        );

        $coverage->stop(
            true,
            [
                TEST_FILES_PATH . 'BankAccount.php' => array_merge(
                    range(6, 9),
                    range(20, 25),
                    range(27, 32)
                )
            ]
        );

        return $coverage;
    }

    protected function getCoverageForBankAccountForFirstTwoTests(): CodeCoverage
    {
        $data = $this->getXdebugDataForBankAccount();

        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->onConsecutiveCalls(
                $data[0],
                $data[1]
            ));

        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'BankAccount.php');

        $coverage = new CodeCoverage($stub, $filter);

        $coverage->start(
            new \BankAccountTest('testBalanceIsInitiallyZero'),
            true
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(6, 9)]
        );

        $coverage->start(
            new \BankAccountTest('testBalanceCannotBecomeNegative')
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(27, 32)]
        );

        return $coverage;
    }

    protected function getCoverageForBankAccountForLastTwoTests()
    {
        $data = $this->getXdebugDataForBankAccount();

        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->onConsecutiveCalls(
                $data[2],
                $data[3]
            ));

        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'BankAccount.php');

        $coverage = new CodeCoverage($stub, $filter);

        $coverage->start(
            new \BankAccountTest('testBalanceCannotBecomeNegative2')
        );

        $coverage->stop(
            true,
            [TEST_FILES_PATH . 'BankAccount.php' => range(20, 25)]
        );

        $coverage->start(
            new \BankAccountTest('testDepositWithdrawMoney')
        );

        $coverage->stop(
            true,
            [
                TEST_FILES_PATH . 'BankAccount.php' => array_merge(
                    range(6, 9),
                    range(20, 25),
                    range(27, 32)
                )
            ]
        );

        return $coverage;
    }

    protected function getExpectedDataArrayForBankAccount(): array
    {
        return [
            TEST_FILES_PATH . 'BankAccount.php' => [
                8 => [
                    0 => 'BankAccountTest::testBalanceIsInitiallyZero',
                    1 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                9  => null,
                13 => [],
                14 => [],
                15 => [],
                16 => [],
                18 => [],
                22 => [
                    0 => 'BankAccountTest::testBalanceCannotBecomeNegative2',
                    1 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                24 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney',
                ],
                25 => null,
                29 => [
                    0 => 'BankAccountTest::testBalanceCannotBecomeNegative',
                    1 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                31 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                32 => null
            ]
        ];
    }

    protected function getExpectedDataArrayForBankAccountInReverseOrder(): array
    {
        return [
            TEST_FILES_PATH . 'BankAccount.php' => [
                8 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney',
                    1 => 'BankAccountTest::testBalanceIsInitiallyZero'
                ],
                9  => null,
                13 => [],
                14 => [],
                15 => [],
                16 => [],
                18 => [],
                22 => [
                    0 => 'BankAccountTest::testBalanceCannotBecomeNegative2',
                    1 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                24 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney',
                ],
                25 => null,
                29 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney',
                    1 => 'BankAccountTest::testBalanceCannotBecomeNegative'
                ],
                31 => [
                    0 => 'BankAccountTest::testDepositWithdrawMoney'
                ],
                32 => null
            ]
        ];
    }

    protected function getCoverageForFileWithIgnoredLines(): CodeCoverage
    {
        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'source_with_ignore.php');

        $coverage = new CodeCoverage(
            $this->setUpXdebugStubForFileWithIgnoredLines(),
            $filter
        );

        $coverage->start('FileWithIgnoredLines', true);
        $coverage->stop();

        return $coverage;
    }

    protected function setUpXdebugStubForFileWithIgnoredLines(): Driver
    {
        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->returnValue(
                [
                    TEST_FILES_PATH . 'source_with_ignore.php' => [
                        2 => 1,
                        4 => -1,
                        6 => -1,
                        7 => 1
                    ]
                ]
            ));

        return $stub;
    }

    protected function getCoverageForClassWithAnonymousFunction(): CodeCoverage
    {
        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'source_with_class_and_anonymous_function.php');

        $coverage = new CodeCoverage(
            $this->setUpXdebugStubForClassWithAnonymousFunction(),
            $filter
        );

        $coverage->start('ClassWithAnonymousFunction', true);
        $coverage->stop();

        return $coverage;
    }

    protected function setUpXdebugStubForClassWithAnonymousFunction(): Driver
    {
        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->returnValue(
                [
                    TEST_FILES_PATH . 'source_with_class_and_anonymous_function.php' => [
                        7  => 1,
                        9  => 1,
                        10 => -1,
                        11 => 1,
                        12 => 1,
                        13 => 1,
                        14 => 1,
                        17 => 1,
                        18 => 1
                    ]
                ]
            ));

        return $stub;
    }

    protected function getCoverageForCrashParsing(): CodeCoverage
    {
        $filter = new Filter;
        $filter->addFileToWhitelist(TEST_FILES_PATH . 'Crash.php');

        // This is a file with invalid syntax, so it isn't executed.
        return new CodeCoverage(
            $this->setUpXdebugStubForCrashParsing(),
            $filter
        );
    }

    protected function setUpXdebugStubForCrashParsing(): Driver
    {
        $stub = $this->createMock(Driver::class);

        $stub->expects($this->any())
            ->method('stop')
            ->will($this->returnValue([]));
        return $stub;
    }

}
[![Latest Stable Version](https://poser.pugx.org/phpunit/php-code-coverage/v/stable.png)](https://packagist.org/packages/phpunit/php-code-coverage)
[![Build Status](https://travis-ci.org/sebastianbergmann/php-code-coverage.svg?branch=master)](https://travis-ci.org/sebastianbergmann/php-code-coverage)

# SebastianBergmann\CodeCoverage

**SebastianBergmann\CodeCoverage** is a library that provides collection, processing, and rendering functionality for PHP code coverage information.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require phpunit/php-code-coverage

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev phpunit/php-code-coverage

## Using the SebastianBergmann\CodeCoverage API

```php
<?php
use SebastianBergmann\CodeCoverage\CodeCoverage;

$coverage = new CodeCoverage;

$coverage->filter()->addDirectoryToWhitelist('/path/to/src');

$coverage->start('<name of test>');

// ...

$coverage->stop();

$writer = new \SebastianBergmann\CodeCoverage\Report\Clover;
$writer->process($coverage, '/tmp/clover.xml');

$writer = new \SebastianBergmann\CodeCoverage\Report\Html\Facade;
$writer->process($coverage, '/tmp/code-coverage-report');
```

/tests/_files/tmp
/vendor
/composer.lock
/.idea
/.php_cs
/.php_cs.cache
/.phpunit.result.cache
github: sebastianbergmann
| Q                         | A
| --------------------------| ---------------
| php-code-coverage version | x.y.z
| PHP version               | x.y.z
| Driver                    | Xdebug / PHPDBG
| Xdebug version (if used)  | x.y.z
| Installation Method       | Composer / PHPUnit PHAR
| Usage Method              | PHPUnit / other
| PHPUnit version (if used) | x.y.z

<!--
- Please fill in this template according to your issue.
- Please keep the table shown above at the top of your issue.
- Please post code as text (using proper markup). Do not post screenshots of code.
- For support request or how-tos, visit https://phpunit.de/support.html
- Otherwise, replace this comment by the description of your issue.
-->

Please refer to [https://github.com/sebastianbergmann/phpunit/blob/master/CONTRIBUTING.md](https://github.com/sebastianbergmann/phpunit/blob/master/.github/CONTRIBUTING.md) for details on how to contribute to this project.
/tools export-ignore

*.php diff=php
<?xml version="1.0" encoding="UTF-8"?>
<phive xmlns="https://phar.io/phive">
  <phar name="php-cs-fixer" version="^2.14" installed="2.14.2" location="./tools/php-cs-fixer" copy="true"/>
</phive>
language: php

php:
  - 7.2
  - 7.3
  - 7.4snapshot

matrix:
  fast_finish: true

env:
  matrix:
    - DRIVER="xdebug" DEPENDENCIES="high"
    - DRIVER="phpdbg" DEPENDENCIES="high"
    - DRIVER="pcov"   DEPENDENCIES="high"
    - DRIVER="xdebug" DEPENDENCIES="low"
    - DRIVER="phpdbg" DEPENDENCIES="low"
    - DRIVER="pcov"   DEPENDENCIES="low"
  global:
    - DEFAULT_COMPOSER_FLAGS="--no-interaction --no-ansi --no-progress --no-suggest"

before_install:
  - ./tools/composer clear-cache

install:
  - if [[ "$DEPENDENCIES" = 'high' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS; fi
  - if [[ "$DEPENDENCIES" = 'low' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS --prefer-lowest; fi

before_script:
  - |
     if [[ "$DRIVER" = 'pcov' ]]; then
       echo > $HOME/.phpenv/versions/$TRAVIS_PHP_VERSION/etc/conf.d/xdebug.ini
       git clone --single-branch --branch=v1.0.6 --depth=1 https://github.com/krakjoe/pcov
       cd pcov
       phpize
       ./configure
       make clean install
       echo "extension=pcov.so" > $HOME/.phpenv/versions/$TRAVIS_PHP_VERSION/etc/conf.d/pcov.ini
       cd $TRAVIS_BUILD_DIR
     fi

script:
  - if [[ "$DRIVER" = 'phpdbg' ]]; then phpdbg -qrr vendor/bin/phpunit --coverage-clover=coverage.xml; fi
  - if [[ "$DRIVER" != 'phpdbg' ]]; then vendor/bin/phpunit --coverage-clover=coverage.xml; fi

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false

jobs:
  include:
    - stage: Static Code Analysis
      php: 7.3
      env: php-cs-fixer
      install:
        - phpenv config-rm xdebug.ini
      script:
        - ./tools/php-cs-fixer fix --dry-run -v --show-progress=dots --diff-format=udiff
{
    "name": "phpunit/php-code-coverage",
    "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
    "type": "library",
    "keywords": [
        "coverage",
        "testing",
        "xunit"
    ],
    "homepage": "https://github.com/sebastianbergmann/php-code-coverage",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues"
    },
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.2",
        "ext-dom": "*",
        "ext-xmlwriter": "*",
        "phpunit/php-file-iterator": "^2.0.2",
        "phpunit/php-token-stream": "^3.1.3 || ^4.0",
        "phpunit/php-text-template": "^1.2.1",
        "sebastian/code-unit-reverse-lookup": "^1.0.1",
        "sebastian/environment": "^4.2.2",
        "sebastian/version": "^2.0.1",
        "theseer/tokenizer": "^1.1.3"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.2.2"
    },
    "suggest": {
        "ext-xdebug": "^2.7.2"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "files": [
            "tests/TestCase.php",
            "tests/_files/BankAccountTest.php"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "7.0-dev"
        }
    }
}
<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of the php-code-coverage package.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => ['groups' => ['simple', 'meta']],
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use PHPUnit\Framework\TestCase;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\Test;
use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\CodeCoverage\Driver\PCOV;
use SebastianBergmann\CodeCoverage\Driver\PHPDBG;
use SebastianBergmann\CodeCoverage\Driver\Xdebug;
use SebastianBergmann\CodeCoverage\Node\Builder;
use SebastianBergmann\CodeCoverage\Node\Directory;
use SebastianBergmann\CodeUnitReverseLookup\Wizard;
use SebastianBergmann\Environment\Runtime;

/**
 * Provides collection functionality for PHP code coverage information.
 */
final class CodeCoverage
{
    /**
     * @var Driver
     */
    private $driver;

    /**
     * @var Filter
     */
    private $filter;

    /**
     * @var Wizard
     */
    private $wizard;

    /**
     * @var bool
     */
    private $cacheTokens = false;

    /**
     * @var bool
     */
    private $checkForUnintentionallyCoveredCode = false;

    /**
     * @var bool
     */
    private $forceCoversAnnotation = false;

    /**
     * @var bool
     */
    private $checkForUnexecutedCoveredCode = false;

    /**
     * @var bool
     */
    private $checkForMissingCoversAnnotation = false;

    /**
     * @var bool
     */
    private $addUncoveredFilesFromWhitelist = true;

    /**
     * @var bool
     */
    private $processUncoveredFilesFromWhitelist = false;

    /**
     * @var bool
     */
    private $ignoreDeprecatedCode = false;

    /**
     * @var PhptTestCase|string|TestCase
     */
    private $currentId;

    /**
     * Code coverage data.
     *
     * @var array
     */
    private $data = [];

    /**
     * @var array
     */
    private $ignoredLines = [];

    /**
     * @var bool
     */
    private $disableIgnoredLines = false;

    /**
     * Test data.
     *
     * @var array
     */
    private $tests = [];

    /**
     * @var string[]
     */
    private $unintentionallyCoveredSubclassesWhitelist = [];

    /**
     * Determine if the data has been initialized or not
     *
     * @var bool
     */
    private $isInitialized = false;

    /**
     * Determine whether we need to check for dead and unused code on each test
     *
     * @var bool
     */
    private $shouldCheckForDeadAndUnused = true;

    /**
     * @var Directory
     */
    private $report;

    /**
     * @throws RuntimeException
     */
    public function __construct(Driver $driver = null, Filter $filter = null)
    {
        if ($filter === null) {
            $filter = new Filter;
        }

        if ($driver === null) {
            $driver = $this->selectDriver($filter);
        }

        $this->driver = $driver;
        $this->filter = $filter;

        $this->wizard = new Wizard;
    }

    /**
     * Returns the code coverage information as a graph of node objects.
     */
    public function getReport(): Directory
    {
        if ($this->report === null) {
            $this->report = (new Builder)->build($this);
        }

        return $this->report;
    }

    /**
     * Clears collected code coverage data.
     */
    public function clear(): void
    {
        $this->isInitialized = false;
        $this->currentId     = null;
        $this->data          = [];
        $this->tests         = [];
        $this->report        = null;
    }

    /**
     * Returns the filter object used.
     */
    public function filter(): Filter
    {
        return $this->filter;
    }

    /**
     * Returns the collected code coverage data.
     */
    public function getData(bool $raw = false): array
    {
        if (!$raw && $this->addUncoveredFilesFromWhitelist) {
            $this->addUncoveredFilesFromWhitelist();
        }

        return $this->data;
    }

    /**
     * Sets the coverage data.
     */
    public function setData(array $data): void
    {
        $this->data   = $data;
        $this->report = null;
    }

    /**
     * Returns the test data.
     */
    public function getTests(): array
    {
        return $this->tests;
    }

    /**
     * Sets the test data.
     */
    public function setTests(array $tests): void
    {
        $this->tests = $tests;
    }

    /**
     * Start collection of code coverage information.
     *
     * @param PhptTestCase|string|TestCase $id
     *
     * @throws RuntimeException
     */
    public function start($id, bool $clear = false): void
    {
        if ($clear) {
            $this->clear();
        }

        if ($this->isInitialized === false) {
            $this->initializeData();
        }

        $this->currentId = $id;

        $this->driver->start($this->shouldCheckForDeadAndUnused);
    }

    /**
     * Stop collection of code coverage information.
     *
     * @param array|false $linesToBeCovered
     *
     * @throws MissingCoversAnnotationException
     * @throws CoveredCodeNotExecutedException
     * @throws RuntimeException
     * @throws InvalidArgumentException
     * @throws \ReflectionException
     */
    public function stop(bool $append = true, $linesToBeCovered = [], array $linesToBeUsed = [], bool $ignoreForceCoversAnnotation = false): array
    {
        if (!\is_array($linesToBeCovered) && $linesToBeCovered !== false) {
            throw InvalidArgumentException::create(
                2,
                'array or false'
            );
        }

        $data = $this->driver->stop();
        $this->append($data, null, $append, $linesToBeCovered, $linesToBeUsed, $ignoreForceCoversAnnotation);

        $this->currentId = null;

        return $data;
    }

    /**
     * Appends code coverage data.
     *
     * @param PhptTestCase|string|TestCase $id
     * @param array|false                  $linesToBeCovered
     *
     * @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
     * @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
     * @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
     * @throws \ReflectionException
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     * @throws RuntimeException
     */
    public function append(array $data, $id = null, bool $append = true, $linesToBeCovered = [], array $linesToBeUsed = [], bool $ignoreForceCoversAnnotation = false): void
    {
        if ($id === null) {
            $id = $this->currentId;
        }

        if ($id === null) {
            throw new RuntimeException;
        }

        $this->applyWhitelistFilter($data);
        $this->applyIgnoredLinesFilter($data);
        $this->initializeFilesThatAreSeenTheFirstTime($data);

        if (!$append) {
            return;
        }

        if ($id !== 'UNCOVERED_FILES_FROM_WHITELIST') {
            $this->applyCoversAnnotationFilter(
                $data,
                $linesToBeCovered,
                $linesToBeUsed,
                $ignoreForceCoversAnnotation
            );
        }

        if (empty($data)) {
            return;
        }

        $size   = 'unknown';
        $status = -1;

        if ($id instanceof TestCase) {
            $_size = $id->getSize();

            if ($_size === Test::SMALL) {
                $size = 'small';
            } elseif ($_size === Test::MEDIUM) {
                $size = 'medium';
            } elseif ($_size === Test::LARGE) {
                $size = 'large';
            }

            $status = $id->getStatus();
            $id     = \get_class($id) . '::' . $id->getName();
        } elseif ($id instanceof PhptTestCase) {
            $size = 'large';
            $id   = $id->getName();
        }

        $this->tests[$id] = ['size' => $size, 'status' => $status];

        foreach ($data as $file => $lines) {
            if (!$this->filter->isFile($file)) {
                continue;
            }

            foreach ($lines as $k => $v) {
                if ($v === Driver::LINE_EXECUTED) {
                    if (empty($this->data[$file][$k]) || !\in_array($id, $this->data[$file][$k])) {
                        $this->data[$file][$k][] = $id;
                    }
                }
            }
        }

        $this->report = null;
    }

    /**
     * Merges the data from another instance.
     *
     * @param CodeCoverage $that
     */
    public function merge(self $that): void
    {
        $this->filter->setWhitelistedFiles(
            \array_merge($this->filter->getWhitelistedFiles(), $that->filter()->getWhitelistedFiles())
        );

        foreach ($that->data as $file => $lines) {
            if (!isset($this->data[$file])) {
                if (!$this->filter->isFiltered($file)) {
                    $this->data[$file] = $lines;
                }

                continue;
            }

            // we should compare the lines if any of two contains data
            $compareLineNumbers = \array_unique(
                \array_merge(
                    \array_keys($this->data[$file]),
                    \array_keys($that->data[$file])
                )
            );

            foreach ($compareLineNumbers as $line) {
                $thatPriority = $this->getLinePriority($that->data[$file], $line);
                $thisPriority = $this->getLinePriority($this->data[$file], $line);

                if ($thatPriority > $thisPriority) {
                    $this->data[$file][$line] = $that->data[$file][$line];
                } elseif ($thatPriority === $thisPriority && \is_array($this->data[$file][$line])) {
                    $this->data[$file][$line] = \array_unique(
                        \array_merge($this->data[$file][$line], $that->data[$file][$line])
                    );
                }
            }
        }

        $this->tests  = \array_merge($this->tests, $that->getTests());
        $this->report = null;
    }

    public function setCacheTokens(bool $flag): void
    {
        $this->cacheTokens = $flag;
    }

    public function getCacheTokens(): bool
    {
        return $this->cacheTokens;
    }

    public function setCheckForUnintentionallyCoveredCode(bool $flag): void
    {
        $this->checkForUnintentionallyCoveredCode = $flag;
    }

    public function setForceCoversAnnotation(bool $flag): void
    {
        $this->forceCoversAnnotation = $flag;
    }

    public function setCheckForMissingCoversAnnotation(bool $flag): void
    {
        $this->checkForMissingCoversAnnotation = $flag;
    }

    public function setCheckForUnexecutedCoveredCode(bool $flag): void
    {
        $this->checkForUnexecutedCoveredCode = $flag;
    }

    public function setAddUncoveredFilesFromWhitelist(bool $flag): void
    {
        $this->addUncoveredFilesFromWhitelist = $flag;
    }

    public function setProcessUncoveredFilesFromWhitelist(bool $flag): void
    {
        $this->processUncoveredFilesFromWhitelist = $flag;
    }

    public function setDisableIgnoredLines(bool $flag): void
    {
        $this->disableIgnoredLines = $flag;
    }

    public function setIgnoreDeprecatedCode(bool $flag): void
    {
        $this->ignoreDeprecatedCode = $flag;
    }

    public function setUnintentionallyCoveredSubclassesWhitelist(array $whitelist): void
    {
        $this->unintentionallyCoveredSubclassesWhitelist = $whitelist;
    }

    /**
     * Determine the priority for a line
     *
     * 1 = the line is not set
     * 2 = the line has not been tested
     * 3 = the line is dead code
     * 4 = the line has been tested
     *
     * During a merge, a higher number is better.
     *
     * @param array $data
     * @param int   $line
     *
     * @return int
     */
    private function getLinePriority($data, $line)
    {
        if (!\array_key_exists($line, $data)) {
            return 1;
        }

        if (\is_array($data[$line]) && \count($data[$line]) === 0) {
            return 2;
        }

        if ($data[$line] === null) {
            return 3;
        }

        return 4;
    }

    /**
     * Applies the @covers annotation filtering.
     *
     * @param array|false $linesToBeCovered
     *
     * @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
     * @throws \ReflectionException
     * @throws MissingCoversAnnotationException
     * @throws UnintentionallyCoveredCodeException
     */
    private function applyCoversAnnotationFilter(array &$data, $linesToBeCovered, array $linesToBeUsed, bool $ignoreForceCoversAnnotation): void
    {
        if ($linesToBeCovered === false ||
            ($this->forceCoversAnnotation && empty($linesToBeCovered) && !$ignoreForceCoversAnnotation)) {
            if ($this->checkForMissingCoversAnnotation) {
                throw new MissingCoversAnnotationException;
            }

            $data = [];

            return;
        }

        if (empty($linesToBeCovered)) {
            return;
        }

        if ($this->checkForUnintentionallyCoveredCode &&
            (!$this->currentId instanceof TestCase ||
            (!$this->currentId->isMedium() && !$this->currentId->isLarge()))) {
            $this->performUnintentionallyCoveredCodeCheck($data, $linesToBeCovered, $linesToBeUsed);
        }

        if ($this->checkForUnexecutedCoveredCode) {
            $this->performUnexecutedCoveredCodeCheck($data, $linesToBeCovered, $linesToBeUsed);
        }

        $data = \array_intersect_key($data, $linesToBeCovered);

        foreach (\array_keys($data) as $filename) {
            $_linesToBeCovered = \array_flip($linesToBeCovered[$filename]);
            $data[$filename]   = \array_intersect_key($data[$filename], $_linesToBeCovered);
        }
    }

    private function applyWhitelistFilter(array &$data): void
    {
        foreach (\array_keys($data) as $filename) {
            if ($this->filter->isFiltered($filename)) {
                unset($data[$filename]);
            }
        }
    }

    /**
     * @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
     */
    private function applyIgnoredLinesFilter(array &$data): void
    {
        foreach (\array_keys($data) as $filename) {
            if (!$this->filter->isFile($filename)) {
                continue;
            }

            foreach ($this->getLinesToBeIgnored($filename) as $line) {
                unset($data[$filename][$line]);
            }
        }
    }

    private function initializeFilesThatAreSeenTheFirstTime(array $data): void
    {
        foreach ($data as $file => $lines) {
            if (!isset($this->data[$file]) && $this->filter->isFile($file)) {
                $this->data[$file] = [];

                foreach ($lines as $k => $v) {
                    $this->data[$file][$k] = $v === -2 ? null : [];
                }
            }
        }
    }

    /**
     * @throws CoveredCodeNotExecutedException
     * @throws InvalidArgumentException
     * @throws MissingCoversAnnotationException
     * @throws RuntimeException
     * @throws UnintentionallyCoveredCodeException
     * @throws \ReflectionException
     */
    private function addUncoveredFilesFromWhitelist(): void
    {
        $data           = [];
        $uncoveredFiles = \array_diff(
            $this->filter->getWhitelist(),
            \array_keys($this->data)
        );

        foreach ($uncoveredFiles as $uncoveredFile) {
            if (!\file_exists($uncoveredFile)) {
                continue;
            }

            $data[$uncoveredFile] = [];

            $lines = \count(\file($uncoveredFile));

            for ($i = 1; $i <= $lines; $i++) {
                $data[$uncoveredFile][$i] = Driver::LINE_NOT_EXECUTED;
            }
        }

        $this->append($data, 'UNCOVERED_FILES_FROM_WHITELIST');
    }

    private function getLinesToBeIgnored(string $fileName): array
    {
        if (isset($this->ignoredLines[$fileName])) {
            return $this->ignoredLines[$fileName];
        }

        try {
            return $this->getLinesToBeIgnoredInner($fileName);
        } catch (\OutOfBoundsException $e) {
            // This can happen with PHP_Token_Stream if the file is syntactically invalid,
            // and probably affects a file that wasn't executed.
            return [];
        }
    }

    private function getLinesToBeIgnoredInner(string $fileName): array
    {
        $this->ignoredLines[$fileName] = [];

        $lines = \file($fileName);

        foreach ($lines as $index => $line) {
            if (!\trim($line)) {
                $this->ignoredLines[$fileName][] = $index + 1;
            }
        }

        if ($this->cacheTokens) {
            $tokens = \PHP_Token_Stream_CachingFactory::get($fileName);
        } else {
            $tokens = new \PHP_Token_Stream($fileName);
        }

        foreach ($tokens->getInterfaces() as $interface) {
            $interfaceStartLine = $interface['startLine'];
            $interfaceEndLine   = $interface['endLine'];

            foreach (\range($interfaceStartLine, $interfaceEndLine) as $line) {
                $this->ignoredLines[$fileName][] = $line;
            }
        }

        foreach (\array_merge($tokens->getClasses(), $tokens->getTraits()) as $classOrTrait) {
            $classOrTraitStartLine = $classOrTrait['startLine'];
            $classOrTraitEndLine   = $classOrTrait['endLine'];

            if (empty($classOrTrait['methods'])) {
                foreach (\range($classOrTraitStartLine, $classOrTraitEndLine) as $line) {
                    $this->ignoredLines[$fileName][] = $line;
                }

                continue;
            }

            $firstMethod          = \array_shift($classOrTrait['methods']);
            $firstMethodStartLine = $firstMethod['startLine'];
            $lastMethodEndLine    = $firstMethod['endLine'];

            do {
                $lastMethod = \array_pop($classOrTrait['methods']);
            } while ($lastMethod !== null && 0 === \strpos($lastMethod['signature'], 'anonymousFunction'));

            if ($lastMethod !== null) {
                $lastMethodEndLine = $lastMethod['endLine'];
            }

            foreach (\range($classOrTraitStartLine, $firstMethodStartLine) as $line) {
                $this->ignoredLines[$fileName][] = $line;
            }

            foreach (\range($lastMethodEndLine + 1, $classOrTraitEndLine) as $line) {
                $this->ignoredLines[$fileName][] = $line;
            }
        }

        if ($this->disableIgnoredLines) {
            $this->ignoredLines[$fileName] = \array_unique($this->ignoredLines[$fileName]);
            \sort($this->ignoredLines[$fileName]);

            return $this->ignoredLines[$fileName];
        }

        $ignore = false;
        $stop   = false;

        foreach ($tokens->tokens() as $token) {
            switch (\get_class($token)) {
                case \PHP_Token_COMMENT::class:
                case \PHP_Token_DOC_COMMENT::class:
                    $_token = \trim((string) $token);
                    $_line  = \trim($lines[$token->getLine() - 1]);

                    if ($_token === '// @codeCoverageIgnore' ||
                        $_token === '//@codeCoverageIgnore') {
                        $ignore = true;
                        $stop   = true;
                    } elseif ($_token === '// @codeCoverageIgnoreStart' ||
                        $_token === '//@codeCoverageIgnoreStart') {
                        $ignore = true;
                    } elseif ($_token === '// @codeCoverageIgnoreEnd' ||
                        $_token === '//@codeCoverageIgnoreEnd') {
                        $stop = true;
                    }

                    if (!$ignore) {
                        $start = $token->getLine();
                        $end   = $start + \substr_count((string) $token, "\n");

                        // Do not ignore the first line when there is a token
                        // before the comment
                        if (0 !== \strpos($_token, $_line)) {
                            $start++;
                        }

                        for ($i = $start; $i < $end; $i++) {
                            $this->ignoredLines[$fileName][] = $i;
                        }

                        // A DOC_COMMENT token or a COMMENT token starting with "/*"
                        // does not contain the final \n character in its text
                        if (isset($lines[$i - 1]) && 0 === \strpos($_token, '/*') && '*/' === \substr(\trim($lines[$i - 1]), -2)) {
                            $this->ignoredLines[$fileName][] = $i;
                        }
                    }

                    break;

                case \PHP_Token_INTERFACE::class:
                case \PHP_Token_TRAIT::class:
                case \PHP_Token_CLASS::class:
                case \PHP_Token_FUNCTION::class:
                    /* @var \PHP_Token_Interface $token */

                    $docblock = (string) $token->getDocblock();

                    $this->ignoredLines[$fileName][] = $token->getLine();

                    if (\strpos($docblock, '@codeCoverageIgnore') || ($this->ignoreDeprecatedCode && \strpos($docblock, '@deprecated'))) {
                        $endLine = $token->getEndLine();

                        for ($i = $token->getLine(); $i <= $endLine; $i++) {
                            $this->ignoredLines[$fileName][] = $i;
                        }
                    }

                    break;

                /* @noinspection PhpMissingBreakStatementInspection */
                case \PHP_Token_NAMESPACE::class:
                    $this->ignoredLines[$fileName][] = $token->getEndLine();

                // Intentional fallthrough
                case \PHP_Token_DECLARE::class:
                case \PHP_Token_OPEN_TAG::class:
                case \PHP_Token_CLOSE_TAG::class:
                case \PHP_Token_USE::class:
                case \PHP_Token_USE_FUNCTION::class:
                    $this->ignoredLines[$fileName][] = $token->getLine();

                    break;
            }

            if ($ignore) {
                $this->ignoredLines[$fileName][] = $token->getLine();

                if ($stop) {
                    $ignore = false;
                    $stop   = false;
                }
            }
        }

        $this->ignoredLines[$fileName][] = \count($lines) + 1;

        $this->ignoredLines[$fileName] = \array_unique(
            $this->ignoredLines[$fileName]
        );

        $this->ignoredLines[$fileName] = \array_unique($this->ignoredLines[$fileName]);
        \sort($this->ignoredLines[$fileName]);

        return $this->ignoredLines[$fileName];
    }

    /**
     * @throws \ReflectionException
     * @throws UnintentionallyCoveredCodeException
     */
    private function performUnintentionallyCoveredCodeCheck(array &$data, array $linesToBeCovered, array $linesToBeUsed): void
    {
        $allowedLines = $this->getAllowedLines(
            $linesToBeCovered,
            $linesToBeUsed
        );

        $unintentionallyCoveredUnits = [];

        foreach ($data as $file => $_data) {
            foreach ($_data as $line => $flag) {
                if ($flag === 1 && !isset($allowedLines[$file][$line])) {
                    $unintentionallyCoveredUnits[] = $this->wizard->lookup($file, $line);
                }
            }
        }

        $unintentionallyCoveredUnits = $this->processUnintentionallyCoveredUnits($unintentionallyCoveredUnits);

        if (!empty($unintentionallyCoveredUnits)) {
            throw new UnintentionallyCoveredCodeException(
                $unintentionallyCoveredUnits
            );
        }
    }

    /**
     * @throws CoveredCodeNotExecutedException
     */
    private function performUnexecutedCoveredCodeCheck(array &$data, array $linesToBeCovered, array $linesToBeUsed): void
    {
        $executedCodeUnits = $this->coverageToCodeUnits($data);
        $message           = '';

        foreach ($this->linesToCodeUnits($linesToBeCovered) as $codeUnit) {
            if (!\in_array($codeUnit, $executedCodeUnits)) {
                $message .= \sprintf(
                    '- %s is expected to be executed (@covers) but was not executed' . "\n",
                    $codeUnit
                );
            }
        }

        foreach ($this->linesToCodeUnits($linesToBeUsed) as $codeUnit) {
            if (!\in_array($codeUnit, $executedCodeUnits)) {
                $message .= \sprintf(
                    '- %s is expected to be executed (@uses) but was not executed' . "\n",
                    $codeUnit
                );
            }
        }

        if (!empty($message)) {
            throw new CoveredCodeNotExecutedException($message);
        }
    }

    private function getAllowedLines(array $linesToBeCovered, array $linesToBeUsed): array
    {
        $allowedLines = [];

        foreach (\array_keys($linesToBeCovered) as $file) {
            if (!isset($allowedLines[$file])) {
                $allowedLines[$file] = [];
            }

            $allowedLines[$file] = \array_merge(
                $allowedLines[$file],
                $linesToBeCovered[$file]
            );
        }

        foreach (\array_keys($linesToBeUsed) as $file) {
            if (!isset($allowedLines[$file])) {
                $allowedLines[$file] = [];
            }

            $allowedLines[$file] = \array_merge(
                $allowedLines[$file],
                $linesToBeUsed[$file]
            );
        }

        foreach (\array_keys($allowedLines) as $file) {
            $allowedLines[$file] = \array_flip(
                \array_unique($allowedLines[$file])
            );
        }

        return $allowedLines;
    }

    /**
     * @throws RuntimeException
     */
    private function selectDriver(Filter $filter): Driver
    {
        $runtime = new Runtime;

        if ($runtime->hasPHPDBGCodeCoverage()) {
            return new PHPDBG;
        }

        if ($runtime->hasPCOV()) {
            return new PCOV;
        }

        if ($runtime->hasXdebug()) {
            return new Xdebug($filter);
        }

        throw new RuntimeException('No code coverage driver available');
    }

    private function processUnintentionallyCoveredUnits(array $unintentionallyCoveredUnits): array
    {
        $unintentionallyCoveredUnits = \array_unique($unintentionallyCoveredUnits);
        \sort($unintentionallyCoveredUnits);

        foreach (\array_keys($unintentionallyCoveredUnits) as $k => $v) {
            $unit = \explode('::', $unintentionallyCoveredUnits[$k]);

            if (\count($unit) !== 2) {
                continue;
            }

            $class = new \ReflectionClass($unit[0]);

            foreach ($this->unintentionallyCoveredSubclassesWhitelist as $whitelisted) {
                if ($class->isSubclassOf($whitelisted)) {
                    unset($unintentionallyCoveredUnits[$k]);

                    break;
                }
            }
        }

        return \array_values($unintentionallyCoveredUnits);
    }

    /**
     * @throws CoveredCodeNotExecutedException
     * @throws InvalidArgumentException
     * @throws MissingCoversAnnotationException
     * @throws RuntimeException
     * @throws UnintentionallyCoveredCodeException
     * @throws \ReflectionException
     */
    private function initializeData(): void
    {
        $this->isInitialized = true;

        if ($this->processUncoveredFilesFromWhitelist) {
            $this->shouldCheckForDeadAndUnused = false;

            $this->driver->start();

            foreach ($this->filter->getWhitelist() as $file) {
                if ($this->filter->isFile($file)) {
                    include_once $file;
                }
            }

            $data = [];

            foreach ($this->driver->stop() as $file => $fileCoverage) {
                if ($this->filter->isFiltered($file)) {
                    continue;
                }

                foreach (\array_keys($fileCoverage) as $key) {
                    if ($fileCoverage[$key] === Driver::LINE_EXECUTED) {
                        $fileCoverage[$key] = Driver::LINE_NOT_EXECUTED;
                    }
                }

                $data[$file] = $fileCoverage;
            }

            $this->append($data, 'UNCOVERED_FILES_FROM_WHITELIST');
        }
    }

    private function coverageToCodeUnits(array $data): array
    {
        $codeUnits = [];

        foreach ($data as $filename => $lines) {
            foreach ($lines as $line => $flag) {
                if ($flag === 1) {
                    $codeUnits[] = $this->wizard->lookup($filename, $line);
                }
            }
        }

        return \array_unique($codeUnits);
    }

    private function linesToCodeUnits(array $data): array
    {
        $codeUnits = [];

        foreach ($data as $filename => $lines) {
            foreach ($lines as $line) {
                $codeUnits[] = $this->wizard->lookup($filename, $line);
            }
        }

        return \array_unique($codeUnits);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Driver;

/**
 * Driver for PCOV code coverage functionality.
 *
 * @codeCoverageIgnore
 */
final class PCOV implements Driver
{
    /**
     * Start collection of code coverage information.
     */
    public function start(bool $determineUnusedAndDead = true): void
    {
        \pcov\start();
    }

    /**
     * Stop collection of code coverage information.
     */
    public function stop(): array
    {
        \pcov\stop();

        $waiting = \pcov\waiting();
        $collect = [];

        if ($waiting) {
            $collect = \pcov\collect(\pcov\inclusive, $waiting);

            \pcov\clear();
        }

        return $collect;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Driver;

/**
 * Interface for code coverage drivers.
 */
interface Driver
{
    /**
     * @var int
     *
     * @see http://xdebug.org/docs/code_coverage
     */
    public const LINE_EXECUTED = 1;

    /**
     * @var int
     *
     * @see http://xdebug.org/docs/code_coverage
     */
    public const LINE_NOT_EXECUTED = -1;

    /**
     * @var int
     *
     * @see http://xdebug.org/docs/code_coverage
     */
    public const LINE_NOT_EXECUTABLE = -2;

    /**
     * Start collection of code coverage information.
     */
    public function start(bool $determineUnusedAndDead = true): void;

    /**
     * Stop collection of code coverage information.
     */
    public function stop(): array;
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Driver;

use SebastianBergmann\CodeCoverage\RuntimeException;

/**
 * Driver for PHPDBG's code coverage functionality.
 *
 * @codeCoverageIgnore
 */
final class PHPDBG implements Driver
{
    /**
     * @throws RuntimeException
     */
    public function __construct()
    {
        if (\PHP_SAPI !== 'phpdbg') {
            throw new RuntimeException(
                'This driver requires the PHPDBG SAPI'
            );
        }

        if (!\function_exists('phpdbg_start_oplog')) {
            throw new RuntimeException(
                'This build of PHPDBG does not support code coverage'
            );
        }
    }

    /**
     * Start collection of code coverage information.
     */
    public function start(bool $determineUnusedAndDead = true): void
    {
        \phpdbg_start_oplog();
    }

    /**
     * Stop collection of code coverage information.
     */
    public function stop(): array
    {
        static $fetchedLines = [];

        $dbgData = \phpdbg_end_oplog();

        if ($fetchedLines == []) {
            $sourceLines = \phpdbg_get_executable();
        } else {
            $newFiles = \array_diff(\get_included_files(), \array_keys($fetchedLines));

            $sourceLines = [];

            if ($newFiles) {
                $sourceLines = phpdbg_get_executable(['files' => $newFiles]);
            }
        }

        foreach ($sourceLines as $file => $lines) {
            foreach ($lines as $lineNo => $numExecuted) {
                $sourceLines[$file][$lineNo] = self::LINE_NOT_EXECUTED;
            }
        }

        $fetchedLines = \array_merge($fetchedLines, $sourceLines);

        return $this->detectExecutedLines($fetchedLines, $dbgData);
    }

    /**
     * Convert phpdbg based data into the format CodeCoverage expects
     */
    private function detectExecutedLines(array $sourceLines, array $dbgData): array
    {
        foreach ($dbgData as $file => $coveredLines) {
            foreach ($coveredLines as $lineNo => $numExecuted) {
                // phpdbg also reports $lineNo=0 when e.g. exceptions get thrown.
                // make sure we only mark lines executed which are actually executable.
                if (isset($sourceLines[$file][$lineNo])) {
                    $sourceLines[$file][$lineNo] = self::LINE_EXECUTED;
                }
            }
        }

        return $sourceLines;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Driver;

use SebastianBergmann\CodeCoverage\Filter;
use SebastianBergmann\CodeCoverage\RuntimeException;

/**
 * Driver for Xdebug's code coverage functionality.
 *
 * @codeCoverageIgnore
 */
final class Xdebug implements Driver
{
    /**
     * @var array
     */
    private $cacheNumLines = [];

    /**
     * @var Filter
     */
    private $filter;

    /**
     * @throws RuntimeException
     */
    public function __construct(Filter $filter = null)
    {
        if (!\extension_loaded('xdebug')) {
            throw new RuntimeException('This driver requires Xdebug');
        }

        if (\version_compare(\phpversion('xdebug'), '3', '>=')) {
            $mode = \getenv('XDEBUG_MODE');

            if ($mode === false) {
                $mode = \ini_get('xdebug.mode');
            }

            if ($mode === false ||
                !\in_array('coverage', \explode(',', $mode), true)) {
                throw new RuntimeException('XDEBUG_MODE=coverage or xdebug.mode=coverage has to be set');
            }
        } elseif (!\ini_get('xdebug.coverage_enable')) {
            throw new RuntimeException('xdebug.coverage_enable=On has to be set');
        }

        if ($filter === null) {
            $filter = new Filter;
        }

        $this->filter = $filter;
    }

    /**
     * Start collection of code coverage information.
     */
    public function start(bool $determineUnusedAndDead = true): void
    {
        if ($determineUnusedAndDead) {
            \xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
        } else {
            \xdebug_start_code_coverage();
        }
    }

    /**
     * Stop collection of code coverage information.
     */
    public function stop(): array
    {
        $data = \xdebug_get_code_coverage();

        \xdebug_stop_code_coverage();

        return $this->cleanup($data);
    }

    private function cleanup(array $data): array
    {
        foreach (\array_keys($data) as $file) {
            unset($data[$file][0]);

            if (!$this->filter->isFile($file)) {
                continue;
            }

            $numLines = $this->getNumberOfLinesInFile($file);

            foreach (\array_keys($data[$file]) as $line) {
                if ($line > $numLines) {
                    unset($data[$file][$line]);
                }
            }
        }

        return $data;
    }

    private function getNumberOfLinesInFile(string $fileName): int
    {
        if (!isset($this->cacheNumLines[$fileName])) {
            $buffer = \file_get_contents($fileName);
            $lines  = \substr_count($buffer, "\n");

            if (\substr($buffer, -1) !== "\n") {
                $lines++;
            }

            $this->cacheNumLines[$fileName] = $lines;
        }

        return $this->cacheNumLines[$fileName];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use SebastianBergmann\Version as VersionId;

final class Version
{
    /**
     * @var string
     */
    private static $version;

    public static function id(): string
    {
        if (self::$version === null) {
            $version       = new VersionId('7.0.15', \dirname(__DIR__));
            self::$version = $version->getVersion();
        }

        return self::$version;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;

/**
 * Filter for whitelisting of code coverage information.
 */
final class Filter
{
    /**
     * Source files that are whitelisted.
     *
     * @var array
     */
    private $whitelistedFiles = [];

    /**
     * Remembers the result of the `is_file()` calls.
     *
     * @var bool[]
     */
    private $isFileCallsCache = [];

    /**
     * Adds a directory to the whitelist (recursively).
     */
    public function addDirectoryToWhitelist(string $directory, string $suffix = '.php', string $prefix = ''): void
    {
        $facade = new FileIteratorFacade;
        $files  = $facade->getFilesAsArray($directory, $suffix, $prefix);

        foreach ($files as $file) {
            $this->addFileToWhitelist($file);
        }
    }

    /**
     * Adds a file to the whitelist.
     */
    public function addFileToWhitelist(string $filename): void
    {
        $filename = \realpath($filename);

        if (!$filename) {
            return;
        }

        $this->whitelistedFiles[$filename] = true;
    }

    /**
     * Adds files to the whitelist.
     *
     * @param string[] $files
     */
    public function addFilesToWhitelist(array $files): void
    {
        foreach ($files as $file) {
            $this->addFileToWhitelist($file);
        }
    }

    /**
     * Removes a directory from the whitelist (recursively).
     */
    public function removeDirectoryFromWhitelist(string $directory, string $suffix = '.php', string $prefix = ''): void
    {
        $facade = new FileIteratorFacade;
        $files  = $facade->getFilesAsArray($directory, $suffix, $prefix);

        foreach ($files as $file) {
            $this->removeFileFromWhitelist($file);
        }
    }

    /**
     * Removes a file from the whitelist.
     */
    public function removeFileFromWhitelist(string $filename): void
    {
        $filename = \realpath($filename);

        if (!$filename || !isset($this->whitelistedFiles[$filename])) {
            return;
        }

        unset($this->whitelistedFiles[$filename]);
    }

    /**
     * Checks whether a filename is a real filename.
     */
    public function isFile(string $filename): bool
    {
        if (isset($this->isFileCallsCache[$filename])) {
            return $this->isFileCallsCache[$filename];
        }

        if ($filename === '-' ||
            \strpos($filename, 'vfs://') === 0 ||
            \strpos($filename, 'xdebug://debug-eval') !== false ||
            \strpos($filename, 'eval()\'d code') !== false ||
            \strpos($filename, 'runtime-created function') !== false ||
            \strpos($filename, 'runkit created function') !== false ||
            \strpos($filename, 'assert code') !== false ||
            \strpos($filename, 'regexp code') !== false ||
            \strpos($filename, 'Standard input code') !== false) {
            $isFile = false;
        } else {
            $isFile = \file_exists($filename);
        }

        $this->isFileCallsCache[$filename] = $isFile;

        return $isFile;
    }

    /**
     * Checks whether or not a file is filtered.
     */
    public function isFiltered(string $filename): bool
    {
        if (!$this->isFile($filename)) {
            return true;
        }

        return !isset($this->whitelistedFiles[$filename]);
    }

    /**
     * Returns the list of whitelisted files.
     *
     * @return string[]
     */
    public function getWhitelist(): array
    {
        return \array_keys($this->whitelistedFiles);
    }

    /**
     * Returns whether this filter has a whitelist.
     */
    public function hasWhitelist(): bool
    {
        return !empty($this->whitelistedFiles);
    }

    /**
     * Returns the whitelisted files.
     *
     * @return string[]
     */
    public function getWhitelistedFiles(): array
    {
        return $this->whitelistedFiles;
    }

    /**
     * Sets the whitelisted files.
     */
    public function setWhitelistedFiles(array $whitelistedFiles): void
    {
        $this->whitelistedFiles = $whitelistedFiles;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\RuntimeException;

/**
 * Generates a Clover XML logfile from a code coverage object.
 */
final class Clover
{
    /**
     * @throws \RuntimeException
     */
    public function process(CodeCoverage $coverage, ?string $target = null, ?string $name = null): string
    {
        $xmlDocument               = new \DOMDocument('1.0', 'UTF-8');
        $xmlDocument->formatOutput = true;

        $xmlCoverage = $xmlDocument->createElement('coverage');
        $xmlCoverage->setAttribute('generated', (string) $_SERVER['REQUEST_TIME']);
        $xmlDocument->appendChild($xmlCoverage);

        $xmlProject = $xmlDocument->createElement('project');
        $xmlProject->setAttribute('timestamp', (string) $_SERVER['REQUEST_TIME']);

        if (\is_string($name)) {
            $xmlProject->setAttribute('name', $name);
        }

        $xmlCoverage->appendChild($xmlProject);

        $packages = [];
        $report   = $coverage->getReport();

        foreach ($report as $item) {
            if (!$item instanceof File) {
                continue;
            }

            /* @var File $item */

            $xmlFile = $xmlDocument->createElement('file');
            $xmlFile->setAttribute('name', $item->getPath());

            $classes      = $item->getClassesAndTraits();
            $coverageData = $item->getCoverageData();
            $lines        = [];
            $namespace    = 'global';

            foreach ($classes as $className => $class) {
                $classStatements        = 0;
                $coveredClassStatements = 0;
                $coveredMethods         = 0;
                $classMethods           = 0;

                foreach ($class['methods'] as $methodName => $method) {
                    if ($method['executableLines'] == 0) {
                        continue;
                    }

                    $classMethods++;
                    $classStatements += $method['executableLines'];
                    $coveredClassStatements += $method['executedLines'];

                    if ($method['coverage'] == 100) {
                        $coveredMethods++;
                    }

                    $methodCount = 0;

                    foreach (\range($method['startLine'], $method['endLine']) as $line) {
                        if (isset($coverageData[$line]) && ($coverageData[$line] !== null)) {
                            $methodCount = \max($methodCount, \count($coverageData[$line]));
                        }
                    }

                    $lines[$method['startLine']] = [
                        'ccn'         => $method['ccn'],
                        'count'       => $methodCount,
                        'crap'        => $method['crap'],
                        'type'        => 'method',
                        'visibility'  => $method['visibility'],
                        'name'        => $methodName,
                    ];
                }

                if (!empty($class['package']['namespace'])) {
                    $namespace = $class['package']['namespace'];
                }

                $xmlClass = $xmlDocument->createElement('class');
                $xmlClass->setAttribute('name', $className);
                $xmlClass->setAttribute('namespace', $namespace);

                if (!empty($class['package']['fullPackage'])) {
                    $xmlClass->setAttribute(
                        'fullPackage',
                        $class['package']['fullPackage']
                    );
                }

                if (!empty($class['package']['category'])) {
                    $xmlClass->setAttribute(
                        'category',
                        $class['package']['category']
                    );
                }

                if (!empty($class['package']['package'])) {
                    $xmlClass->setAttribute(
                        'package',
                        $class['package']['package']
                    );
                }

                if (!empty($class['package']['subpackage'])) {
                    $xmlClass->setAttribute(
                        'subpackage',
                        $class['package']['subpackage']
                    );
                }

                $xmlFile->appendChild($xmlClass);

                $xmlMetrics = $xmlDocument->createElement('metrics');
                $xmlMetrics->setAttribute('complexity', (string) $class['ccn']);
                $xmlMetrics->setAttribute('methods', (string) $classMethods);
                $xmlMetrics->setAttribute('coveredmethods', (string) $coveredMethods);
                $xmlMetrics->setAttribute('conditionals', '0');
                $xmlMetrics->setAttribute('coveredconditionals', '0');
                $xmlMetrics->setAttribute('statements', (string) $classStatements);
                $xmlMetrics->setAttribute('coveredstatements', (string) $coveredClassStatements);
                $xmlMetrics->setAttribute('elements', (string) ($classMethods + $classStatements /* + conditionals */));
                $xmlMetrics->setAttribute('coveredelements', (string) ($coveredMethods + $coveredClassStatements /* + coveredconditionals */));
                $xmlClass->appendChild($xmlMetrics);
            }

            foreach ($coverageData as $line => $data) {
                if ($data === null || isset($lines[$line])) {
                    continue;
                }

                $lines[$line] = [
                    'count' => \count($data), 'type' => 'stmt',
                ];
            }

            \ksort($lines);

            foreach ($lines as $line => $data) {
                $xmlLine = $xmlDocument->createElement('line');
                $xmlLine->setAttribute('num', (string) $line);
                $xmlLine->setAttribute('type', $data['type']);

                if (isset($data['name'])) {
                    $xmlLine->setAttribute('name', $data['name']);
                }

                if (isset($data['visibility'])) {
                    $xmlLine->setAttribute('visibility', $data['visibility']);
                }

                if (isset($data['ccn'])) {
                    $xmlLine->setAttribute('complexity', (string) $data['ccn']);
                }

                if (isset($data['crap'])) {
                    $xmlLine->setAttribute('crap', (string) $data['crap']);
                }

                $xmlLine->setAttribute('count', (string) $data['count']);
                $xmlFile->appendChild($xmlLine);
            }

            $linesOfCode = $item->getLinesOfCode();

            $xmlMetrics = $xmlDocument->createElement('metrics');
            $xmlMetrics->setAttribute('loc', (string) $linesOfCode['loc']);
            $xmlMetrics->setAttribute('ncloc', (string) $linesOfCode['ncloc']);
            $xmlMetrics->setAttribute('classes', (string) $item->getNumClassesAndTraits());
            $xmlMetrics->setAttribute('methods', (string) $item->getNumMethods());
            $xmlMetrics->setAttribute('coveredmethods', (string) $item->getNumTestedMethods());
            $xmlMetrics->setAttribute('conditionals', '0');
            $xmlMetrics->setAttribute('coveredconditionals', '0');
            $xmlMetrics->setAttribute('statements', (string) $item->getNumExecutableLines());
            $xmlMetrics->setAttribute('coveredstatements', (string) $item->getNumExecutedLines());
            $xmlMetrics->setAttribute('elements', (string) ($item->getNumMethods() + $item->getNumExecutableLines() /* + conditionals */));
            $xmlMetrics->setAttribute('coveredelements', (string) ($item->getNumTestedMethods() + $item->getNumExecutedLines() /* + coveredconditionals */));
            $xmlFile->appendChild($xmlMetrics);

            if ($namespace === 'global') {
                $xmlProject->appendChild($xmlFile);
            } else {
                if (!isset($packages[$namespace])) {
                    $packages[$namespace] = $xmlDocument->createElement(
                        'package'
                    );

                    $packages[$namespace]->setAttribute('name', $namespace);
                    $xmlProject->appendChild($packages[$namespace]);
                }

                $packages[$namespace]->appendChild($xmlFile);
            }
        }

        $linesOfCode = $report->getLinesOfCode();

        $xmlMetrics = $xmlDocument->createElement('metrics');
        $xmlMetrics->setAttribute('files', (string) \count($report));
        $xmlMetrics->setAttribute('loc', (string) $linesOfCode['loc']);
        $xmlMetrics->setAttribute('ncloc', (string) $linesOfCode['ncloc']);
        $xmlMetrics->setAttribute('classes', (string) $report->getNumClassesAndTraits());
        $xmlMetrics->setAttribute('methods', (string) $report->getNumMethods());
        $xmlMetrics->setAttribute('coveredmethods', (string) $report->getNumTestedMethods());
        $xmlMetrics->setAttribute('conditionals', '0');
        $xmlMetrics->setAttribute('coveredconditionals', '0');
        $xmlMetrics->setAttribute('statements', (string) $report->getNumExecutableLines());
        $xmlMetrics->setAttribute('coveredstatements', (string) $report->getNumExecutedLines());
        $xmlMetrics->setAttribute('elements', (string) ($report->getNumMethods() + $report->getNumExecutableLines() /* + conditionals */));
        $xmlMetrics->setAttribute('coveredelements', (string) ($report->getNumTestedMethods() + $report->getNumExecutedLines() /* + coveredconditionals */));
        $xmlProject->appendChild($xmlMetrics);

        $buffer = $xmlDocument->saveXML();

        if ($target !== null) {
            if (!$this->createDirectory(\dirname($target))) {
                throw new \RuntimeException(\sprintf('Directory "%s" was not created', \dirname($target)));
            }

            if (@\file_put_contents($target, $buffer) === false) {
                throw new RuntimeException(
                    \sprintf(
                        'Could not write to "%s',
                        $target
                    )
                );
            }
        }

        return $buffer;
    }

    private function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\Node\AbstractNode;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;

/**
 * Renders the dashboard for a directory node.
 */
final class Dashboard extends Renderer
{
    /**
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function render(DirectoryNode $node, string $file): void
    {
        $classes  = $node->getClassesAndTraits();
        $template = new \Text_Template(
            $this->templatePath . 'dashboard.html',
            '{{',
            '}}'
        );

        $this->setCommonTemplateVariables($template, $node);

        $baseLink             = $node->getId() . '/';
        $complexity           = $this->complexity($classes, $baseLink);
        $coverageDistribution = $this->coverageDistribution($classes);
        $insufficientCoverage = $this->insufficientCoverage($classes, $baseLink);
        $projectRisks         = $this->projectRisks($classes, $baseLink);

        $template->setVar(
            [
                'insufficient_coverage_classes' => $insufficientCoverage['class'],
                'insufficient_coverage_methods' => $insufficientCoverage['method'],
                'project_risks_classes'         => $projectRisks['class'],
                'project_risks_methods'         => $projectRisks['method'],
                'complexity_class'              => $complexity['class'],
                'complexity_method'             => $complexity['method'],
                'class_coverage_distribution'   => $coverageDistribution['class'],
                'method_coverage_distribution'  => $coverageDistribution['method'],
            ]
        );

        $template->renderTo($file);
    }

    /**
     * Returns the data for the Class/Method Complexity charts.
     */
    protected function complexity(array $classes, string $baseLink): array
    {
        $result = ['class' => [], 'method' => []];

        foreach ($classes as $className => $class) {
            foreach ($class['methods'] as $methodName => $method) {
                if ($className !== '*') {
                    $methodName = $className . '::' . $methodName;
                }

                $result['method'][] = [
                    $method['coverage'],
                    $method['ccn'],
                    \sprintf(
                        '<a href="%s">%s</a>',
                        \str_replace($baseLink, '', $method['link']),
                        $methodName
                    ),
                ];
            }

            $result['class'][] = [
                $class['coverage'],
                $class['ccn'],
                \sprintf(
                    '<a href="%s">%s</a>',
                    \str_replace($baseLink, '', $class['link']),
                    $className
                ),
            ];
        }

        return [
            'class'  => \json_encode($result['class']),
            'method' => \json_encode($result['method']),
        ];
    }

    /**
     * Returns the data for the Class / Method Coverage Distribution chart.
     */
    protected function coverageDistribution(array $classes): array
    {
        $result = [
            'class' => [
                '0%'      => 0,
                '0-10%'   => 0,
                '10-20%'  => 0,
                '20-30%'  => 0,
                '30-40%'  => 0,
                '40-50%'  => 0,
                '50-60%'  => 0,
                '60-70%'  => 0,
                '70-80%'  => 0,
                '80-90%'  => 0,
                '90-100%' => 0,
                '100%'    => 0,
            ],
            'method' => [
                '0%'      => 0,
                '0-10%'   => 0,
                '10-20%'  => 0,
                '20-30%'  => 0,
                '30-40%'  => 0,
                '40-50%'  => 0,
                '50-60%'  => 0,
                '60-70%'  => 0,
                '70-80%'  => 0,
                '80-90%'  => 0,
                '90-100%' => 0,
                '100%'    => 0,
            ],
        ];

        foreach ($classes as $class) {
            foreach ($class['methods'] as $methodName => $method) {
                if ($method['coverage'] === 0) {
                    $result['method']['0%']++;
                } elseif ($method['coverage'] === 100) {
                    $result['method']['100%']++;
                } else {
                    $key = \floor($method['coverage'] / 10) * 10;
                    $key = $key . '-' . ($key + 10) . '%';
                    $result['method'][$key]++;
                }
            }

            if ($class['coverage'] === 0) {
                $result['class']['0%']++;
            } elseif ($class['coverage'] === 100) {
                $result['class']['100%']++;
            } else {
                $key = \floor($class['coverage'] / 10) * 10;
                $key = $key . '-' . ($key + 10) . '%';
                $result['class'][$key]++;
            }
        }

        return [
            'class'  => \json_encode(\array_values($result['class'])),
            'method' => \json_encode(\array_values($result['method'])),
        ];
    }

    /**
     * Returns the classes / methods with insufficient coverage.
     */
    protected function insufficientCoverage(array $classes, string $baseLink): array
    {
        $leastTestedClasses = [];
        $leastTestedMethods = [];
        $result             = ['class' => '', 'method' => ''];

        foreach ($classes as $className => $class) {
            foreach ($class['methods'] as $methodName => $method) {
                if ($method['coverage'] < $this->highLowerBound) {
                    $key = $methodName;

                    if ($className !== '*') {
                        $key = $className . '::' . $methodName;
                    }

                    $leastTestedMethods[$key] = $method['coverage'];
                }
            }

            if ($class['coverage'] < $this->highLowerBound) {
                $leastTestedClasses[$className] = $class['coverage'];
            }
        }

        \asort($leastTestedClasses);
        \asort($leastTestedMethods);

        foreach ($leastTestedClasses as $className => $coverage) {
            $result['class'] .= \sprintf(
                '       <tr><td><a href="%s">%s</a></td><td class="text-right">%d%%</td></tr>' . "\n",
                \str_replace($baseLink, '', $classes[$className]['link']),
                $className,
                $coverage
            );
        }

        foreach ($leastTestedMethods as $methodName => $coverage) {
            [$class, $method] = \explode('::', $methodName);

            $result['method'] .= \sprintf(
                '       <tr><td><a href="%s"><abbr title="%s">%s</abbr></a></td><td class="text-right">%d%%</td></tr>' . "\n",
                \str_replace($baseLink, '', $classes[$class]['methods'][$method]['link']),
                $methodName,
                $method,
                $coverage
            );
        }

        return $result;
    }

    /**
     * Returns the project risks according to the CRAP index.
     */
    protected function projectRisks(array $classes, string $baseLink): array
    {
        $classRisks  = [];
        $methodRisks = [];
        $result      = ['class' => '', 'method' => ''];

        foreach ($classes as $className => $class) {
            foreach ($class['methods'] as $methodName => $method) {
                if ($method['coverage'] < $this->highLowerBound && $method['ccn'] > 1) {
                    $key = $methodName;

                    if ($className !== '*') {
                        $key = $className . '::' . $methodName;
                    }

                    $methodRisks[$key] = $method['crap'];
                }
            }

            if ($class['coverage'] < $this->highLowerBound &&
                $class['ccn'] > \count($class['methods'])) {
                $classRisks[$className] = $class['crap'];
            }
        }

        \arsort($classRisks);
        \arsort($methodRisks);

        foreach ($classRisks as $className => $crap) {
            $result['class'] .= \sprintf(
                '       <tr><td><a href="%s">%s</a></td><td class="text-right">%d</td></tr>' . "\n",
                \str_replace($baseLink, '', $classes[$className]['link']),
                $className,
                $crap
            );
        }

        foreach ($methodRisks as $methodName => $crap) {
            [$class, $method] = \explode('::', $methodName);

            $result['method'] .= \sprintf(
                '       <tr><td><a href="%s"><abbr title="%s">%s</abbr></a></td><td class="text-right">%d</td></tr>' . "\n",
                \str_replace($baseLink, '', $classes[$class]['methods'][$method]['link']),
                $methodName,
                $method,
                $crap
            );
        }

        return $result;
    }

    protected function getActiveBreadcrumb(AbstractNode $node): string
    {
        return \sprintf(
            '         <li class="breadcrumb-item"><a href="index.html">%s</a></li>' . "\n" .
            '         <li class="breadcrumb-item active">(Dashboard)</li>' . "\n",
            $node->getName()
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\Node\File as FileNode;
use SebastianBergmann\CodeCoverage\Util;

/**
 * Renders a file node.
 */
final class File extends Renderer
{
    /**
     * @var int
     */
    private $htmlSpecialCharsFlags = \ENT_COMPAT | \ENT_HTML401 | \ENT_SUBSTITUTE;

    /**
     * @throws \RuntimeException
     */
    public function render(FileNode $node, string $file): void
    {
        $template = new \Text_Template($this->templatePath . 'file.html', '{{', '}}');

        $template->setVar(
            [
                'items' => $this->renderItems($node),
                'lines' => $this->renderSource($node),
            ]
        );

        $this->setCommonTemplateVariables($template, $node);

        $template->renderTo($file);
    }

    protected function renderItems(FileNode $node): string
    {
        $template = new \Text_Template($this->templatePath . 'file_item.html', '{{', '}}');

        $methodItemTemplate = new \Text_Template(
            $this->templatePath . 'method_item.html',
            '{{',
            '}}'
        );

        $items = $this->renderItemTemplate(
            $template,
            [
                'name'                         => 'Total',
                'numClasses'                   => $node->getNumClassesAndTraits(),
                'numTestedClasses'             => $node->getNumTestedClassesAndTraits(),
                'numMethods'                   => $node->getNumFunctionsAndMethods(),
                'numTestedMethods'             => $node->getNumTestedFunctionsAndMethods(),
                'linesExecutedPercent'         => $node->getLineExecutedPercent(false),
                'linesExecutedPercentAsString' => $node->getLineExecutedPercent(),
                'numExecutedLines'             => $node->getNumExecutedLines(),
                'numExecutableLines'           => $node->getNumExecutableLines(),
                'testedMethodsPercent'         => $node->getTestedFunctionsAndMethodsPercent(false),
                'testedMethodsPercentAsString' => $node->getTestedFunctionsAndMethodsPercent(),
                'testedClassesPercent'         => $node->getTestedClassesAndTraitsPercent(false),
                'testedClassesPercentAsString' => $node->getTestedClassesAndTraitsPercent(),
                'crap'                         => '<abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr>',
            ]
        );

        $items .= $this->renderFunctionItems(
            $node->getFunctions(),
            $methodItemTemplate
        );

        $items .= $this->renderTraitOrClassItems(
            $node->getTraits(),
            $template,
            $methodItemTemplate
        );

        $items .= $this->renderTraitOrClassItems(
            $node->getClasses(),
            $template,
            $methodItemTemplate
        );

        return $items;
    }

    protected function renderTraitOrClassItems(array $items, \Text_Template $template, \Text_Template $methodItemTemplate): string
    {
        $buffer = '';

        if (empty($items)) {
            return $buffer;
        }

        foreach ($items as $name => $item) {
            $numMethods       = 0;
            $numTestedMethods = 0;

            foreach ($item['methods'] as $method) {
                if ($method['executableLines'] > 0) {
                    $numMethods++;

                    if ($method['executedLines'] === $method['executableLines']) {
                        $numTestedMethods++;
                    }
                }
            }

            if ($item['executableLines'] > 0) {
                $numClasses                   = 1;
                $numTestedClasses             = $numTestedMethods == $numMethods ? 1 : 0;
                $linesExecutedPercentAsString = Util::percent(
                    $item['executedLines'],
                    $item['executableLines'],
                    true
                );
            } else {
                $numClasses                   = 'n/a';
                $numTestedClasses             = 'n/a';
                $linesExecutedPercentAsString = 'n/a';
            }

            $buffer .= $this->renderItemTemplate(
                $template,
                [
                    'name'                         => $this->abbreviateClassName($name),
                    'numClasses'                   => $numClasses,
                    'numTestedClasses'             => $numTestedClasses,
                    'numMethods'                   => $numMethods,
                    'numTestedMethods'             => $numTestedMethods,
                    'linesExecutedPercent'         => Util::percent(
                        $item['executedLines'],
                        $item['executableLines'],
                        false
                    ),
                    'linesExecutedPercentAsString' => $linesExecutedPercentAsString,
                    'numExecutedLines'             => $item['executedLines'],
                    'numExecutableLines'           => $item['executableLines'],
                    'testedMethodsPercent'         => Util::percent(
                        $numTestedMethods,
                        $numMethods
                    ),
                    'testedMethodsPercentAsString' => Util::percent(
                        $numTestedMethods,
                        $numMethods,
                        true
                    ),
                    'testedClassesPercent'         => Util::percent(
                        $numTestedMethods == $numMethods ? 1 : 0,
                        1
                    ),
                    'testedClassesPercentAsString' => Util::percent(
                        $numTestedMethods == $numMethods ? 1 : 0,
                        1,
                        true
                    ),
                    'crap'                         => $item['crap'],
                ]
            );

            foreach ($item['methods'] as $method) {
                $buffer .= $this->renderFunctionOrMethodItem(
                    $methodItemTemplate,
                    $method,
                    '&nbsp;'
                );
            }
        }

        return $buffer;
    }

    protected function renderFunctionItems(array $functions, \Text_Template $template): string
    {
        if (empty($functions)) {
            return '';
        }

        $buffer = '';

        foreach ($functions as $function) {
            $buffer .= $this->renderFunctionOrMethodItem(
                $template,
                $function
            );
        }

        return $buffer;
    }

    protected function renderFunctionOrMethodItem(\Text_Template $template, array $item, string $indent = ''): string
    {
        $numMethods       = 0;
        $numTestedMethods = 0;

        if ($item['executableLines'] > 0) {
            $numMethods = 1;

            if ($item['executedLines'] === $item['executableLines']) {
                $numTestedMethods = 1;
            }
        }

        return $this->renderItemTemplate(
            $template,
            [
                'name'                         => \sprintf(
                    '%s<a href="#%d"><abbr title="%s">%s</abbr></a>',
                    $indent,
                    $item['startLine'],
                    \htmlspecialchars($item['signature'], $this->htmlSpecialCharsFlags),
                    $item['functionName'] ?? $item['methodName']
                ),
                'numMethods'                   => $numMethods,
                'numTestedMethods'             => $numTestedMethods,
                'linesExecutedPercent'         => Util::percent(
                    $item['executedLines'],
                    $item['executableLines']
                ),
                'linesExecutedPercentAsString' => Util::percent(
                    $item['executedLines'],
                    $item['executableLines'],
                    true
                ),
                'numExecutedLines'             => $item['executedLines'],
                'numExecutableLines'           => $item['executableLines'],
                'testedMethodsPercent'         => Util::percent(
                    $numTestedMethods,
                    1
                ),
                'testedMethodsPercentAsString' => Util::percent(
                    $numTestedMethods,
                    1,
                    true
                ),
                'crap'                         => $item['crap'],
            ]
        );
    }

    protected function renderSource(FileNode $node): string
    {
        $coverageData = $node->getCoverageData();
        $testData     = $node->getTestData();
        $codeLines    = $this->loadFile($node->getPath());
        $lines        = '';
        $i            = 1;

        foreach ($codeLines as $line) {
            $trClass        = '';
            $popoverContent = '';
            $popoverTitle   = '';

            if (\array_key_exists($i, $coverageData)) {
                $numTests = ($coverageData[$i] ? \count($coverageData[$i]) : 0);

                if ($coverageData[$i] === null) {
                    $trClass = ' class="warning"';
                } elseif ($numTests == 0) {
                    $trClass = ' class="danger"';
                } else {
                    $lineCss        = 'covered-by-large-tests';
                    $popoverContent = '<ul>';

                    if ($numTests > 1) {
                        $popoverTitle = $numTests . ' tests cover line ' . $i;
                    } else {
                        $popoverTitle = '1 test covers line ' . $i;
                    }

                    foreach ($coverageData[$i] as $test) {
                        if ($lineCss == 'covered-by-large-tests' && $testData[$test]['size'] == 'medium') {
                            $lineCss = 'covered-by-medium-tests';
                        } elseif ($testData[$test]['size'] == 'small') {
                            $lineCss = 'covered-by-small-tests';
                        }

                        switch ($testData[$test]['status']) {
                            case 0:
                                switch ($testData[$test]['size']) {
                                    case 'small':
                                        $testCSS = ' class="covered-by-small-tests"';

                                        break;

                                    case 'medium':
                                        $testCSS = ' class="covered-by-medium-tests"';

                                        break;

                                    default:
                                        $testCSS = ' class="covered-by-large-tests"';

                                        break;
                                }

                                break;

                            case 1:
                            case 2:
                                $testCSS = ' class="warning"';

                                break;

                            case 3:
                                $testCSS = ' class="danger"';

                                break;

                            case 4:
                                $testCSS = ' class="danger"';

                                break;

                            default:
                                $testCSS = '';
                        }

                        $popoverContent .= \sprintf(
                            '<li%s>%s</li>',
                            $testCSS,
                            \htmlspecialchars($test, $this->htmlSpecialCharsFlags)
                        );
                    }

                    $popoverContent .= '</ul>';
                    $trClass         = ' class="' . $lineCss . ' popin"';
                }
            }

            $popover = '';

            if (!empty($popoverTitle)) {
                $popover = \sprintf(
                    ' data-title="%s" data-content="%s" data-placement="top" data-html="true"',
                    $popoverTitle,
                    \htmlspecialchars($popoverContent, $this->htmlSpecialCharsFlags)
                );
            }

            $lines .= \sprintf(
                '     <tr%s><td%s><div align="right"><a name="%d"></a><a href="#%d">%d</a></div></td><td class="codeLine">%s</td></tr>' . "\n",
                $trClass,
                $popover,
                $i,
                $i,
                $i,
                $line
            );

            $i++;
        }

        return $lines;
    }

    /**
     * @param string $file
     */
    protected function loadFile($file): array
    {
        $buffer              = \file_get_contents($file);
        $tokens              = \token_get_all($buffer);
        $result              = [''];
        $i                   = 0;
        $stringFlag          = false;
        $fileEndsWithNewLine = \substr($buffer, -1) == "\n";

        unset($buffer);

        foreach ($tokens as $j => $token) {
            if (\is_string($token)) {
                if ($token === '"' && $tokens[$j - 1] !== '\\') {
                    $result[$i] .= \sprintf(
                        '<span class="string">%s</span>',
                        \htmlspecialchars($token, $this->htmlSpecialCharsFlags)
                    );

                    $stringFlag = !$stringFlag;
                } else {
                    $result[$i] .= \sprintf(
                        '<span class="keyword">%s</span>',
                        \htmlspecialchars($token, $this->htmlSpecialCharsFlags)
                    );
                }

                continue;
            }

            [$token, $value] = $token;

            $value = \str_replace(
                ["\t", ' '],
                ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;'],
                \htmlspecialchars($value, $this->htmlSpecialCharsFlags)
            );

            if ($value === "\n") {
                $result[++$i] = '';
            } else {
                $lines = \explode("\n", $value);

                foreach ($lines as $jj => $line) {
                    $line = \trim($line);

                    if ($line !== '') {
                        if ($stringFlag) {
                            $colour = 'string';
                        } else {
                            switch ($token) {
                                case \T_INLINE_HTML:
                                    $colour = 'html';

                                    break;

                                case \T_COMMENT:
                                case \T_DOC_COMMENT:
                                    $colour = 'comment';

                                    break;

                                case \T_ABSTRACT:
                                case \T_ARRAY:
                                case \T_AS:
                                case \T_BREAK:
                                case \T_CALLABLE:
                                case \T_CASE:
                                case \T_CATCH:
                                case \T_CLASS:
                                case \T_CLONE:
                                case \T_CONTINUE:
                                case \T_DEFAULT:
                                case \T_ECHO:
                                case \T_ELSE:
                                case \T_ELSEIF:
                                case \T_EMPTY:
                                case \T_ENDDECLARE:
                                case \T_ENDFOR:
                                case \T_ENDFOREACH:
                                case \T_ENDIF:
                                case \T_ENDSWITCH:
                                case \T_ENDWHILE:
                                case \T_EXIT:
                                case \T_EXTENDS:
                                case \T_FINAL:
                                case \T_FINALLY:
                                case \T_FOREACH:
                                case \T_FUNCTION:
                                case \T_GLOBAL:
                                case \T_IF:
                                case \T_IMPLEMENTS:
                                case \T_INCLUDE:
                                case \T_INCLUDE_ONCE:
                                case \T_INSTANCEOF:
                                case \T_INSTEADOF:
                                case \T_INTERFACE:
                                case \T_ISSET:
                                case \T_LOGICAL_AND:
                                case \T_LOGICAL_OR:
                                case \T_LOGICAL_XOR:
                                case \T_NAMESPACE:
                                case \T_NEW:
                                case \T_PRIVATE:
                                case \T_PROTECTED:
                                case \T_PUBLIC:
                                case \T_REQUIRE:
                                case \T_REQUIRE_ONCE:
                                case \T_RETURN:
                                case \T_STATIC:
                                case \T_THROW:
                                case \T_TRAIT:
                                case \T_TRY:
                                case \T_UNSET:
                                case \T_USE:
                                case \T_VAR:
                                case \T_WHILE:
                                case \T_YIELD:
                                    $colour = 'keyword';

                                    break;

                                default:
                                    $colour = 'default';
                            }
                        }

                        $result[$i] .= \sprintf(
                            '<span class="%s">%s</span>',
                            $colour,
                            $line
                        );
                    }

                    if (isset($lines[$jj + 1])) {
                        $result[++$i] = '';
                    }
                }
            }
        }

        if ($fileEndsWithNewLine) {
            unset($result[\count($result) - 1]);
        }

        return $result;
    }

    private function abbreviateClassName(string $className): string
    {
        $tmp = \explode('\\', $className);

        if (\count($tmp) > 1) {
            $className = \sprintf(
                '<abbr title="%s">%s</abbr>',
                $className,
                \array_pop($tmp)
            );
        }

        return $className;
    }
}
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Dashboard for {{full_path}}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{{path_to_root}}_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/nv.d3.min.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/style.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
{{breadcrumbs}}
       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="row">
    <div class="col-md-12">
     <h2>Classes</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="classCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="classComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
{{insufficient_coverage_classes}}
       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Class</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>
{{project_risks_classes}}
       </tbody>
      </table>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-12">
     <h2>Methods</h2>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Coverage Distribution</h3>
     <div id="methodCoverageDistribution" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Complexity</h3>
     <div id="methodComplexity" style="height: 300px;">
       <svg></svg>
     </div>
    </div>
   </div>
   <div class="row">
    <div class="col-md-6">
     <h3>Insufficient Coverage</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right">Coverage</th>
        </tr>
       </thead>
       <tbody>
{{insufficient_coverage_methods}}
       </tbody>
      </table>
     </div>
    </div>
    <div class="col-md-6">
     <h3>Project Risks</h3>
     <div class="scrollbox">
      <table class="table">
       <thead>
        <tr>
         <th>Method</th>
         <th class="text-right"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></th>
        </tr>
       </thead>
       <tbody>
{{project_risks_methods}}
       </tbody>
      </table>
     </div>
    </div>
   </div>
   <footer>
    <hr/>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage {{version}}</a> using {{runtime}}{{generator}} at {{date}}.</small>
    </p>
   </footer>
  </div>
  <script src="{{path_to_root}}_js/jquery.min.js" type="text/javascript"></script>
  <script src="{{path_to_root}}_js/d3.min.js" type="text/javascript"></script>
  <script src="{{path_to_root}}_js/nv.d3.min.js" type="text/javascript"></script>
  <script type="text/javascript">
$(document).ready(function() {
  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#classCoverageDistribution svg')
      .datum(getCoverageDistributionData({{class_coverage_distribution}}, "Class Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.multiBarChart();
    chart.tooltips(false)
      .showControls(false)
      .showLegend(false)
      .reduceXTicks(false)
      .staggerLabels(true)
      .yAxis.tickFormat(d3.format('d'));

    d3.select('#methodCoverageDistribution svg')
      .datum(getCoverageDistributionData({{method_coverage_distribution}}, "Method Coverage"))
      .transition().duration(500).call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getCoverageDistributionData(data, label) {
    var labels = [
      '0%',
      '0-10%',
      '10-20%',
      '20-30%',
      '30-40%',
      '40-50%',
      '50-60%',
      '60-70%',
      '70-80%',
      '80-90%',
      '90-100%',
      '100%'
    ];
    var values = [];
    $.each(labels, function(key) {
      values.push({x: labels[key], y: data[key]});
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Cyclomatic Complexity');

    d3.select('#classComplexity svg')
      .datum(getComplexityData({{complexity_class}}, 'Class Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  nv.addGraph(function() {
    var chart = nv.models.scatterChart()
      .showDistX(true)
      .showDistY(true)
      .showLegend(false)
      .forceX([0, 100]);
    chart.tooltipContent(function(graph) {
      return '<p>' + graph.point.class + '</p>';
    });

    chart.xAxis.axisLabel('Code Coverage (in percent)');
    chart.yAxis.axisLabel('Method Complexity');

    d3.select('#methodComplexity svg')
      .datum(getComplexityData({{complexity_method}}, 'Method Complexity'))
      .transition()
      .duration(500)
      .call(chart);

    nv.utils.windowResize(chart.update);

    return chart;
  });

  function getComplexityData(data, label) {
    var values = [];
    $.each(data, function(key) {
      var value = Math.round(data[key][0]*100) / 100;
      values.push({
        x: value,
        y: data[key][1],
        class: data[key][2],
        size: 0.05,
        shape: 'diamond'
      });
    });

    return [
      {
        key: label,
        values: values,
        color: "#4572A7"
      }
    ];
  }
});
  </script>
 </body>
</html>
       <div class="progress">
         <div class="progress-bar bg-{{level}}" role="progressbar" aria-valuenow="{{percent}}" aria-valuemin="0" aria-valuemax="100" style="width: {{percent}}%">
           <span class="sr-only">{{percent}}% covered ({{level}})</span>
         </div>
       </div>
/*!
 * Bootstrap v4.3.1 (https://getbootstrap.com/)
 * Copyright 2011-2019 The Bootstrap Authors
 * Copyright 2011-2019 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:"\2014\00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-break:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-last{-ms-flex-order:13;order:13}.order-0{-ms-flex-order:0;order:0}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-last{-ms-flex-order:13;order:13}.order-sm-0{-ms-flex-order:0;order:0}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-last{-ms-flex-order:13;order:13}.order-md-0{-ms-flex-order:0;order:0}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-last{-ms-flex-order:13;order:13}.order-lg-0{-ms-flex-order:0;order:0}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-last{-ms-flex-order:13;order:13}.order-xl-0{-ms-flex-order:0;order:0}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;margin-bottom:1rem;color:#212529}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{color:#212529;background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-primary tbody+tbody,.table-primary td,.table-primary th,.table-primary thead th{border-color:#7abaff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-secondary tbody+tbody,.table-secondary td,.table-secondary th,.table-secondary thead th{border-color:#b3b7bb}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-success tbody+tbody,.table-success td,.table-success th,.table-success thead th{border-color:#8fd19e}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-info tbody+tbody,.table-info td,.table-info th,.table-info thead th{border-color:#86cfda}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-warning tbody+tbody,.table-warning td,.table-warning th,.table-warning thead th{border-color:#ffdf7e}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-danger tbody+tbody,.table-danger td,.table-danger th,.table-danger thead th{border-color:#ed969e}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-light tbody+tbody,.table-light td,.table-light th,.table-light thead th{border-color:#fbfcfc}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#95999c}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#343a40;border-color:#454d55}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#343a40}.table-dark td,.table-dark th,.table-dark thead th{border-color:#454d55}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{color:#fff;background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive>.table-bordered{border:0}.form-control{display:block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.5em + .5rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(1.5em + 1rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(40,167,69,.9);border-radius:.25rem}.form-control.is-valid,.was-validated .form-control:valid{border-color:#28a745;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:center right calc(.375em + .1875rem);background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-valid:focus,.was-validated .form-control:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.form-control.is-valid~.valid-feedback,.form-control.is-valid~.valid-tooltip,.was-validated .form-control:valid~.valid-feedback,.was-validated .form-control:valid~.valid-tooltip{display:block}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-valid,.was-validated .custom-select:valid{border-color:#28a745;padding-right:calc((1em + .75rem) * 3 / 4 + 1.75rem);background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px,url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-valid:focus,.was-validated .custom-select:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-select.is-valid~.valid-feedback,.custom-select.is-valid~.valid-tooltip,.was-validated .custom-select:valid~.valid-feedback,.was-validated .custom-select:valid~.valid-tooltip{display:block}.form-control-file.is-valid~.valid-feedback,.form-control-file.is-valid~.valid-tooltip,.was-validated .form-control-file:valid~.valid-feedback,.was-validated .form-control-file:valid~.valid-tooltip{display:block}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#28a745}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#28a745}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{border-color:#28a745}.custom-control-input.is-valid~.valid-feedback,.custom-control-input.is-valid~.valid-tooltip,.was-validated .custom-control-input:valid~.valid-feedback,.was-validated .custom-control-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{border-color:#34ce57;background-color:#34ce57}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-control-input.is-valid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:valid:focus:not(:checked)~.custom-control-label::before{border-color:#28a745}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#28a745}.custom-file-input.is-valid~.valid-feedback,.custom-file-input.is-valid~.valid-tooltip,.was-validated .custom-file-input:valid~.valid-feedback,.was-validated .custom-file-input:valid~.valid-tooltip{display:block}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.form-control.is-invalid,.was-validated .form-control:invalid{border-color:#dc3545;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23dc3545' viewBox='-2 -2 7 7'%3e%3cpath stroke='%23dc3545' d='M0 0l3 3m0-3L0 3'/%3e%3ccircle r='.5'/%3e%3ccircle cx='3' r='.5'/%3e%3ccircle cy='3' r='.5'/%3e%3ccircle cx='3' cy='3' r='.5'/%3e%3c/svg%3E");background-repeat:no-repeat;background-position:center right calc(.375em + .1875rem);background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-control.is-invalid~.invalid-feedback,.form-control.is-invalid~.invalid-tooltip,.was-validated .form-control:invalid~.invalid-feedback,.was-validated .form-control:invalid~.invalid-tooltip{display:block}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-invalid,.was-validated .custom-select:invalid{border-color:#dc3545;padding-right:calc((1em + .75rem) * 3 / 4 + 1.75rem);background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px,url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23dc3545' viewBox='-2 -2 7 7'%3e%3cpath stroke='%23dc3545' d='M0 0l3 3m0-3L0 3'/%3e%3ccircle r='.5'/%3e%3ccircle cx='3' r='.5'/%3e%3ccircle cy='3' r='.5'/%3e%3ccircle cx='3' cy='3' r='.5'/%3e%3c/svg%3E") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-invalid:focus,.was-validated .custom-select:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-select.is-invalid~.invalid-feedback,.custom-select.is-invalid~.invalid-tooltip,.was-validated .custom-select:invalid~.invalid-feedback,.was-validated .custom-select:invalid~.invalid-tooltip{display:block}.form-control-file.is-invalid~.invalid-feedback,.form-control-file.is-invalid~.invalid-tooltip,.was-validated .form-control-file:invalid~.invalid-feedback,.was-validated .form-control-file:invalid~.invalid-tooltip{display:block}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{border-color:#dc3545}.custom-control-input.is-invalid~.invalid-feedback,.custom-control-input.is-invalid~.invalid-tooltip,.was-validated .custom-control-input:invalid~.invalid-feedback,.was-validated .custom-control-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{border-color:#e4606d;background-color:#e4606d}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-control-input.is-invalid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus:not(:checked)~.custom-control-label::before{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#dc3545}.custom-file-input.is-invalid~.invalid-feedback,.custom-file-input.is-invalid~.invalid-tooltip,.was-validated .custom-file-input:invalid~.invalid-feedback,.was-validated .custom-file-input:invalid~.invalid-tooltip{display:block}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;-ms-flex-negative:0;flex-shrink:0;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.btn{display:inline-block;font-weight:400;color:#212529;text-align:center;vertical-align:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:transparent;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.btn{transition:none}}.btn:hover{color:#212529;text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5a6268;border-color:#545b62}.btn-secondary.focus,.btn-secondary:focus{box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#545b62;border-color:#4e555b}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-warning{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#212529;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#212529;background-color:#d39e00;border-color:#c69500}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled).active,.btn-light:not(:disabled):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled).active:focus,.btn-light:not(:disabled):not(.disabled):active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled).active,.btn-dark:not(:disabled):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled).active:focus,.btn-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-outline-primary{color:#007bff;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled).active,.btn-outline-primary:not(:disabled):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#6c757d;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled).active,.btn-outline-secondary:not(:disabled):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-success{color:#28a745;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled).active,.btn-outline-success:not(:disabled):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success:not(:disabled):not(.disabled).active:focus,.btn-outline-success:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled).active,.btn-outline-info:not(:disabled):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info:not(:disabled):not(.disabled).active:focus,.btn-outline-info:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;border-color:#ffc107}.btn-outline-warning:hover{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled).active,.btn-outline-warning:not(:disabled):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled).active,.btn-outline-danger:not(:disabled):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-light{color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled).active,.btn-outline-light:not(:disabled):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled).active:focus,.btn-outline-light:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled).active,.btn-outline-dark:not(:disabled):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;text-decoration:none}.btn-link:hover{color:#0056b3;text-decoration:underline}.btn-link.focus,.btn-link:focus{text-decoration:underline;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle{white-space:nowrap}.dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-left{right:auto;left:0}.dropdown-menu-right{right:0;left:auto}@media (min-width:576px){.dropdown-menu-sm-left{right:auto;left:0}.dropdown-menu-sm-right{right:0;left:auto}}@media (min-width:768px){.dropdown-menu-md-left{right:auto;left:0}.dropdown-menu-md-right{right:0;left:auto}}@media (min-width:992px){.dropdown-menu-lg-left{right:auto;left:0}.dropdown-menu-lg-right{right:0;left:auto}}@media (min-width:1200px){.dropdown-menu-xl-left{right:auto;left:0}.dropdown-menu-xl-right{right:0;left:auto}}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropright .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:""}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;margin-right:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;pointer-events:none;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:1 1 auto;flex:1 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:1}.btn-toolbar{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn-group:not(:first-child),.btn-group>.btn:not(:first-child){margin-left:-1px}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{width:100%}.btn-group-vertical>.btn-group:not(:first-child),.btn-group-vertical>.btn:not(:first-child){margin-top:-1px}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control,.input-group>.form-control-plaintext{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;width:1%;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control,.input-group>.form-control-plaintext+.custom-file,.input-group>.form-control-plaintext+.custom-select,.input-group>.form-control-plaintext+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-append,.input-group-prepend{display:-ms-flexbox;display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn:focus,.input-group-prepend .btn:focus{z-index:3}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.custom-select,.input-group-lg>.form-control:not(textarea){height:calc(1.5em + 1rem + 2px)}.input-group-lg>.custom-select,.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.custom-select,.input-group-sm>.form-control:not(textarea){height:calc(1.5em + .5rem + 2px)}.input-group-sm>.custom-select,.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group-lg>.custom-select,.input-group-sm>.custom-select{padding-right:1.75rem}.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:-ms-inline-flexbox;display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;z-index:-1;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;border-color:#007bff;background-color:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:focus:not(:checked)~.custom-control-label::before{border-color:#80bdff}.custom-control-input:not(:disabled):active~.custom-control-label::before{color:#fff;background-color:#b3d7ff;border-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0;vertical-align:top}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:"";background-color:#fff;border:#adb5bd solid 1px}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:"";background:no-repeat 50%/50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{border-color:#007bff;background-color:#007bff}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0 2h4'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-switch{padding-left:2.25rem}.custom-switch .custom-control-label::before{left:-2.25rem;width:1.75rem;pointer-events:all;border-radius:.5rem}.custom-switch .custom-control-label::after{top:calc(.25rem + 2px);left:calc(-2.25rem + 2px);width:calc(1rem - 4px);height:calc(1rem - 4px);background-color:#adb5bd;border-radius:.5rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-switch .custom-control-label::after{transition:none}}.custom-switch .custom-control-input:checked~.custom-control-label::after{background-color:#fff;-webkit-transform:translateX(.75rem);transform:translateX(.75rem)}.custom-switch .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-select{display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem 1.75rem .375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;vertical-align:middle;background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size="1"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{display:none}.custom-select-sm{height:calc(1.5em + .5rem + 2px);padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:.875rem}.custom-select-lg{height:calc(1.5em + 1rem + 2px);padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem}.custom-file{position:relative;display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(1.5em + .75rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-label{border-color:#80bdff;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-file-input:disabled~.custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en)~.custom-file-label::after{content:"Browse"}.custom-file-input~.custom-file-label[data-browse]::after{content:attr(data-browse)}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:calc(1.5em + .75rem);padding:.375rem .75rem;line-height:1.5;color:#495057;content:"Browse";background-color:#e9ecef;border-left:inherit;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;height:calc(1rem + .4rem);padding:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#b3d7ff}.custom-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{transition:none}}.custom-range::-moz-range-thumb:active{background-color:#b3d7ff}.custom-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:.2rem;margin-left:.2rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{transition:none}}.custom-range::-ms-thumb:active{background-color:#b3d7ff}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-range:disabled::-webkit-slider-thumb{background-color:#adb5bd}.custom-range:disabled::-webkit-slider-runnable-track{cursor:default}.custom-range:disabled::-moz-range-thumb{background-color:#adb5bd}.custom-range:disabled::-moz-range-track{cursor:default}.custom-range:disabled::-ms-thumb{background-color:#adb5bd}.custom-control-label::before,.custom-file-label,.custom-select{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d;pointer-events:none;cursor:default}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:"";background:no-repeat center center;background-size:100% 100%}@media (max-width:575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width:767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width:991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width:1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:-ms-flexbox;display:flex;-ms-flex:1 0 0%;flex:1 0 0%;-ms-flex-direction:column;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:not(:last-child) .card-header,.card-group>.card:not(:last-child) .card-img-top{border-top-right-radius:0}.card-group>.card:not(:last-child) .card-footer,.card-group>.card:not(:last-child) .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:not(:first-child) .card-header,.card-group>.card:not(:first-child) .card-img-top{border-top-left-radius:0}.card-group>.card:not(:first-child) .card-footer,.card-group>.card:not(:first-child) .card-img-bottom{border-bottom-left-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;-moz-column-count:3;column-count:3;-webkit-column-gap:1.25rem;-moz-column-gap:1.25rem;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion>.card{overflow:hidden}.accordion>.card:not(:first-of-type) .card-header:first-child{border-radius:0}.accordion>.card:not(:first-of-type):not(:last-of-type){border-bottom:0;border-radius:0}.accordion>.card:first-of-type{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion>.card:last-of-type{border-top-left-radius:0;border-top-right-radius:0}.accordion>.card .card-header{margin-bottom:-1px}.breadcrumb{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:2;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:1;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.badge{transition:none}}a.badge:focus,a.badge:hover{text-decoration:none}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}a.badge-primary:focus,a.badge-primary:hover{color:#fff;background-color:#0062cc}a.badge-primary.focus,a.badge-primary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.badge-secondary{color:#fff;background-color:#6c757d}a.badge-secondary:focus,a.badge-secondary:hover{color:#fff;background-color:#545b62}a.badge-secondary.focus,a.badge-secondary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.badge-success{color:#fff;background-color:#28a745}a.badge-success:focus,a.badge-success:hover{color:#fff;background-color:#1e7e34}a.badge-success.focus,a.badge-success:focus{outline:0;box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.badge-info{color:#fff;background-color:#17a2b8}a.badge-info:focus,a.badge-info:hover{color:#fff;background-color:#117a8b}a.badge-info.focus,a.badge-info:focus{outline:0;box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.badge-warning{color:#212529;background-color:#ffc107}a.badge-warning:focus,a.badge-warning:hover{color:#212529;background-color:#d39e00}a.badge-warning.focus,a.badge-warning:focus{outline:0;box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.badge-danger{color:#fff;background-color:#dc3545}a.badge-danger:focus,a.badge-danger:hover{color:#fff;background-color:#bd2130}a.badge-danger.focus,a.badge-danger:focus{outline:0;box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.badge-light{color:#212529;background-color:#f8f9fa}a.badge-light:focus,a.badge-light:hover{color:#212529;background-color:#dae0e5}a.badge-light.focus,a.badge-light:focus{outline:0;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.badge-dark{color:#fff;background-color:#343a40}a.badge-dark:focus,a.badge-dark:hover{color:#fff;background-color:#1d2124}a.badge-dark.focus,a.badge-dark:focus{outline:0;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#383d41;background-color:#e2e3e5;border-color:#d6d8db}.alert-secondary hr{border-top-color:#c8cbcf}.alert-secondary .alert-link{color:#202326}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;color:#fff;text-align:center;white-space:nowrap;background-color:#007bff;transition:width .6s ease}@media (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}@media (prefers-reduced-motion:reduce){.progress-bar-animated{-webkit-animation:none;animation:none}}.media{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{z-index:1;color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.list-group-horizontal{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}@media (min-width:576px){.list-group-horizontal-sm{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-sm .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-sm .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-sm .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:768px){.list-group-horizontal-md{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-md .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-md .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-md .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:992px){.list-group-horizontal-lg{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-lg .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-lg .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-lg .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:1200px){.list-group-horizontal-xl{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-xl .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-xl .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xl .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}.list-group-flush .list-group-item{border-right:0;border-left:0;border-radius:0}.list-group-flush .list-group-item:last-child{margin-bottom:-1px}.list-group-flush:first-child .list-group-item:first-child{border-top:0}.list-group-flush:last-child .list-group-item:last-child{margin-bottom:0;border-bottom:0}.list-group-item-primary{color:#004085;background-color:#b8daff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#004085;background-color:#9fcdff}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#383d41;background-color:#d6d8db}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#383d41;background-color:#c8cbcf}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#383d41;border-color:#383d41}.list-group-item-success{color:#155724;background-color:#c3e6cb}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#155724;background-color:#b1dfbb}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#0c5460;background-color:#abdde5}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#856404;background-color:#ffe8a1}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#721c24;background-color:#f1b0b7}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:hover{color:#000;text-decoration:none}.close:not(:disabled):not(.disabled):focus,.close:not(:disabled):not(.disabled):hover{opacity:.75}button.close{padding:0;background-color:transparent;border:0;-webkit-appearance:none;-moz-appearance:none;appearance:none}a.close.disabled{pointer-events:none}.toast{max-width:350px;overflow:hidden;font-size:.875rem;background-color:rgba(255,255,255,.85);background-clip:padding-box;border:1px solid rgba(0,0,0,.1);box-shadow:0 .25rem .75rem rgba(0,0,0,.1);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);opacity:0;border-radius:.25rem}.toast:not(:last-child){margin-bottom:.75rem}.toast.showing{opacity:1}.toast.show{display:block;opacity:1}.toast.hide{display:none}.toast-header{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.25rem .75rem;color:#6c757d;background-color:rgba(255,255,255,.85);background-clip:padding-box;border-bottom:1px solid rgba(0,0,0,.05)}.toast-body{padding:.75rem}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;left:0;z-index:1050;display:none;width:100%;height:100%;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-50px);transform:translate(0,-50px)}@media (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{-webkit-transform:none;transform:none}.modal-dialog-scrollable{display:-ms-flexbox;display:flex;max-height:calc(100% - 1rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 1rem);overflow:hidden}.modal-dialog-scrollable .modal-footer,.modal-dialog-scrollable .modal-header{-ms-flex-negative:0;flex-shrink:0}.modal-dialog-scrollable .modal-body{overflow-y:auto}.modal-dialog-centered{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:calc(100% - 1rem)}.modal-dialog-centered::before{display:block;height:calc(100vh - 1rem);content:""}.modal-dialog-centered.modal-dialog-scrollable{-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;height:100%}.modal-dialog-centered.modal-dialog-scrollable .modal-content{max-height:none}.modal-dialog-centered.modal-dialog-scrollable::before{content:none}.modal-content{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.modal-backdrop{position:fixed;top:0;left:0;z-index:1040;width:100vw;height:100vh;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:1rem 1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:.3rem;border-top-right-radius:.3rem}.modal-header .close{padding:1rem 1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;justify-content:flex-end;padding:1rem;border-top:1px solid #dee2e6;border-bottom-right-radius:.3rem;border-bottom-left-radius:.3rem}.modal-footer>:not(:first-child){margin-left:.25rem}.modal-footer>:not(:last-child){margin-right:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-scrollable{max-height:calc(100% - 3.5rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 3.5rem)}.modal-dialog-centered{min-height:calc(100% - 3.5rem)}.modal-dialog-centered::before{height:calc(100vh - 3.5rem)}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg,.modal-xl{max-width:800px}}@media (min-width:1200px){.modal-xl{max-width:1140px}}.tooltip{position:absolute;z-index:1070;display:block;margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top]>.arrow,.bs-popover-top>.arrow{bottom:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=top]>.arrow::before,.bs-popover-top>.arrow::before{bottom:0;border-width:.5rem .5rem 0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top]>.arrow::after,.bs-popover-top>.arrow::after{bottom:1px;border-width:.5rem .5rem 0;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right]>.arrow,.bs-popover-right>.arrow{left:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right]>.arrow::before,.bs-popover-right>.arrow::before{left:0;border-width:.5rem .5rem .5rem 0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{left:1px;border-width:.5rem .5rem .5rem 0;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom]>.arrow,.bs-popover-bottom>.arrow{top:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=bottom]>.arrow::before,.bs-popover-bottom>.arrow::before{top:0;border-width:0 .5rem .5rem .5rem;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom]>.arrow::after,.bs-popover-bottom>.arrow::after{top:1px;border-width:0 .5rem .5rem .5rem;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:"";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left]>.arrow,.bs-popover-left>.arrow{right:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left]>.arrow::before,.bs-popover-left>.arrow::before{right:0;border-width:.5rem 0 .5rem .5rem;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left]>.arrow::after,.bs-popover-left>.arrow::after{right:1px;border-width:.5rem 0 .5rem .5rem;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel.pointer-event{-ms-touch-action:pan-y;touch-action:pan-y}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner::after{display:block;clear:both;content:""}.carousel-item{position:relative;display:none;float:left;width:100%;margin-right:-100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;transition:-webkit-transform .6s ease-in-out;transition:transform .6s ease-in-out;transition:transform .6s ease-in-out,-webkit-transform .6s ease-in-out}@media (prefers-reduced-motion:reduce){.carousel-item{transition:none}}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.active.carousel-item-right,.carousel-item-next:not(.carousel-item-left){-webkit-transform:translateX(100%);transform:translateX(100%)}.active.carousel-item-left,.carousel-item-prev:not(.carousel-item-right){-webkit-transform:translateX(-100%);transform:translateX(-100%)}.carousel-fade .carousel-item{opacity:0;transition-property:opacity;-webkit-transform:none;transform:none}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{z-index:1;opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{z-index:0;opacity:0;transition:0s .6s opacity}@media (prefers-reduced-motion:reduce){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{transition:none}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;z-index:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5;transition:opacity .15s ease}@media (prefers-reduced-motion:reduce){.carousel-control-next,.carousel-control-prev{transition:none}}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:no-repeat 50%/100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3e%3c/svg%3e")}.carousel-control-next-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3e%3c/svg%3e")}.carousel-indicators{position:absolute;right:0;bottom:0;left:0;z-index:15;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{box-sizing:content-box;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:#fff;background-clip:padding-box;border-top:10px solid transparent;border-bottom:10px solid transparent;opacity:.5;transition:opacity .6s ease}@media (prefers-reduced-motion:reduce){.carousel-indicators li{transition:none}}.carousel-indicators .active{opacity:1}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}@-webkit-keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.spinner-border{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;border:.25em solid currentColor;border-right-color:transparent;border-radius:50%;-webkit-animation:spinner-border .75s linear infinite;animation:spinner-border .75s linear infinite}.spinner-border-sm{width:1rem;height:1rem;border-width:.2em}@-webkit-keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}@keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}.spinner-grow{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;background-color:currentColor;border-radius:50%;opacity:0;-webkit-animation:spinner-grow .75s linear infinite;animation:spinner-grow .75s linear infinite}.spinner-grow-sm{width:1rem;height:1rem}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#007bff!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#6c757d!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#545b62!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #dee2e6!important}.border-top{border-top:1px solid #dee2e6!important}.border-right{border-right:1px solid #dee2e6!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-left{border-left:1px solid #dee2e6!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#007bff!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded-sm{border-radius:.2rem!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-lg{border-radius:.3rem!important}.rounded-circle{border-radius:50%!important}.rounded-pill{border-radius:50rem!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:""}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:-ms-flexbox!important;display:flex!important}.d-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media print{.d-print-none{display:none!important}.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:-ms-flexbox!important;display:flex!important}.d-print-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:""}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}@media (min-width:576px){.flex-sm-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-sm-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-sm-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-sm-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-sm-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-sm-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-sm-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-sm-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-sm-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-sm-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-sm-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-sm-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-sm-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-sm-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-sm-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-sm-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-sm-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-sm-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-sm-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-sm-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-sm-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-sm-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-sm-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:768px){.flex-md-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-md-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-md-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-md-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-md-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-md-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-md-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-md-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-md-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-md-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-md-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-md-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-md-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-md-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-md-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-md-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-md-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-md-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-md-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-md-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-md-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-md-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-md-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-lg-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-lg-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-lg-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-lg-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-lg-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-lg-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-lg-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-lg-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-lg-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-lg-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-lg-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-lg-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-lg-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-lg-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-lg-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-lg-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-lg-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-lg-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-lg-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-lg-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-lg-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-lg-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-xl-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-xl-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-xl-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-xl-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-xl-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-xl-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-xl-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-xl-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-xl-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-xl-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-xl-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-xl-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-xl-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-xl-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-xl-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-xl-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-xl-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-xl-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-xl-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-xl-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-xl-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-xl-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.overflow-auto{overflow:auto!important}.overflow-hidden{overflow:hidden!important}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports ((position:-webkit-sticky) or (position:sticky)){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.min-vw-100{min-width:100vw!important}.min-vh-100{min-height:100vh!important}.vw-100{width:100vw!important}.vh-100{height:100vh!important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;pointer-events:auto;content:"";background-color:rgba(0,0,0,0)}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-n1{margin:-.25rem!important}.mt-n1,.my-n1{margin-top:-.25rem!important}.mr-n1,.mx-n1{margin-right:-.25rem!important}.mb-n1,.my-n1{margin-bottom:-.25rem!important}.ml-n1,.mx-n1{margin-left:-.25rem!important}.m-n2{margin:-.5rem!important}.mt-n2,.my-n2{margin-top:-.5rem!important}.mr-n2,.mx-n2{margin-right:-.5rem!important}.mb-n2,.my-n2{margin-bottom:-.5rem!important}.ml-n2,.mx-n2{margin-left:-.5rem!important}.m-n3{margin:-1rem!important}.mt-n3,.my-n3{margin-top:-1rem!important}.mr-n3,.mx-n3{margin-right:-1rem!important}.mb-n3,.my-n3{margin-bottom:-1rem!important}.ml-n3,.mx-n3{margin-left:-1rem!important}.m-n4{margin:-1.5rem!important}.mt-n4,.my-n4{margin-top:-1.5rem!important}.mr-n4,.mx-n4{margin-right:-1.5rem!important}.mb-n4,.my-n4{margin-bottom:-1.5rem!important}.ml-n4,.mx-n4{margin-left:-1.5rem!important}.m-n5{margin:-3rem!important}.mt-n5,.my-n5{margin-top:-3rem!important}.mr-n5,.mx-n5{margin-right:-3rem!important}.mb-n5,.my-n5{margin-bottom:-3rem!important}.ml-n5,.mx-n5{margin-left:-3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-n1{margin:-.25rem!important}.mt-sm-n1,.my-sm-n1{margin-top:-.25rem!important}.mr-sm-n1,.mx-sm-n1{margin-right:-.25rem!important}.mb-sm-n1,.my-sm-n1{margin-bottom:-.25rem!important}.ml-sm-n1,.mx-sm-n1{margin-left:-.25rem!important}.m-sm-n2{margin:-.5rem!important}.mt-sm-n2,.my-sm-n2{margin-top:-.5rem!important}.mr-sm-n2,.mx-sm-n2{margin-right:-.5rem!important}.mb-sm-n2,.my-sm-n2{margin-bottom:-.5rem!important}.ml-sm-n2,.mx-sm-n2{margin-left:-.5rem!important}.m-sm-n3{margin:-1rem!important}.mt-sm-n3,.my-sm-n3{margin-top:-1rem!important}.mr-sm-n3,.mx-sm-n3{margin-right:-1rem!important}.mb-sm-n3,.my-sm-n3{margin-bottom:-1rem!important}.ml-sm-n3,.mx-sm-n3{margin-left:-1rem!important}.m-sm-n4{margin:-1.5rem!important}.mt-sm-n4,.my-sm-n4{margin-top:-1.5rem!important}.mr-sm-n4,.mx-sm-n4{margin-right:-1.5rem!important}.mb-sm-n4,.my-sm-n4{margin-bottom:-1.5rem!important}.ml-sm-n4,.mx-sm-n4{margin-left:-1.5rem!important}.m-sm-n5{margin:-3rem!important}.mt-sm-n5,.my-sm-n5{margin-top:-3rem!important}.mr-sm-n5,.mx-sm-n5{margin-right:-3rem!important}.mb-sm-n5,.my-sm-n5{margin-bottom:-3rem!important}.ml-sm-n5,.mx-sm-n5{margin-left:-3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-n1{margin:-.25rem!important}.mt-md-n1,.my-md-n1{margin-top:-.25rem!important}.mr-md-n1,.mx-md-n1{margin-right:-.25rem!important}.mb-md-n1,.my-md-n1{margin-bottom:-.25rem!important}.ml-md-n1,.mx-md-n1{margin-left:-.25rem!important}.m-md-n2{margin:-.5rem!important}.mt-md-n2,.my-md-n2{margin-top:-.5rem!important}.mr-md-n2,.mx-md-n2{margin-right:-.5rem!important}.mb-md-n2,.my-md-n2{margin-bottom:-.5rem!important}.ml-md-n2,.mx-md-n2{margin-left:-.5rem!important}.m-md-n3{margin:-1rem!important}.mt-md-n3,.my-md-n3{margin-top:-1rem!important}.mr-md-n3,.mx-md-n3{margin-right:-1rem!important}.mb-md-n3,.my-md-n3{margin-bottom:-1rem!important}.ml-md-n3,.mx-md-n3{margin-left:-1rem!important}.m-md-n4{margin:-1.5rem!important}.mt-md-n4,.my-md-n4{margin-top:-1.5rem!important}.mr-md-n4,.mx-md-n4{margin-right:-1.5rem!important}.mb-md-n4,.my-md-n4{margin-bottom:-1.5rem!important}.ml-md-n4,.mx-md-n4{margin-left:-1.5rem!important}.m-md-n5{margin:-3rem!important}.mt-md-n5,.my-md-n5{margin-top:-3rem!important}.mr-md-n5,.mx-md-n5{margin-right:-3rem!important}.mb-md-n5,.my-md-n5{margin-bottom:-3rem!important}.ml-md-n5,.mx-md-n5{margin-left:-3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-n1{margin:-.25rem!important}.mt-lg-n1,.my-lg-n1{margin-top:-.25rem!important}.mr-lg-n1,.mx-lg-n1{margin-right:-.25rem!important}.mb-lg-n1,.my-lg-n1{margin-bottom:-.25rem!important}.ml-lg-n1,.mx-lg-n1{margin-left:-.25rem!important}.m-lg-n2{margin:-.5rem!important}.mt-lg-n2,.my-lg-n2{margin-top:-.5rem!important}.mr-lg-n2,.mx-lg-n2{margin-right:-.5rem!important}.mb-lg-n2,.my-lg-n2{margin-bottom:-.5rem!important}.ml-lg-n2,.mx-lg-n2{margin-left:-.5rem!important}.m-lg-n3{margin:-1rem!important}.mt-lg-n3,.my-lg-n3{margin-top:-1rem!important}.mr-lg-n3,.mx-lg-n3{margin-right:-1rem!important}.mb-lg-n3,.my-lg-n3{margin-bottom:-1rem!important}.ml-lg-n3,.mx-lg-n3{margin-left:-1rem!important}.m-lg-n4{margin:-1.5rem!important}.mt-lg-n4,.my-lg-n4{margin-top:-1.5rem!important}.mr-lg-n4,.mx-lg-n4{margin-right:-1.5rem!important}.mb-lg-n4,.my-lg-n4{margin-bottom:-1.5rem!important}.ml-lg-n4,.mx-lg-n4{margin-left:-1.5rem!important}.m-lg-n5{margin:-3rem!important}.mt-lg-n5,.my-lg-n5{margin-top:-3rem!important}.mr-lg-n5,.mx-lg-n5{margin-right:-3rem!important}.mb-lg-n5,.my-lg-n5{margin-bottom:-3rem!important}.ml-lg-n5,.mx-lg-n5{margin-left:-3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-n1{margin:-.25rem!important}.mt-xl-n1,.my-xl-n1{margin-top:-.25rem!important}.mr-xl-n1,.mx-xl-n1{margin-right:-.25rem!important}.mb-xl-n1,.my-xl-n1{margin-bottom:-.25rem!important}.ml-xl-n1,.mx-xl-n1{margin-left:-.25rem!important}.m-xl-n2{margin:-.5rem!important}.mt-xl-n2,.my-xl-n2{margin-top:-.5rem!important}.mr-xl-n2,.mx-xl-n2{margin-right:-.5rem!important}.mb-xl-n2,.my-xl-n2{margin-bottom:-.5rem!important}.ml-xl-n2,.mx-xl-n2{margin-left:-.5rem!important}.m-xl-n3{margin:-1rem!important}.mt-xl-n3,.my-xl-n3{margin-top:-1rem!important}.mr-xl-n3,.mx-xl-n3{margin-right:-1rem!important}.mb-xl-n3,.my-xl-n3{margin-bottom:-1rem!important}.ml-xl-n3,.mx-xl-n3{margin-left:-1rem!important}.m-xl-n4{margin:-1.5rem!important}.mt-xl-n4,.my-xl-n4{margin-top:-1.5rem!important}.mr-xl-n4,.mx-xl-n4{margin-right:-1.5rem!important}.mb-xl-n4,.my-xl-n4{margin-bottom:-1.5rem!important}.ml-xl-n4,.mx-xl-n4{margin-left:-1.5rem!important}.m-xl-n5{margin:-3rem!important}.mt-xl-n5,.my-xl-n5{margin-top:-3rem!important}.mr-xl-n5,.mx-xl-n5{margin-right:-3rem!important}.mb-xl-n5,.my-xl-n5{margin-bottom:-3rem!important}.ml-xl-n5,.mx-xl-n5{margin-left:-3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-monospace{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace!important}.text-justify{text-align:justify!important}.text-wrap{white-space:normal!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-lighter{font-weight:lighter!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-weight-bolder{font-weight:bolder!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0056b3!important}.text-secondary{color:#6c757d!important}a.text-secondary:focus,a.text-secondary:hover{color:#494f54!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#19692c!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#0f6674!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#ba8b00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#a71d2a!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#cbd3da!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#121416!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.text-decoration-none{text-decoration:none!important}.text-break{word-break:break-word!important;overflow-wrap:break-word!important}.text-reset{color:inherit!important}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:" (" attr(title) ")"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px!important}.container{min-width:992px!important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}}
/*# sourceMappingURL=bootstrap.min.css.map */.nvd3 .nv-axis{pointer-events:none;opacity:1}.nvd3 .nv-axis path{fill:none;stroke:#000;stroke-opacity:.75;shape-rendering:crispEdges}.nvd3 .nv-axis path.domain{stroke-opacity:.75}.nvd3 .nv-axis.nv-x path.domain{stroke-opacity:0}.nvd3 .nv-axis line{fill:none;stroke:#e5e5e5;shape-rendering:crispEdges}.nvd3 .nv-axis .zero line,.nvd3 .nv-axis line.zero{stroke-opacity:.75}.nvd3 .nv-axis .nv-axisMaxMin text{font-weight:700}.nvd3 .x .nv-axis .nv-axisMaxMin text,.nvd3 .x2 .nv-axis .nv-axisMaxMin text,.nvd3 .x3 .nv-axis .nv-axisMaxMin text{text-anchor:middle}.nvd3 .nv-axis.nv-disabled{opacity:0}.nvd3 .nv-bars rect{fill-opacity:.75;transition:fill-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear}.nvd3 .nv-bars rect.hover{fill-opacity:1}.nvd3 .nv-bars .hover rect{fill:#add8e6}.nvd3 .nv-bars text{fill:rgba(0,0,0,0)}.nvd3 .nv-bars .hover text{fill:rgba(0,0,0,1)}.nvd3 .nv-multibar .nv-groups rect,.nvd3 .nv-multibarHorizontal .nv-groups rect,.nvd3 .nv-discretebar .nv-groups rect{stroke-opacity:0;transition:fill-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear}.nvd3 .nv-multibar .nv-groups rect:hover,.nvd3 .nv-multibarHorizontal .nv-groups rect:hover,.nvd3 .nv-candlestickBar .nv-ticks rect:hover,.nvd3 .nv-discretebar .nv-groups rect:hover{fill-opacity:1}.nvd3 .nv-discretebar .nv-groups text,.nvd3 .nv-multibarHorizontal .nv-groups text{font-weight:700;fill:rgba(0,0,0,1);stroke:rgba(0,0,0,0)}.nvd3 .nv-boxplot circle{fill-opacity:.5}.nvd3 .nv-boxplot circle:hover{fill-opacity:1}.nvd3 .nv-boxplot rect:hover{fill-opacity:1}.nvd3 line.nv-boxplot-median{stroke:#000}.nv-boxplot-tick:hover{stroke-width:2.5px}.nvd3.nv-bullet{font:10px sans-serif}.nvd3.nv-bullet .nv-measure{fill-opacity:.8}.nvd3.nv-bullet .nv-measure:hover{fill-opacity:1}.nvd3.nv-bullet .nv-marker{stroke:#000;stroke-width:2px}.nvd3.nv-bullet .nv-markerTriangle{stroke:#000;fill:#fff;stroke-width:1.5px}.nvd3.nv-bullet .nv-tick line{stroke:#666;stroke-width:.5px}.nvd3.nv-bullet .nv-range.nv-s0{fill:#eee}.nvd3.nv-bullet .nv-range.nv-s1{fill:#ddd}.nvd3.nv-bullet .nv-range.nv-s2{fill:#ccc}.nvd3.nv-bullet .nv-title{font-size:14px;font-weight:700}.nvd3.nv-bullet .nv-subtitle{fill:#999}.nvd3.nv-bullet .nv-range{fill:#bababa;fill-opacity:.4}.nvd3.nv-bullet .nv-range:hover{fill-opacity:.7}.nvd3.nv-candlestickBar .nv-ticks .nv-tick{stroke-width:1px}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.hover{stroke-width:2px}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.positive rect{stroke:#2ca02c;fill:#2ca02c}.nvd3.nv-candlestickBar .nv-ticks .nv-tick.negative rect{stroke:#d62728;fill:#d62728}.with-transitions .nv-candlestickBar .nv-ticks .nv-tick{transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-candlestickBar .nv-ticks line{stroke:#333}.nvd3 .nv-legend .nv-disabled rect{}.nvd3 .nv-check-box .nv-box{fill-opacity:0;stroke-width:2}.nvd3 .nv-check-box .nv-check{fill-opacity:0;stroke-width:4}.nvd3 .nv-series.nv-disabled .nv-check-box .nv-check{fill-opacity:0;stroke-opacity:0}.nvd3 .nv-controlsWrap .nv-legend .nv-check-box .nv-check{opacity:0}.nvd3.nv-linePlusBar .nv-bar rect{fill-opacity:.75}.nvd3.nv-linePlusBar .nv-bar rect:hover{fill-opacity:1}.nvd3 .nv-groups path.nv-line{fill:none}.nvd3 .nv-groups path.nv-area{stroke:none}.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point{fill-opacity:0;stroke-opacity:0}.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point{fill-opacity:.5!important;stroke-opacity:.5!important}.with-transitions .nvd3 .nv-groups .nv-point{transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-scatter .nv-groups .nv-point.hover,.nvd3 .nv-groups .nv-point.hover{stroke-width:7px;fill-opacity:.95!important;stroke-opacity:.95!important}.nvd3 .nv-point-paths path{stroke:#aaa;stroke-opacity:0;fill:#eee;fill-opacity:0}.nvd3 .nv-indexLine{cursor:ew-resize}svg.nvd3-svg{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-ms-user-select:none;-moz-user-select:none;user-select:none;display:block;width:100%;height:100%}.nvtooltip.with-3d-shadow,.with-3d-shadow .nvtooltip{-moz-box-shadow:0 5px 10px rgba(0,0,0,.2);-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nvd3 text{font:400 12px Arial}.nvd3 .title{font:700 14px Arial}.nvd3 .nv-background{fill:#fff;fill-opacity:0}.nvd3.nv-noData{font-size:18px;font-weight:700}.nv-brush .extent{fill-opacity:.125;shape-rendering:crispEdges}.nv-brush .resize path{fill:#eee;stroke:#666}.nvd3 .nv-legend .nv-series{cursor:pointer}.nvd3 .nv-legend .nv-disabled circle{fill-opacity:0}.nvd3 .nv-brush .extent{fill-opacity:0!important}.nvd3 .nv-brushBackground rect{stroke:#000;stroke-width:.4;fill:#fff;fill-opacity:.7}.nvd3.nv-ohlcBar .nv-ticks .nv-tick{stroke-width:1px}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover{stroke-width:2px}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive{stroke:#2ca02c}.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative{stroke:#d62728}.nvd3 .background path{fill:none;stroke:#EEE;stroke-opacity:.4;shape-rendering:crispEdges}.nvd3 .foreground path{fill:none;stroke-opacity:.7}.nvd3 .nv-parallelCoordinates-brush .extent{fill:#fff;fill-opacity:.6;stroke:gray;shape-rendering:crispEdges}.nvd3 .nv-parallelCoordinates .hover{fill-opacity:1;stroke-width:3px}.nvd3 .missingValuesline line{fill:none;stroke:#000;stroke-width:1;stroke-opacity:1;stroke-dasharray:5,5}.nvd3.nv-pie path{stroke-opacity:0;transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear,stroke-width 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-pie .nv-pie-title{font-size:24px;fill:rgba(19,196,249,.59)}.nvd3.nv-pie .nv-slice text{stroke:#000;stroke-width:0}.nvd3.nv-pie path{stroke:#fff;stroke-width:1px;stroke-opacity:1}.nvd3.nv-pie .hover path{fill-opacity:.7}.nvd3.nv-pie .nv-label{pointer-events:none}.nvd3.nv-pie .nv-label rect{fill-opacity:0;stroke-opacity:0}.nvd3 .nv-groups .nv-point.hover{stroke-width:20px;stroke-opacity:.5}.nvd3 .nv-scatter .nv-point.hover{fill-opacity:1}.nv-noninteractive{pointer-events:none}.nv-distx,.nv-disty{pointer-events:none}.nvd3.nv-sparkline path{fill:none}.nvd3.nv-sparklineplus g.nv-hoverValue{pointer-events:none}.nvd3.nv-sparklineplus .nv-hoverValue line{stroke:#333;stroke-width:1.5px}.nvd3.nv-sparklineplus,.nvd3.nv-sparklineplus g{pointer-events:all}.nvd3 .nv-hoverArea{fill-opacity:0;stroke-opacity:0}.nvd3.nv-sparklineplus .nv-xValue,.nvd3.nv-sparklineplus .nv-yValue{stroke-width:0;font-size:.9em;font-weight:400}.nvd3.nv-sparklineplus .nv-yValue{stroke:#f66}.nvd3.nv-sparklineplus .nv-maxValue{stroke:#2ca02c;fill:#2ca02c}.nvd3.nv-sparklineplus .nv-minValue{stroke:#d62728;fill:#d62728}.nvd3.nv-sparklineplus .nv-currentValue{font-weight:700;font-size:1.1em}.nvd3.nv-stackedarea path.nv-area{fill-opacity:.7;stroke-opacity:0;transition:fill-opacity 250ms linear,stroke-opacity 250ms linear;-moz-transition:fill-opacity 250ms linear,stroke-opacity 250ms linear;-webkit-transition:fill-opacity 250ms linear,stroke-opacity 250ms linear}.nvd3.nv-stackedarea path.nv-area.hover{fill-opacity:.9}.nvd3.nv-stackedarea .nv-groups .nv-point{stroke-opacity:0;fill-opacity:0}.nvtooltip{position:absolute;background-color:rgba(255,255,255,1);color:rgba(0,0,0,1);padding:1px;border:1px solid rgba(0,0,0,.2);z-index:10000;display:block;font-family:Arial;font-size:13px;text-align:left;pointer-events:none;white-space:nowrap;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.nvtooltip{background:rgba(255,255,255,.8);border:1px solid rgba(0,0,0,.5);border-radius:4px}.nvtooltip.with-transitions,.with-transitions .nvtooltip{transition:opacity 50ms linear;-moz-transition:opacity 50ms linear;-webkit-transition:opacity 50ms linear;transition-delay:200ms;-moz-transition-delay:200ms;-webkit-transition-delay:200ms}.nvtooltip.x-nvtooltip,.nvtooltip.y-nvtooltip{padding:8px}.nvtooltip h3{margin:0;padding:4px 14px;line-height:18px;font-weight:400;background-color:rgba(247,247,247,.75);color:rgba(0,0,0,1);text-align:center;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.nvtooltip p{margin:0;padding:5px 14px;text-align:center}.nvtooltip span{display:inline-block;margin:2px 0}.nvtooltip table{margin:6px;border-spacing:0}.nvtooltip table td{padding:2px 9px 2px 0;vertical-align:middle}.nvtooltip table td.key{font-weight:400}.nvtooltip table td.value{text-align:right;font-weight:700}.nvtooltip table tr.highlight td{padding:1px 9px 1px 0;border-bottom-style:solid;border-bottom-width:1px;border-top-style:solid;border-top-width:1px}.nvtooltip table td.legend-color-guide div{width:8px;height:8px;vertical-align:middle}.nvtooltip table td.legend-color-guide div{width:12px;height:12px;border:1px solid #999}.nvtooltip .footer{padding:3px;text-align:center}.nvtooltip-pending-removal{pointer-events:none;display:none}.nvd3 .nv-interactiveGuideLine{pointer-events:none}.nvd3 line.nv-guideline{stroke:#ccc}.octicon {
  display: inline-block;
  vertical-align: text-top;
  fill: currentColor;
}
body {
 padding-top: 10px;
}

.popover {
 max-width: none;
}

.octicon {
 margin-right:.25em;
}

.table-bordered>thead>tr>td {
 border-bottom-width: 1px;
}

.table tbody>tr>td, .table thead>tr>td {
 padding-top: 3px;
 padding-bottom: 3px;
}

.table-condensed tbody>tr>td {
 padding-top: 0;
 padding-bottom: 0;
}

.table .progress {
 margin-bottom: inherit;
}

.table-borderless th, .table-borderless td {
 border: 0 !important;
}

.table tbody tr.covered-by-large-tests, li.covered-by-large-tests, tr.success, td.success, li.success, span.success {
 background-color: #dff0d8;
}

.table tbody tr.covered-by-medium-tests, li.covered-by-medium-tests {
 background-color: #c3e3b5;
}

.table tbody tr.covered-by-small-tests, li.covered-by-small-tests {
 background-color: #99cb84;
}

.table tbody tr.danger, .table tbody td.danger, li.danger, span.danger {
 background-color: #f2dede;
}

.table tbody td.warning, li.warning, span.warning {
 background-color: #fcf8e3;
}

.table tbody td.info {
 background-color: #d9edf7;
}

td.big {
 width: 117px;
}

td.small {
}

td.codeLine {
 font-family: "Source Code Pro", "SFMono-Regular", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
 white-space: pre;
}

td span.comment {
 color: #888a85;
}

td span.default {
 color: #2e3436;
}

td span.html {
 color: #888a85;
}

td span.keyword {
 color: #2e3436;
 font-weight: bold;
}

pre span.string {
 color: #2e3436;
}

span.success, span.warning, span.danger {
 margin-right: 2px;
 padding-left: 10px;
 padding-right: 10px;
 text-align: center;
}

#classCoverageDistribution, #classComplexity {
 height: 200px;
 width: 475px;
}

#toplink {
 position: fixed;
 left: 5px;
 bottom: 5px;
 outline: 0;
}

svg text {
 font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
 font-size: 11px;
 color: #666;
 fill: #666;
}

.scrollbox {
 height:245px;
 overflow-x:hidden;
 overflow-y:scroll;
}
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for {{full_path}}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{{path_to_root}}_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/style.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
{{breadcrumbs}}
       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
       <td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
      </tr>
     </thead>
     <tbody>
{{items}}
     </tbody>
    </table>
   </div>
   <table id="code" class="table table-borderless table-condensed">
    <tbody>
{{lines}}
    </tbody>
   </table>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="success"><strong>Executed</strong></span>
     <span class="danger"><strong>Not Executed</strong></span>
     <span class="warning"><strong>Dead Code</strong></span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage {{version}}</a> using {{runtime}}{{generator}} at {{date}}.</small>
    </p>
    <a title="Back to the top" id="toplink" href="#">
        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16"><path fill-rule="evenodd" d="M12 11L6 5l-6 6h12z"/></svg>
    </a>
   </footer>
  </div>
  <script src="{{path_to_root}}_js/jquery.min.js" type="text/javascript"></script>
  <script src="{{path_to_root}}_js/popper.min.js" type="text/javascript"></script>
  <script src="{{path_to_root}}_js/bootstrap.min.js" type="text/javascript"></script>
  <script src="{{path_to_root}}_js/file.js" type="text/javascript"></script>
 </body>
</html>
      <tr>
       <td class="{{classes_level}}">{{name}}</td>
       <td class="{{classes_level}} big">{{classes_bar}}</td>
       <td class="{{classes_level}} small"><div align="right">{{classes_tested_percent}}</div></td>
       <td class="{{classes_level}} small"><div align="right">{{classes_number}}</div></td>
       <td class="{{methods_level}} big">{{methods_bar}}</td>
       <td class="{{methods_level}} small"><div align="right">{{methods_tested_percent}}</div></td>
       <td class="{{methods_level}} small"><div align="right">{{methods_number}}</div></td>
       <td class="{{methods_level}} small">{{crap}}</td>
       <td class="{{lines_level}} big">{{lines_bar}}</td>
       <td class="{{lines_level}} small"><div align="right">{{lines_executed_percent}}</div></td>
       <td class="{{lines_level}} small"><div align="right">{{lines_number}}</div></td>
      </tr>

      <tr>
       <td class="{{methods_level}}" colspan="4">{{name}}</td>
       <td class="{{methods_level}} big">{{methods_bar}}</td>
       <td class="{{methods_level}} small"><div align="right">{{methods_tested_percent}}</div></td>
       <td class="{{methods_level}} small"><div align="right">{{methods_number}}</div></td>
       <td class="{{methods_level}} small">{{crap}}</td>
       <td class="{{lines_level}} big">{{lines_bar}}</td>
       <td class="{{lines_level}} small"><div align="right">{{lines_executed_percent}}</div></td>
       <td class="{{lines_level}} small"><div align="right">{{lines_number}}</div></td>
      </tr>

/* nvd3 version 1.8.1 (https://github.com/novus/nvd3) 2015-06-15 */
!function(){var a={};a.dev=!1,a.tooltip=a.tooltip||{},a.utils=a.utils||{},a.models=a.models||{},a.charts={},a.logs={},a.dom={},a.dispatch=d3.dispatch("render_start","render_end"),Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d&&a?this:a,b.concat(Array.prototype.slice.call(arguments)))};return d.prototype=this.prototype,e.prototype=new d,e}),a.dev&&(a.dispatch.on("render_start",function(){a.logs.startTime=+new Date}),a.dispatch.on("render_end",function(){a.logs.endTime=+new Date,a.logs.totalTime=a.logs.endTime-a.logs.startTime,a.log("total",a.logs.totalTime)})),a.log=function(){if(a.dev&&window.console&&console.log&&console.log.apply)console.log.apply(console,arguments);else if(a.dev&&window.console&&"function"==typeof console.log&&Function.prototype.bind){var b=Function.prototype.bind.call(console.log,console);b.apply(console,arguments)}return arguments[arguments.length-1]},a.deprecated=function(a,b){console&&console.warn&&console.warn("nvd3 warning: `"+a+"` has been deprecated. ",b||"")},a.render=function(b){b=b||1,a.render.active=!0,a.dispatch.render_start();var c=function(){for(var d,e,f=0;b>f&&(e=a.render.queue[f]);f++)d=e.generate(),typeof e.callback==typeof Function&&e.callback(d);a.render.queue.splice(0,f),a.render.queue.length?setTimeout(c):(a.dispatch.render_end(),a.render.active=!1)};setTimeout(c)},a.render.active=!1,a.render.queue=[],a.addGraph=function(b){typeof arguments[0]==typeof Function&&(b={generate:arguments[0],callback:arguments[1]}),a.render.queue.push(b),a.render.active||a.render()},"undefined"!=typeof module&&"undefined"!=typeof exports&&(module.exports=a),"undefined"!=typeof window&&(window.nv=a),a.dom.write=function(a){return void 0!==window.fastdom?fastdom.write(a):a()},a.dom.read=function(a){return void 0!==window.fastdom?fastdom.read(a):a()},a.interactiveGuideline=function(){"use strict";function b(l){l.each(function(l){function m(){var a=d3.mouse(this),d=a[0],e=a[1],i=!0,j=!1;if(k&&(d=d3.event.offsetX,e=d3.event.offsetY,"svg"!==d3.event.target.tagName&&(i=!1),d3.event.target.className.baseVal.match("nv-legend")&&(j=!0)),i&&(d-=f.left,e-=f.top),0>d||0>e||d>o||e>p||d3.event.relatedTarget&&void 0===d3.event.relatedTarget.ownerSVGElement||j){if(k&&d3.event.relatedTarget&&void 0===d3.event.relatedTarget.ownerSVGElement&&(void 0===d3.event.relatedTarget.className||d3.event.relatedTarget.className.match(c.nvPointerEventsClass)))return;return h.elementMouseout({mouseX:d,mouseY:e}),b.renderGuideLine(null),void c.hidden(!0)}c.hidden(!1);var l=g.invert(d);h.elementMousemove({mouseX:d,mouseY:e,pointXValue:l}),"dblclick"===d3.event.type&&h.elementDblclick({mouseX:d,mouseY:e,pointXValue:l}),"click"===d3.event.type&&h.elementClick({mouseX:d,mouseY:e,pointXValue:l})}var n=d3.select(this),o=d||960,p=e||400,q=n.selectAll("g.nv-wrap.nv-interactiveLineLayer").data([l]),r=q.enter().append("g").attr("class"," nv-wrap nv-interactiveLineLayer");r.append("g").attr("class","nv-interactiveGuideLine"),j&&(j.on("touchmove",m).on("mousemove",m,!0).on("mouseout",m,!0).on("dblclick",m).on("click",m),b.guideLine=null,b.renderGuideLine=function(c){i&&(b.guideLine&&b.guideLine.attr("x1")===c||a.dom.write(function(){var b=q.select(".nv-interactiveGuideLine").selectAll("line").data(null!=c?[a.utils.NaNtoZero(c)]:[],String);b.enter().append("line").attr("class","nv-guideline").attr("x1",function(a){return a}).attr("x2",function(a){return a}).attr("y1",p).attr("y2",0),b.exit().remove()}))})})}var c=a.models.tooltip();c.duration(0).hideDelay(0)._isInteractiveLayer(!0).hidden(!1);var d=null,e=null,f={left:0,top:0},g=d3.scale.linear(),h=d3.dispatch("elementMousemove","elementMouseout","elementClick","elementDblclick"),i=!0,j=null,k="ActiveXObject"in window;return b.dispatch=h,b.tooltip=c,b.margin=function(a){return arguments.length?(f.top="undefined"!=typeof a.top?a.top:f.top,f.left="undefined"!=typeof a.left?a.left:f.left,b):f},b.width=function(a){return arguments.length?(d=a,b):d},b.height=function(a){return arguments.length?(e=a,b):e},b.xScale=function(a){return arguments.length?(g=a,b):g},b.showGuideLine=function(a){return arguments.length?(i=a,b):i},b.svgContainer=function(a){return arguments.length?(j=a,b):j},b},a.interactiveBisect=function(a,b,c){"use strict";if(!(a instanceof Array))return null;var d;d="function"!=typeof c?function(a){return a.x}:c;var e=function(a,b){return d(a)-b},f=d3.bisector(e).left,g=d3.max([0,f(a,b)-1]),h=d(a[g]);if("undefined"==typeof h&&(h=g),h===b)return g;var i=d3.min([g+1,a.length-1]),j=d(a[i]);return"undefined"==typeof j&&(j=i),Math.abs(j-b)>=Math.abs(h-b)?g:i},a.nearestValueIndex=function(a,b,c){"use strict";var d=1/0,e=null;return a.forEach(function(a,f){var g=Math.abs(b-a);null!=a&&d>=g&&c>g&&(d=g,e=f)}),e},function(){"use strict";a.models.tooltip=function(){function b(){if(k){var a=d3.select(k);"svg"!==a.node().tagName&&(a=a.select("svg"));var b=a.node()?a.attr("viewBox"):null;if(b){b=b.split(" ");var c=parseInt(a.style("width"),10)/b[2];p.left=p.left*c,p.top=p.top*c}}}function c(){if(!n){var a;a=k?k:document.body,n=d3.select(a).append("div").attr("class","nvtooltip "+(j?j:"xy-tooltip")).attr("id",v),n.style("top",0).style("left",0),n.style("opacity",0),n.selectAll("div, table, td, tr").classed(w,!0),n.classed(w,!0),o=n.node()}}function d(){if(r&&B(e)){b();var f=p.left,g=null!==i?i:p.top;return a.dom.write(function(){c();var b=A(e);b&&(o.innerHTML=b),k&&u?a.dom.read(function(){var a=k.getElementsByTagName("svg")[0],b={left:0,top:0};if(a){var c=a.getBoundingClientRect(),d=k.getBoundingClientRect(),e=c.top;if(0>e){var i=k.getBoundingClientRect();e=Math.abs(e)>i.height?0:e}b.top=Math.abs(e-d.top),b.left=Math.abs(c.left-d.left)}f+=k.offsetLeft+b.left-2*k.scrollLeft,g+=k.offsetTop+b.top-2*k.scrollTop,h&&h>0&&(g=Math.floor(g/h)*h),C([f,g])}):C([f,g])}),d}}var e=null,f="w",g=25,h=0,i=null,j=null,k=null,l=!0,m=400,n=null,o=null,p={left:null,top:null},q={left:0,top:0},r=!0,s=100,t=!0,u=!1,v="nvtooltip-"+Math.floor(1e5*Math.random()),w="nv-pointer-events-none",x=function(a){return a},y=function(a){return a},z=function(a){return a},A=function(a){if(null===a)return"";var b=d3.select(document.createElement("table"));if(t){var c=b.selectAll("thead").data([a]).enter().append("thead");c.append("tr").append("td").attr("colspan",3).append("strong").classed("x-value",!0).html(y(a.value))}var d=b.selectAll("tbody").data([a]).enter().append("tbody"),e=d.selectAll("tr").data(function(a){return a.series}).enter().append("tr").classed("highlight",function(a){return a.highlight});e.append("td").classed("legend-color-guide",!0).append("div").style("background-color",function(a){return a.color}),e.append("td").classed("key",!0).html(function(a,b){return z(a.key,b)}),e.append("td").classed("value",!0).html(function(a,b){return x(a.value,b)}),e.selectAll("td").each(function(a){if(a.highlight){var b=d3.scale.linear().domain([0,1]).range(["#fff",a.color]),c=.6;d3.select(this).style("border-bottom-color",b(c)).style("border-top-color",b(c))}});var f=b.node().outerHTML;return void 0!==a.footer&&(f+="<div class='footer'>"+a.footer+"</div>"),f},B=function(a){if(a&&a.series){if(a.series instanceof Array)return!!a.series.length;if(a.series instanceof Object)return a.series=[a.series],!0}return!1},C=function(b){o&&a.dom.read(function(){var c,d,e=parseInt(o.offsetHeight,10),h=parseInt(o.offsetWidth,10),i=a.utils.windowSize().width,j=a.utils.windowSize().height,k=window.pageYOffset,p=window.pageXOffset;j=window.innerWidth>=document.body.scrollWidth?j:j-16,i=window.innerHeight>=document.body.scrollHeight?i:i-16;var r,t,u=function(a){var b=d;do isNaN(a.offsetTop)||(b+=a.offsetTop),a=a.offsetParent;while(a);return b},v=function(a){var b=c;do isNaN(a.offsetLeft)||(b+=a.offsetLeft),a=a.offsetParent;while(a);return b};switch(f){case"e":c=b[0]-h-g,d=b[1]-e/2,r=v(o),t=u(o),p>r&&(c=b[0]+g>p?b[0]+g:p-r+c),k>t&&(d=k-t+d),t+e>k+j&&(d=k+j-t+d-e);break;case"w":c=b[0]+g,d=b[1]-e/2,r=v(o),t=u(o),r+h>i&&(c=b[0]-h-g),k>t&&(d=k+5),t+e>k+j&&(d=k+j-t+d-e);break;case"n":c=b[0]-h/2-5,d=b[1]+g,r=v(o),t=u(o),p>r&&(c=p+5),r+h>i&&(c=c-h/2+5),t+e>k+j&&(d=k+j-t+d-e);break;case"s":c=b[0]-h/2,d=b[1]-e-g,r=v(o),t=u(o),p>r&&(c=p+5),r+h>i&&(c=c-h/2+5),k>t&&(d=k);break;case"none":c=b[0],d=b[1]-g,r=v(o),t=u(o)}c-=q.left,d-=q.top;var w=o.getBoundingClientRect(),k=window.pageYOffset||document.documentElement.scrollTop,p=window.pageXOffset||document.documentElement.scrollLeft,x="translate("+(w.left+p)+"px, "+(w.top+k)+"px)",y="translate("+c+"px, "+d+"px)",z=d3.interpolateString(x,y),A=n.style("opacity")<.1;l?n.transition().delay(m).duration(0).style("opacity",0):n.interrupt().transition().duration(A?0:s).styleTween("transform",function(){return z},"important").style("-webkit-transform",y).style("opacity",1)})};return d.nvPointerEventsClass=w,d.options=a.utils.optionsFunc.bind(d),d._options=Object.create({},{duration:{get:function(){return s},set:function(a){s=a}},gravity:{get:function(){return f},set:function(a){f=a}},distance:{get:function(){return g},set:function(a){g=a}},snapDistance:{get:function(){return h},set:function(a){h=a}},classes:{get:function(){return j},set:function(a){j=a}},chartContainer:{get:function(){return k},set:function(a){k=a}},fixedTop:{get:function(){return i},set:function(a){i=a}},enabled:{get:function(){return r},set:function(a){r=a}},hideDelay:{get:function(){return m},set:function(a){m=a}},contentGenerator:{get:function(){return A},set:function(a){A=a}},valueFormatter:{get:function(){return x},set:function(a){x=a}},headerFormatter:{get:function(){return y},set:function(a){y=a}},keyFormatter:{get:function(){return z},set:function(a){z=a}},headerEnabled:{get:function(){return t},set:function(a){t=a}},_isInteractiveLayer:{get:function(){return u},set:function(a){u=!!a}},position:{get:function(){return p},set:function(a){p.left=void 0!==a.left?a.left:p.left,p.top=void 0!==a.top?a.top:p.top}},offset:{get:function(){return q},set:function(a){q.left=void 0!==a.left?a.left:q.left,q.top=void 0!==a.top?a.top:q.top}},hidden:{get:function(){return l},set:function(a){l!=a&&(l=!!a,d())}},data:{get:function(){return e},set:function(a){a.point&&(a.value=a.point.x,a.series=a.series||{},a.series.value=a.point.y,a.series.color=a.point.color||a.series.color),e=a}},tooltipElem:{get:function(){return o},set:function(){}},id:{get:function(){return v},set:function(){}}}),a.utils.initOptions(d),d}}(),a.utils.windowSize=function(){var a={width:640,height:480};return window.innerWidth&&window.innerHeight?(a.width=window.innerWidth,a.height=window.innerHeight,a):"CSS1Compat"==document.compatMode&&document.documentElement&&document.documentElement.offsetWidth?(a.width=document.documentElement.offsetWidth,a.height=document.documentElement.offsetHeight,a):document.body&&document.body.offsetWidth?(a.width=document.body.offsetWidth,a.height=document.body.offsetHeight,a):a},a.utils.windowResize=function(b){return window.addEventListener?window.addEventListener("resize",b):a.log("ERROR: Failed to bind to window.resize with: ",b),{callback:b,clear:function(){window.removeEventListener("resize",b)}}},a.utils.getColor=function(b){if(void 0===b)return a.utils.defaultColor();if(Array.isArray(b)){var c=d3.scale.ordinal().range(b);return function(a,b){var d=void 0===b?a:b;return a.color||c(d)}}return b},a.utils.defaultColor=function(){return a.utils.getColor(d3.scale.category20().range())},a.utils.customTheme=function(a,b,c){b=b||function(a){return a.key},c=c||d3.scale.category20().range();var d=c.length;return function(e){var f=b(e);return"function"==typeof a[f]?a[f]():void 0!==a[f]?a[f]:(d||(d=c.length),d-=1,c[d])}},a.utils.pjax=function(b,c){var d=function(d){d3.html(d,function(d){var e=d3.select(c).node();e.parentNode.replaceChild(d3.select(d).select(c).node(),e),a.utils.pjax(b,c)})};d3.selectAll(b).on("click",function(){history.pushState(this.href,this.textContent,this.href),d(this.href),d3.event.preventDefault()}),d3.select(window).on("popstate",function(){d3.event.state&&d(d3.event.state)})},a.utils.calcApproxTextWidth=function(a){if("function"==typeof a.style&&"function"==typeof a.text){var b=parseInt(a.style("font-size").replace("px",""),10),c=a.text().length;return c*b*.5}return 0},a.utils.NaNtoZero=function(a){return"number"!=typeof a||isNaN(a)||null===a||1/0===a||a===-1/0?0:a},d3.selection.prototype.watchTransition=function(a){var b=[this].concat([].slice.call(arguments,1));return a.transition.apply(a,b)},a.utils.renderWatch=function(b,c){if(!(this instanceof a.utils.renderWatch))return new a.utils.renderWatch(b,c);var d=void 0!==c?c:250,e=[],f=this;this.models=function(a){return a=[].slice.call(arguments,0),a.forEach(function(a){a.__rendered=!1,function(a){a.dispatch.on("renderEnd",function(){a.__rendered=!0,f.renderEnd("model")})}(a),e.indexOf(a)<0&&e.push(a)}),this},this.reset=function(a){void 0!==a&&(d=a),e=[]},this.transition=function(a,b,c){if(b=arguments.length>1?[].slice.call(arguments,1):[],c=b.length>1?b.pop():void 0!==d?d:250,a.__rendered=!1,e.indexOf(a)<0&&e.push(a),0===c)return a.__rendered=!0,a.delay=function(){return this},a.duration=function(){return this},a;a.__rendered=0===a.length?!0:a.every(function(a){return!a.length})?!0:!1;var g=0;return a.transition().duration(c).each(function(){++g}).each("end",function(){0===--g&&(a.__rendered=!0,f.renderEnd.apply(this,b))})},this.renderEnd=function(){e.every(function(a){return a.__rendered})&&(e.forEach(function(a){a.__rendered=!1}),b.renderEnd.apply(this,arguments))}},a.utils.deepExtend=function(b){var c=arguments.length>1?[].slice.call(arguments,1):[];c.forEach(function(c){for(var d in c){var e=b[d]instanceof Array,f="object"==typeof b[d],g="object"==typeof c[d];f&&!e&&g?a.utils.deepExtend(b[d],c[d]):b[d]=c[d]}})},a.utils.state=function(){if(!(this instanceof a.utils.state))return new a.utils.state;var b={},c=function(){},d=function(){return{}},e=null,f=null;this.dispatch=d3.dispatch("change","set"),this.dispatch.on("set",function(a){c(a,!0)}),this.getter=function(a){return d=a,this},this.setter=function(a,b){return b||(b=function(){}),c=function(c,d){a(c),d&&b()},this},this.init=function(b){e=e||{},a.utils.deepExtend(e,b)};var g=function(){var a=d();if(JSON.stringify(a)===JSON.stringify(b))return!1;for(var c in a)void 0===b[c]&&(b[c]={}),b[c]=a[c],f=!0;return!0};this.update=function(){e&&(c(e,!1),e=null),g.call(this)&&this.dispatch.change(b)}},a.utils.optionsFunc=function(a){return a&&d3.map(a).forEach(function(a,b){"function"==typeof this[a]&&this[a](b)}.bind(this)),this},a.utils.calcTicksX=function(b,c){var d=1,e=0;for(e;e<c.length;e+=1){var f=c[e]&&c[e].values?c[e].values.length:0;d=f>d?f:d}return a.log("Requested number of ticks: ",b),a.log("Calculated max values to be: ",d),b=b>d?b=d-1:b,b=1>b?1:b,b=Math.floor(b),a.log("Calculating tick count as: ",b),b},a.utils.calcTicksY=function(b,c){return a.utils.calcTicksX(b,c)},a.utils.initOption=function(a,b){a._calls&&a._calls[b]?a[b]=a._calls[b]:(a[b]=function(c){return arguments.length?(a._overrides[b]=!0,a._options[b]=c,a):a._options[b]},a["_"+b]=function(c){return arguments.length?(a._overrides[b]||(a._options[b]=c),a):a._options[b]})},a.utils.initOptions=function(b){b._overrides=b._overrides||{};var c=Object.getOwnPropertyNames(b._options||{}),d=Object.getOwnPropertyNames(b._calls||{});c=c.concat(d);for(var e in c)a.utils.initOption(b,c[e])},a.utils.inheritOptionsD3=function(a,b,c){a._d3options=c.concat(a._d3options||[]),c.unshift(b),c.unshift(a),d3.rebind.apply(this,c)},a.utils.arrayUnique=function(a){return a.sort().filter(function(b,c){return!c||b!=a[c-1]})},a.utils.symbolMap=d3.map(),a.utils.symbol=function(){function b(b,e){var f=c.call(this,b,e),g=d.call(this,b,e);return-1!==d3.svg.symbolTypes.indexOf(f)?d3.svg.symbol().type(f).size(g)():a.utils.symbolMap.get(f)(g)}var c,d=64;return b.type=function(a){return arguments.length?(c=d3.functor(a),b):c},b.size=function(a){return arguments.length?(d=d3.functor(a),b):d},b},a.utils.inheritOptions=function(b,c){var d=Object.getOwnPropertyNames(c._options||{}),e=Object.getOwnPropertyNames(c._calls||{}),f=c._inherited||[],g=c._d3options||[],h=d.concat(e).concat(f).concat(g);h.unshift(c),h.unshift(b),d3.rebind.apply(this,h),b._inherited=a.utils.arrayUnique(d.concat(e).concat(f).concat(d).concat(b._inherited||[])),b._d3options=a.utils.arrayUnique(g.concat(b._d3options||[]))},a.utils.initSVG=function(a){a.classed({"nvd3-svg":!0})},a.utils.sanitizeHeight=function(a,b){return a||parseInt(b.style("height"),10)||400},a.utils.sanitizeWidth=function(a,b){return a||parseInt(b.style("width"),10)||960},a.utils.availableHeight=function(b,c,d){return a.utils.sanitizeHeight(b,c)-d.top-d.bottom},a.utils.availableWidth=function(b,c,d){return a.utils.sanitizeWidth(b,c)-d.left-d.right},a.utils.noData=function(b,c){var d=b.options(),e=d.margin(),f=d.noData(),g=null==f?["No Data Available."]:[f],h=a.utils.availableHeight(d.height(),c,e),i=a.utils.availableWidth(d.width(),c,e),j=e.left+i/2,k=e.top+h/2;c.selectAll("g").remove();var l=c.selectAll(".nv-noData").data(g);l.enter().append("text").attr("class","nvd3 nv-noData").attr("dy","-.7em").style("text-anchor","middle"),l.attr("x",j).attr("y",k).text(function(a){return a})},a.models.axis=function(){"use strict";function b(g){return s.reset(),g.each(function(b){var g=d3.select(this);a.utils.initSVG(g);var p=g.selectAll("g.nv-wrap.nv-axis").data([b]),q=p.enter().append("g").attr("class","nvd3 nv-wrap nv-axis"),t=(q.append("g"),p.select("g"));null!==n?c.ticks(n):("top"==c.orient()||"bottom"==c.orient())&&c.ticks(Math.abs(d.range()[1]-d.range()[0])/100),t.watchTransition(s,"axis").call(c),r=r||c.scale();var u=c.tickFormat();null==u&&(u=r.tickFormat());var v=t.selectAll("text.nv-axislabel").data([h||null]);v.exit().remove();var w,x,y;switch(c.orient()){case"top":v.enter().append("text").attr("class","nv-axislabel"),y=d.range().length<2?0:2===d.range().length?d.range()[1]:d.range()[d.range().length-1]+(d.range()[1]-d.range()[0]),v.attr("text-anchor","middle").attr("y",0).attr("x",y/2),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-x",0==b?"nv-axisMin-x":"nv-axisMax-x"].join(" ")}).append("text"),x.exit().remove(),x.attr("transform",function(b){return"translate("+a.utils.NaNtoZero(d(b))+",0)"}).select("text").attr("dy","-0.5em").attr("y",-c.tickPadding()).attr("text-anchor","middle").text(function(a){var b=u(a);return(""+b).match("NaN")?"":b}),x.watchTransition(s,"min-max top").attr("transform",function(b,c){return"translate("+a.utils.NaNtoZero(d.range()[c])+",0)"}));break;case"bottom":w=o+36;var z=30,A=0,B=t.selectAll("g").select("text"),C="";if(j%360){B.each(function(){var a=this.getBoundingClientRect(),b=a.width;A=a.height,b>z&&(z=b)}),C="rotate("+j+" 0,"+(A/2+c.tickPadding())+")";var D=Math.abs(Math.sin(j*Math.PI/180));w=(D?D*z:z)+30,B.attr("transform",C).style("text-anchor",j%360>0?"start":"end")}v.enter().append("text").attr("class","nv-axislabel"),y=d.range().length<2?0:2===d.range().length?d.range()[1]:d.range()[d.range().length-1]+(d.range()[1]-d.range()[0]),v.attr("text-anchor","middle").attr("y",w).attr("x",y/2),i&&(x=p.selectAll("g.nv-axisMaxMin").data([d.domain()[0],d.domain()[d.domain().length-1]]),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-x",0==b?"nv-axisMin-x":"nv-axisMax-x"].join(" ")}).append("text"),x.exit().remove(),x.attr("transform",function(b){return"translate("+a.utils.NaNtoZero(d(b)+(m?d.rangeBand()/2:0))+",0)"}).select("text").attr("dy",".71em").attr("y",c.tickPadding()).attr("transform",C).style("text-anchor",j?j%360>0?"start":"end":"middle").text(function(a){var b=u(a);return(""+b).match("NaN")?"":b}),x.watchTransition(s,"min-max bottom").attr("transform",function(b){return"translate("+a.utils.NaNtoZero(d(b)+(m?d.rangeBand()/2:0))+",0)"})),l&&B.attr("transform",function(a,b){return"translate(0,"+(b%2==0?"0":"12")+")"});break;case"right":v.enter().append("text").attr("class","nv-axislabel"),v.style("text-anchor",k?"middle":"begin").attr("transform",k?"rotate(90)":"").attr("y",k?-Math.max(e.right,f)+12:-10).attr("x",k?d3.max(d.range())/2:c.tickPadding()),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-y",0==b?"nv-axisMin-y":"nv-axisMax-y"].join(" ")}).append("text").style("opacity",0),x.exit().remove(),x.attr("transform",function(b){return"translate(0,"+a.utils.NaNtoZero(d(b))+")"}).select("text").attr("dy",".32em").attr("y",0).attr("x",c.tickPadding()).style("text-anchor","start").text(function(a){var b=u(a);return(""+b).match("NaN")?"":b}),x.watchTransition(s,"min-max right").attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(d.range()[c])+")"}).select("text").style("opacity",1));break;case"left":v.enter().append("text").attr("class","nv-axislabel"),v.style("text-anchor",k?"middle":"end").attr("transform",k?"rotate(-90)":"").attr("y",k?-Math.max(e.left,f)+25-(o||0):-10).attr("x",k?-d3.max(d.range())/2:-c.tickPadding()),i&&(x=p.selectAll("g.nv-axisMaxMin").data(d.domain()),x.enter().append("g").attr("class",function(a,b){return["nv-axisMaxMin","nv-axisMaxMin-y",0==b?"nv-axisMin-y":"nv-axisMax-y"].join(" ")}).append("text").style("opacity",0),x.exit().remove(),x.attr("transform",function(b){return"translate(0,"+a.utils.NaNtoZero(r(b))+")"}).select("text").attr("dy",".32em").attr("y",0).attr("x",-c.tickPadding()).attr("text-anchor","end").text(function(a){var b=u(a);return(""+b).match("NaN")?"":b}),x.watchTransition(s,"min-max right").attr("transform",function(b,c){return"translate(0,"+a.utils.NaNtoZero(d.range()[c])+")"}).select("text").style("opacity",1))}if(v.text(function(a){return a}),!i||"left"!==c.orient()&&"right"!==c.orient()||(t.selectAll("g").each(function(a){d3.select(this).select("text").attr("opacity",1),(d(a)<d.range()[1]+10||d(a)>d.range()[0]-10)&&((a>1e-10||-1e-10>a)&&d3.select(this).attr("opacity",0),d3.select(this).select("text").attr("opacity",0))}),d.domain()[0]==d.domain()[1]&&0==d.domain()[0]&&p.selectAll("g.nv-axisMaxMin").style("opacity",function(a,b){return b?0:1})),i&&("top"===c.orient()||"bottom"===c.orient())){var E=[];p.selectAll("g.nv-axisMaxMin").each(function(a,b){try{E.push(b?d(a)-this.getBoundingClientRect().width-4:d(a)+this.getBoundingClientRect().width+4)}catch(c){E.push(b?d(a)-4:d(a)+4)}}),t.selectAll("g").each(function(a){(d(a)<E[0]||d(a)>E[1])&&(a>1e-10||-1e-10>a?d3.select(this).remove():d3.select(this).select("text").remove())})}t.selectAll(".tick").filter(function(a){return!parseFloat(Math.round(1e5*a)/1e6)&&void 0!==a}).classed("zero",!0),r=d.copy()}),s.renderEnd("axis immediate"),b}var c=d3.svg.axis(),d=d3.scale.linear(),e={top:0,right:0,bottom:0,left:0},f=75,g=60,h=null,i=!0,j=0,k=!0,l=!1,m=!1,n=null,o=0,p=250,q=d3.dispatch("renderEnd");c.scale(d).orient("bottom").tickFormat(function(a){return a});var r,s=a.utils.renderWatch(q,p);return b.axis=c,b.dispatch=q,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{axisLabelDistance:{get:function(){return o},set:function(a){o=a}},staggerLabels:{get:function(){return l},set:function(a){l=a}},rotateLabels:{get:function(){return j},set:function(a){j=a}},rotateYLabel:{get:function(){return k},set:function(a){k=a}},showMaxMin:{get:function(){return i},set:function(a){i=a}},axisLabel:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return g},set:function(a){g=a}},ticks:{get:function(){return n},set:function(a){n=a}},width:{get:function(){return f},set:function(a){f=a}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},duration:{get:function(){return p},set:function(a){p=a,s.reset(p)}},scale:{get:function(){return d},set:function(e){d=e,c.scale(d),m="function"==typeof d.rangeBands,a.utils.inheritOptionsD3(b,d,["domain","range","rangeBand","rangeBands"])}}}),a.utils.initOptions(b),a.utils.inheritOptionsD3(b,c,["orient","tickValues","tickSubdivide","tickSize","tickPadding","tickFormat"]),a.utils.inheritOptionsD3(b,d,["domain","range","rangeBand","rangeBands"]),b},a.models.boxPlot=function(){"use strict";function b(l){return v.reset(),l.each(function(b){var l=j-i.left-i.right,p=k-i.top-i.bottom;r=d3.select(this),a.utils.initSVG(r),m.domain(c||b.map(function(a,b){return o(a,b)})).rangeBands(e||[0,l],.1);var w=[];if(!d){var x=d3.min(b.map(function(a){var b=[];return b.push(a.values.Q1),a.values.hasOwnProperty("whisker_low")&&null!==a.values.whisker_low&&b.push(a.values.whisker_low),a.values.hasOwnProperty("outliers")&&null!==a.values.outliers&&(b=b.concat(a.values.outliers)),d3.min(b)})),y=d3.max(b.map(function(a){var b=[];return b.push(a.values.Q3),a.values.hasOwnProperty("whisker_high")&&null!==a.values.whisker_high&&b.push(a.values.whisker_high),a.values.hasOwnProperty("outliers")&&null!==a.values.outliers&&(b=b.concat(a.values.outliers)),d3.max(b)}));w=[x,y]}n.domain(d||w),n.range(f||[p,0]),g=g||m,h=h||n.copy().range([n(0),n(0)]);{var z=r.selectAll("g.nv-wrap").data([b]);z.enter().append("g").attr("class","nvd3 nv-wrap")}z.attr("transform","translate("+i.left+","+i.top+")");var A=z.selectAll(".nv-boxplot").data(function(a){return a}),B=A.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6);A.attr("class","nv-boxplot").attr("transform",function(a,b){return"translate("+(m(o(a,b))+.05*m.rangeBand())+", 0)"}).classed("hover",function(a){return a.hover}),A.watchTransition(v,"nv-boxplot: boxplots").style("stroke-opacity",1).style("fill-opacity",.75).delay(function(a,c){return c*t/b.length}).attr("transform",function(a,b){return"translate("+(m(o(a,b))+.05*m.rangeBand())+", 0)"}),A.exit().remove(),B.each(function(a,b){var c=d3.select(this);["low","high"].forEach(function(d){a.values.hasOwnProperty("whisker_"+d)&&null!==a.values["whisker_"+d]&&(c.append("line").style("stroke",a.color?a.color:q(a,b)).attr("class","nv-boxplot-whisker nv-boxplot-"+d),c.append("line").style("stroke",a.color?a.color:q(a,b)).attr("class","nv-boxplot-tick nv-boxplot-"+d))})});var C=A.selectAll(".nv-boxplot-outlier").data(function(a){return a.values.hasOwnProperty("outliers")&&null!==a.values.outliers?a.values.outliers:[]});C.enter().append("circle").style("fill",function(a,b,c){return q(a,c)}).style("stroke",function(a,b,c){return q(a,c)}).on("mouseover",function(a,b,c){d3.select(this).classed("hover",!0),s.elementMouseover({series:{key:a,color:q(a,c)},e:d3.event})}).on("mouseout",function(a,b,c){d3.select(this).classed("hover",!1),s.elementMouseout({series:{key:a,color:q(a,c)},e:d3.event})}).on("mousemove",function(){s.elementMousemove({e:d3.event})}),C.attr("class","nv-boxplot-outlier"),C.watchTransition(v,"nv-boxplot: nv-boxplot-outlier").attr("cx",.45*m.rangeBand()).attr("cy",function(a){return n(a)}).attr("r","3"),C.exit().remove();var D=function(){return null===u?.9*m.rangeBand():Math.min(75,.9*m.rangeBand())},E=function(){return.45*m.rangeBand()-D()/2},F=function(){return.45*m.rangeBand()+D()/2};["low","high"].forEach(function(a){var b="low"===a?"Q1":"Q3";A.select("line.nv-boxplot-whisker.nv-boxplot-"+a).watchTransition(v,"nv-boxplot: boxplots").attr("x1",.45*m.rangeBand()).attr("y1",function(b){return n(b.values["whisker_"+a])}).attr("x2",.45*m.rangeBand()).attr("y2",function(a){return n(a.values[b])}),A.select("line.nv-boxplot-tick.nv-boxplot-"+a).watchTransition(v,"nv-boxplot: boxplots").attr("x1",E).attr("y1",function(b){return n(b.values["whisker_"+a])}).attr("x2",F).attr("y2",function(b){return n(b.values["whisker_"+a])})}),["low","high"].forEach(function(a){B.selectAll(".nv-boxplot-"+a).on("mouseover",function(b,c,d){d3.select(this).classed("hover",!0),s.elementMouseover({series:{key:b.values["whisker_"+a],color:q(b,d)},e:d3.event})}).on("mouseout",function(b,c,d){d3.select(this).classed("hover",!1),s.elementMouseout({series:{key:b.values["whisker_"+a],color:q(b,d)},e:d3.event})}).on("mousemove",function(){s.elementMousemove({e:d3.event})})}),B.append("rect").attr("class","nv-boxplot-box").on("mouseover",function(a,b){d3.select(this).classed("hover",!0),s.elementMouseover({key:a.label,value:a.label,series:[{key:"Q3",value:a.values.Q3,color:a.color||q(a,b)},{key:"Q2",value:a.values.Q2,color:a.color||q(a,b)},{key:"Q1",value:a.values.Q1,color:a.color||q(a,b)}],data:a,index:b,e:d3.event})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),s.elementMouseout({key:a.label,value:a.label,series:[{key:"Q3",value:a.values.Q3,color:a.color||q(a,b)},{key:"Q2",value:a.values.Q2,color:a.color||q(a,b)},{key:"Q1",value:a.values.Q1,color:a.color||q(a,b)}],data:a,index:b,e:d3.event})}).on("mousemove",function(){s.elementMousemove({e:d3.event})}),A.select("rect.nv-boxplot-box").watchTransition(v,"nv-boxplot: boxes").attr("y",function(a){return n(a.values.Q3)}).attr("width",D).attr("x",E).attr("height",function(a){return Math.abs(n(a.values.Q3)-n(a.values.Q1))||1}).style("fill",function(a,b){return a.color||q(a,b)}).style("stroke",function(a,b){return a.color||q(a,b)}),B.append("line").attr("class","nv-boxplot-median"),A.select("line.nv-boxplot-median").watchTransition(v,"nv-boxplot: boxplots line").attr("x1",E).attr("y1",function(a){return n(a.values.Q2)}).attr("x2",F).attr("y2",function(a){return n(a.values.Q2)}),g=m.copy(),h=n.copy()}),v.renderEnd("nv-boxplot immediate"),b}var c,d,e,f,g,h,i={top:0,right:0,bottom:0,left:0},j=960,k=500,l=Math.floor(1e4*Math.random()),m=d3.scale.ordinal(),n=d3.scale.linear(),o=function(a){return a.x},p=function(a){return a.y},q=a.utils.defaultColor(),r=null,s=d3.dispatch("elementMouseover","elementMouseout","elementMousemove","renderEnd"),t=250,u=null,v=a.utils.renderWatch(s,t);return b.dispatch=s,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return j},set:function(a){j=a}},height:{get:function(){return k},set:function(a){k=a}},maxBoxWidth:{get:function(){return u},set:function(a){u=a}},x:{get:function(){return o},set:function(a){o=a}},y:{get:function(){return p},set:function(a){p=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},id:{get:function(){return l},set:function(a){l=a}},margin:{get:function(){return i},set:function(a){i.top=void 0!==a.top?a.top:i.top,i.right=void 0!==a.right?a.right:i.right,i.bottom=void 0!==a.bottom?a.bottom:i.bottom,i.left=void 0!==a.left?a.left:i.left}},color:{get:function(){return q},set:function(b){q=a.utils.getColor(b)}},duration:{get:function(){return t},set:function(a){t=a,v.reset(t)}}}),a.utils.initOptions(b),b},a.models.boxPlotChart=function(){"use strict";function b(k){return t.reset(),t.models(e),l&&t.models(f),m&&t.models(g),k.each(function(k){var p=d3.select(this);a.utils.initSVG(p);var t=(i||parseInt(p.style("width"))||960)-h.left-h.right,u=(j||parseInt(p.style("height"))||400)-h.top-h.bottom;if(b.update=function(){r.beforeUpdate(),p.transition().duration(s).call(b)},b.container=this,!(k&&k.length&&k.filter(function(a){return a.values.hasOwnProperty("Q1")&&a.values.hasOwnProperty("Q2")&&a.values.hasOwnProperty("Q3")}).length)){var v=p.selectAll(".nv-noData").data([q]);return v.enter().append("text").attr("class","nvd3 nv-noData").attr("dy","-.7em").style("text-anchor","middle"),v.attr("x",h.left+t/2).attr("y",h.top+u/2).text(function(a){return a}),b}p.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale().clamp(!0);var w=p.selectAll("g.nv-wrap.nv-boxPlotWithAxes").data([k]),x=w.enter().append("g").attr("class","nvd3 nv-wrap nv-boxPlotWithAxes").append("g"),y=x.append("defs"),z=w.select("g");
x.append("g").attr("class","nv-x nv-axis"),x.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),x.append("g").attr("class","nv-barsWrap"),z.attr("transform","translate("+h.left+","+h.top+")"),n&&z.select(".nv-y.nv-axis").attr("transform","translate("+t+",0)"),e.width(t).height(u);var A=z.select(".nv-barsWrap").datum(k.filter(function(a){return!a.disabled}));if(A.transition().call(e),y.append("clipPath").attr("id","nv-x-label-clip-"+e.id()).append("rect"),z.select("#nv-x-label-clip-"+e.id()+" rect").attr("width",c.rangeBand()*(o?2:1)).attr("height",16).attr("x",-c.rangeBand()/(o?1:2)),l){f.scale(c).ticks(a.utils.calcTicksX(t/100,k)).tickSize(-u,0),z.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),z.select(".nv-x.nv-axis").call(f);var B=z.select(".nv-x.nv-axis").selectAll("g");o&&B.selectAll("text").attr("transform",function(a,b,c){return"translate(0,"+(c%2==0?"5":"17")+")"})}m&&(g.scale(d).ticks(Math.floor(u/36)).tickSize(-t,0),z.select(".nv-y.nv-axis").call(g)),z.select(".nv-zeroLine line").attr("x1",0).attr("x2",t).attr("y1",d(0)).attr("y2",d(0))}),t.renderEnd("nv-boxplot chart immediate"),b}var c,d,e=a.models.boxPlot(),f=a.models.axis(),g=a.models.axis(),h={top:15,right:10,bottom:50,left:60},i=null,j=null,k=a.utils.getColor(),l=!0,m=!0,n=!1,o=!1,p=a.models.tooltip(),q="No Data Available.",r=d3.dispatch("tooltipShow","tooltipHide","beforeUpdate","renderEnd"),s=250;f.orient("bottom").showMaxMin(!1).tickFormat(function(a){return a}),g.orient(n?"right":"left").tickFormat(d3.format(",.1f")),p.duration(0);var t=a.utils.renderWatch(r,s);return e.dispatch.on("elementMouseover.tooltip",function(a){p.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(a){p.data(a).hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(){p.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=r,b.boxplot=e,b.xAxis=f,b.yAxis=g,b.tooltip=p,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return i},set:function(a){i=a}},height:{get:function(){return j},set:function(a){j=a}},staggerLabels:{get:function(){return o},set:function(a){o=a}},showXAxis:{get:function(){return l},set:function(a){l=a}},showYAxis:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return tooltips},set:function(a){tooltips=a}},tooltipContent:{get:function(){return p},set:function(a){p=a}},noData:{get:function(){return q},set:function(a){q=a}},margin:{get:function(){return h},set:function(a){h.top=void 0!==a.top?a.top:h.top,h.right=void 0!==a.right?a.right:h.right,h.bottom=void 0!==a.bottom?a.bottom:h.bottom,h.left=void 0!==a.left?a.left:h.left}},duration:{get:function(){return s},set:function(a){s=a,t.reset(s),e.duration(s),f.duration(s),g.duration(s)}},color:{get:function(){return k},set:function(b){k=a.utils.getColor(b),e.color(k)}},rightAlignYAxis:{get:function(){return n},set:function(a){n=a,g.orient(a?"right":"left")}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.bullet=function(){"use strict";function b(d){return d.each(function(b,d){var p=m-c.left-c.right,s=n-c.top-c.bottom;o=d3.select(this),a.utils.initSVG(o);{var t=f.call(this,b,d).slice().sort(d3.descending),u=g.call(this,b,d).slice().sort(d3.descending),v=h.call(this,b,d).slice().sort(d3.descending),w=i.call(this,b,d).slice(),x=j.call(this,b,d).slice(),y=k.call(this,b,d).slice(),z=d3.scale.linear().domain(d3.extent(d3.merge([l,t]))).range(e?[p,0]:[0,p]);this.__chart__||d3.scale.linear().domain([0,1/0]).range(z.range())}this.__chart__=z;var A=d3.min(t),B=d3.max(t),C=t[1],D=o.selectAll("g.nv-wrap.nv-bullet").data([b]),E=D.enter().append("g").attr("class","nvd3 nv-wrap nv-bullet"),F=E.append("g"),G=D.select("g");F.append("rect").attr("class","nv-range nv-rangeMax"),F.append("rect").attr("class","nv-range nv-rangeAvg"),F.append("rect").attr("class","nv-range nv-rangeMin"),F.append("rect").attr("class","nv-measure"),D.attr("transform","translate("+c.left+","+c.top+")");var H=function(a){return Math.abs(z(a)-z(0))},I=function(a){return z(0>a?a:0)};G.select("rect.nv-rangeMax").attr("height",s).attr("width",H(B>0?B:A)).attr("x",I(B>0?B:A)).datum(B>0?B:A),G.select("rect.nv-rangeAvg").attr("height",s).attr("width",H(C)).attr("x",I(C)).datum(C),G.select("rect.nv-rangeMin").attr("height",s).attr("width",H(B)).attr("x",I(B)).attr("width",H(B>0?A:B)).attr("x",I(B>0?A:B)).datum(B>0?A:B),G.select("rect.nv-measure").style("fill",q).attr("height",s/3).attr("y",s/3).attr("width",0>v?z(0)-z(v[0]):z(v[0])-z(0)).attr("x",I(v)).on("mouseover",function(){r.elementMouseover({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})}).on("mousemove",function(){r.elementMousemove({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})}).on("mouseout",function(){r.elementMouseout({value:v[0],label:y[0]||"Current",color:d3.select(this).style("fill")})});var J=s/6,K=u.map(function(a,b){return{value:a,label:x[b]}});F.selectAll("path.nv-markerTriangle").data(K).enter().append("path").attr("class","nv-markerTriangle").attr("transform",function(a){return"translate("+z(a.value)+","+s/2+")"}).attr("d","M0,"+J+"L"+J+","+-J+" "+-J+","+-J+"Z").on("mouseover",function(a){r.elementMouseover({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill"),pos:[z(a.value),s/2]})}).on("mousemove",function(a){r.elementMousemove({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill")})}).on("mouseout",function(a){r.elementMouseout({value:a.value,label:a.label||"Previous",color:d3.select(this).style("fill")})}),D.selectAll(".nv-range").on("mouseover",function(a,b){var c=w[b]||(b?1==b?"Mean":"Minimum":"Maximum");r.elementMouseover({value:a,label:c,color:d3.select(this).style("fill")})}).on("mousemove",function(){r.elementMousemove({value:v[0],label:y[0]||"Previous",color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){var c=w[b]||(b?1==b?"Mean":"Minimum":"Maximum");r.elementMouseout({value:a,label:c,color:d3.select(this).style("fill")})})}),b}var c={top:0,right:0,bottom:0,left:0},d="left",e=!1,f=function(a){return a.ranges},g=function(a){return a.markers?a.markers:[0]},h=function(a){return a.measures},i=function(a){return a.rangeLabels?a.rangeLabels:[]},j=function(a){return a.markerLabels?a.markerLabels:[]},k=function(a){return a.measureLabels?a.measureLabels:[]},l=[0],m=380,n=30,o=null,p=null,q=a.utils.getColor(["#1f77b4"]),r=d3.dispatch("elementMouseover","elementMouseout","elementMousemove");return b.dispatch=r,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{ranges:{get:function(){return f},set:function(a){f=a}},markers:{get:function(){return g},set:function(a){g=a}},measures:{get:function(){return h},set:function(a){h=a}},forceX:{get:function(){return l},set:function(a){l=a}},width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},tickFormat:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},orient:{get:function(){return d},set:function(a){d=a,e="right"==d||"bottom"==d}},color:{get:function(){return q},set:function(b){q=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.bulletChart=function(){"use strict";function b(d){return d.each(function(e,o){var p=d3.select(this);a.utils.initSVG(p);var q=a.utils.availableWidth(k,p,g),r=l-g.top-g.bottom;if(b.update=function(){b(d)},b.container=this,!e||!h.call(this,e,o))return a.utils.noData(b,p),b;p.selectAll(".nv-noData").remove();var s=h.call(this,e,o).slice().sort(d3.descending),t=i.call(this,e,o).slice().sort(d3.descending),u=j.call(this,e,o).slice().sort(d3.descending),v=p.selectAll("g.nv-wrap.nv-bulletChart").data([e]),w=v.enter().append("g").attr("class","nvd3 nv-wrap nv-bulletChart"),x=w.append("g"),y=v.select("g");x.append("g").attr("class","nv-bulletWrap"),x.append("g").attr("class","nv-titles"),v.attr("transform","translate("+g.left+","+g.top+")");var z=d3.scale.linear().domain([0,Math.max(s[0],t[0],u[0])]).range(f?[q,0]:[0,q]),A=this.__chart__||d3.scale.linear().domain([0,1/0]).range(z.range());this.__chart__=z;var B=x.select(".nv-titles").append("g").attr("text-anchor","end").attr("transform","translate(-6,"+(l-g.top-g.bottom)/2+")");B.append("text").attr("class","nv-title").text(function(a){return a.title}),B.append("text").attr("class","nv-subtitle").attr("dy","1em").text(function(a){return a.subtitle}),c.width(q).height(r);var C=y.select(".nv-bulletWrap");d3.transition(C).call(c);var D=m||z.tickFormat(q/100),E=y.selectAll("g.nv-tick").data(z.ticks(n?n:q/50),function(a){return this.textContent||D(a)}),F=E.enter().append("g").attr("class","nv-tick").attr("transform",function(a){return"translate("+A(a)+",0)"}).style("opacity",1e-6);F.append("line").attr("y1",r).attr("y2",7*r/6),F.append("text").attr("text-anchor","middle").attr("dy","1em").attr("y",7*r/6).text(D);var G=d3.transition(E).attr("transform",function(a){return"translate("+z(a)+",0)"}).style("opacity",1);G.select("line").attr("y1",r).attr("y2",7*r/6),G.select("text").attr("y",7*r/6),d3.transition(E.exit()).attr("transform",function(a){return"translate("+z(a)+",0)"}).style("opacity",1e-6).remove()}),d3.timer.flush(),b}var c=a.models.bullet(),d=a.models.tooltip(),e="left",f=!1,g={top:5,right:40,bottom:20,left:120},h=function(a){return a.ranges},i=function(a){return a.markers?a.markers:[0]},j=function(a){return a.measures},k=null,l=55,m=null,n=null,o=null,p=d3.dispatch("tooltipShow","tooltipHide");return d.duration(0).headerEnabled(!1),c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:a.label,value:a.value,color:a.color},d.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(){d.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(){d.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.bullet=c,b.dispatch=p,b.tooltip=d,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{ranges:{get:function(){return h},set:function(a){h=a}},markers:{get:function(){return i},set:function(a){i=a}},measures:{get:function(){return j},set:function(a){j=a}},width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},tickFormat:{get:function(){return m},set:function(a){m=a}},ticks:{get:function(){return n},set:function(a){n=a}},noData:{get:function(){return o},set:function(a){o=a}},tooltips:{get:function(){return d.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),d.enabled(!!b)}},tooltipContent:{get:function(){return d.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),d.contentGenerator(b)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},orient:{get:function(){return e},set:function(a){e=a,f="right"==e||"bottom"==e}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.candlestickBar=function(){"use strict";function b(x){return x.each(function(b){c=d3.select(this);var x=a.utils.availableWidth(i,c,h),y=a.utils.availableHeight(j,c,h);a.utils.initSVG(c);var A=x/b[0].values.length*.45;l.domain(d||d3.extent(b[0].values.map(n).concat(t))),l.range(v?f||[.5*x/b[0].values.length,x*(b[0].values.length-.5)/b[0].values.length]:f||[5+A/2,x-A/2-5]),m.domain(e||[d3.min(b[0].values.map(s).concat(u)),d3.max(b[0].values.map(r).concat(u))]).range(g||[y,0]),l.domain()[0]===l.domain()[1]&&l.domain(l.domain()[0]?[l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]:[-1,1]),m.domain()[0]===m.domain()[1]&&m.domain(m.domain()[0]?[m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]:[-1,1]);var B=d3.select(this).selectAll("g.nv-wrap.nv-candlestickBar").data([b[0].values]),C=B.enter().append("g").attr("class","nvd3 nv-wrap nv-candlestickBar"),D=C.append("defs"),E=C.append("g"),F=B.select("g");E.append("g").attr("class","nv-ticks"),B.attr("transform","translate("+h.left+","+h.top+")"),c.on("click",function(a,b){z.chartClick({data:a,index:b,pos:d3.event,id:k})}),D.append("clipPath").attr("id","nv-chart-clip-path-"+k).append("rect"),B.select("#nv-chart-clip-path-"+k+" rect").attr("width",x).attr("height",y),F.attr("clip-path",w?"url(#nv-chart-clip-path-"+k+")":"");var G=B.select(".nv-ticks").selectAll(".nv-tick").data(function(a){return a});G.exit().remove();{var H=G.enter().append("g").attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b});H.append("line").attr("class","nv-candlestick-lines").attr("transform",function(a,b){return"translate("+l(n(a,b))+",0)"}).attr("x1",0).attr("y1",function(a,b){return m(r(a,b))}).attr("x2",0).attr("y2",function(a,b){return m(s(a,b))}),H.append("rect").attr("class","nv-candlestick-rects nv-bars").attr("transform",function(a,b){return"translate("+(l(n(a,b))-A/2)+","+(m(o(a,b))-(p(a,b)>q(a,b)?m(q(a,b))-m(p(a,b)):0))+")"}).attr("x",0).attr("y",0).attr("width",A).attr("height",function(a,b){var c=p(a,b),d=q(a,b);return c>d?m(d)-m(c):m(c)-m(d)})}c.selectAll(".nv-candlestick-lines").transition().attr("transform",function(a,b){return"translate("+l(n(a,b))+",0)"}).attr("x1",0).attr("y1",function(a,b){return m(r(a,b))}).attr("x2",0).attr("y2",function(a,b){return m(s(a,b))}),c.selectAll(".nv-candlestick-rects").transition().attr("transform",function(a,b){return"translate("+(l(n(a,b))-A/2)+","+(m(o(a,b))-(p(a,b)>q(a,b)?m(q(a,b))-m(p(a,b)):0))+")"}).attr("x",0).attr("y",0).attr("width",A).attr("height",function(a,b){var c=p(a,b),d=q(a,b);return c>d?m(d)-m(c):m(c)-m(d)})}),b}var c,d,e,f,g,h={top:0,right:0,bottom:0,left:0},i=null,j=null,k=Math.floor(1e4*Math.random()),l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=function(a){return a.open},q=function(a){return a.close},r=function(a){return a.high},s=function(a){return a.low},t=[],u=[],v=!1,w=!0,x=a.utils.defaultColor(),y=!1,z=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd","chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove");return b.highlightPoint=function(a,d){b.clearHighlights(),c.select(".nv-candlestickBar .nv-tick-0-"+a).classed("hover",d)},b.clearHighlights=function(){c.select(".nv-candlestickBar .nv-tick.hover").classed("hover",!1)},b.dispatch=z,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return i},set:function(a){i=a}},height:{get:function(){return j},set:function(a){j=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},padData:{get:function(){return v},set:function(a){v=a}},clipEdge:{get:function(){return w},set:function(a){w=a}},id:{get:function(){return k},set:function(a){k=a}},interactive:{get:function(){return y},set:function(a){y=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},open:{get:function(){return p()},set:function(a){p=a}},close:{get:function(){return q()},set:function(a){q=a}},high:{get:function(){return r},set:function(a){r=a}},low:{get:function(){return s},set:function(a){s=a}},margin:{get:function(){return h},set:function(a){h.top=void 0!=a.top?a.top:h.top,h.right=void 0!=a.right?a.right:h.right,h.bottom=void 0!=a.bottom?a.bottom:h.bottom,h.left=void 0!=a.left?a.left:h.left}},color:{get:function(){return x},set:function(b){x=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.cumulativeLineChart=function(){"use strict";function b(l){return H.reset(),H.models(f),r&&H.models(g),s&&H.models(h),l.each(function(l){function A(){d3.select(b.container).style("cursor","ew-resize")}function E(){G.x=d3.event.x,G.i=Math.round(F.invert(G.x)),K()}function H(){d3.select(b.container).style("cursor","auto"),y.index=G.i,C.stateChange(y)}function K(){bb.data([G]);var a=b.duration();b.duration(0),b.update(),b.duration(a)}var L=d3.select(this);a.utils.initSVG(L),L.classed("nv-chart-"+x,!0);var M=this,N=a.utils.availableWidth(o,L,m),O=a.utils.availableHeight(p,L,m);if(b.update=function(){0===D?L.call(b):L.transition().duration(D).call(b)},b.container=this,y.setter(J(l),b.update).getter(I(l)).update(),y.disabled=l.map(function(a){return!!a.disabled}),!z){var P;z={};for(P in y)z[P]=y[P]instanceof Array?y[P].slice(0):y[P]}var Q=d3.behavior.drag().on("dragstart",A).on("drag",E).on("dragend",H);if(!(l&&l.length&&l.filter(function(a){return a.values.length}).length))return a.utils.noData(b,L),b;if(L.selectAll(".nv-noData").remove(),d=f.xScale(),e=f.yScale(),w)f.yDomain(null);else{var R=l.filter(function(a){return!a.disabled}).map(function(a){var b=d3.extent(a.values,f.y());return b[0]<-.95&&(b[0]=-.95),[(b[0]-b[1])/(1+b[1]),(b[1]-b[0])/(1+b[0])]}),S=[d3.min(R,function(a){return a[0]}),d3.max(R,function(a){return a[1]})];f.yDomain(S)}F.domain([0,l[0].values.length-1]).range([0,N]).clamp(!0);var l=c(G.i,l),T=v?"none":"all",U=L.selectAll("g.nv-wrap.nv-cumulativeLine").data([l]),V=U.enter().append("g").attr("class","nvd3 nv-wrap nv-cumulativeLine").append("g"),W=U.select("g");if(V.append("g").attr("class","nv-interactive"),V.append("g").attr("class","nv-x nv-axis").style("pointer-events","none"),V.append("g").attr("class","nv-y nv-axis"),V.append("g").attr("class","nv-background"),V.append("g").attr("class","nv-linesWrap").style("pointer-events",T),V.append("g").attr("class","nv-avgLinesWrap").style("pointer-events","none"),V.append("g").attr("class","nv-legendWrap"),V.append("g").attr("class","nv-controlsWrap"),q&&(i.width(N),W.select(".nv-legendWrap").datum(l).call(i),m.top!=i.height()&&(m.top=i.height(),O=a.utils.availableHeight(p,L,m)),W.select(".nv-legendWrap").attr("transform","translate(0,"+-m.top+")")),u){var X=[{key:"Re-scale y-axis",disabled:!w}];j.width(140).color(["#444","#444","#444"]).rightAlign(!1).margin({top:5,right:0,bottom:5,left:20}),W.select(".nv-controlsWrap").datum(X).attr("transform","translate(0,"+-m.top+")").call(j)}U.attr("transform","translate("+m.left+","+m.top+")"),t&&W.select(".nv-y.nv-axis").attr("transform","translate("+N+",0)");var Y=l.filter(function(a){return a.tempDisabled});U.select(".tempDisabled").remove(),Y.length&&U.append("text").attr("class","tempDisabled").attr("x",N/2).attr("y","-.71em").style("text-anchor","end").text(Y.map(function(a){return a.key}).join(", ")+" values cannot be calculated for this time period."),v&&(k.width(N).height(O).margin({left:m.left,top:m.top}).svgContainer(L).xScale(d),U.select(".nv-interactive").call(k)),V.select(".nv-background").append("rect"),W.select(".nv-background rect").attr("width",N).attr("height",O),f.y(function(a){return a.display.y}).width(N).height(O).color(l.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!l[b].disabled&&!l[b].tempDisabled}));var Z=W.select(".nv-linesWrap").datum(l.filter(function(a){return!a.disabled&&!a.tempDisabled}));Z.call(f),l.forEach(function(a,b){a.seriesIndex=b});var $=l.filter(function(a){return!a.disabled&&!!B(a)}),_=W.select(".nv-avgLinesWrap").selectAll("line").data($,function(a){return a.key}),ab=function(a){var b=e(B(a));return 0>b?0:b>O?O:b};_.enter().append("line").style("stroke-width",2).style("stroke-dasharray","10,10").style("stroke",function(a){return f.color()(a,a.seriesIndex)}).attr("x1",0).attr("x2",N).attr("y1",ab).attr("y2",ab),_.style("stroke-opacity",function(a){var b=e(B(a));return 0>b||b>O?0:1}).attr("x1",0).attr("x2",N).attr("y1",ab).attr("y2",ab),_.exit().remove();var bb=Z.selectAll(".nv-indexLine").data([G]);bb.enter().append("rect").attr("class","nv-indexLine").attr("width",3).attr("x",-2).attr("fill","red").attr("fill-opacity",.5).style("pointer-events","all").call(Q),bb.attr("transform",function(a){return"translate("+F(a.i)+",0)"}).attr("height",O),r&&(g.scale(d)._ticks(a.utils.calcTicksX(N/70,l)).tickSize(-O,0),W.select(".nv-x.nv-axis").attr("transform","translate(0,"+e.range()[0]+")"),W.select(".nv-x.nv-axis").call(g)),s&&(h.scale(e)._ticks(a.utils.calcTicksY(O/36,l)).tickSize(-N,0),W.select(".nv-y.nv-axis").call(h)),W.select(".nv-background rect").on("click",function(){G.x=d3.mouse(this)[0],G.i=Math.round(F.invert(G.x)),y.index=G.i,C.stateChange(y),K()}),f.dispatch.on("elementClick",function(a){G.i=a.pointIndex,G.x=F(G.i),y.index=G.i,C.stateChange(y),K()}),j.dispatch.on("legendClick",function(a){a.disabled=!a.disabled,w=!a.disabled,y.rescaleY=w,C.stateChange(y),b.update()}),i.dispatch.on("stateChange",function(a){for(var c in a)y[c]=a[c];C.stateChange(y),b.update()}),k.dispatch.on("elementMousemove",function(c){f.clearHighlights();var d,e,i,j=[];if(l.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(g,h){e=a.interactiveBisect(g.values,c.pointXValue,b.x()),f.highlightPoint(h,e,!0);var k=g.values[e];"undefined"!=typeof k&&("undefined"==typeof d&&(d=k),"undefined"==typeof i&&(i=b.xScale()(b.x()(k,e))),j.push({key:g.key,value:b.y()(k,e),color:n(g,g.seriesIndex)}))}),j.length>2){var o=b.yScale().invert(c.mouseY),p=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),q=.03*p,r=a.nearestValueIndex(j.map(function(a){return a.value}),o,q);null!==r&&(j[r].highlight=!0)}var s=g.tickFormat()(b.x()(d,e),e);k.tooltip.position({left:i+m.left,top:c.mouseY+m.top}).chartContainer(M.parentNode).valueFormatter(function(a){return h.tickFormat()(a)}).data({value:s,series:j})(),k.renderGuideLine(i)}),k.dispatch.on("elementMouseout",function(){f.clearHighlights()}),C.on("changeState",function(a){"undefined"!=typeof a.disabled&&(l.forEach(function(b,c){b.disabled=a.disabled[c]}),y.disabled=a.disabled),"undefined"!=typeof a.index&&(G.i=a.index,G.x=F(G.i),y.index=a.index,bb.data([G])),"undefined"!=typeof a.rescaleY&&(w=a.rescaleY),b.update()})}),H.renderEnd("cumulativeLineChart immediate"),b}function c(a,b){return K||(K=f.y()),b.map(function(b){if(!b.values)return b;var c=b.values[a];if(null==c)return b;var d=K(c,a);return-.95>d&&!E?(b.tempDisabled=!0,b):(b.tempDisabled=!1,b.values=b.values.map(function(a,b){return a.display={y:(K(a,b)-d)/(1+d)},a}),b)})}var d,e,f=a.models.line(),g=a.models.axis(),h=a.models.axis(),i=a.models.legend(),j=a.models.legend(),k=a.interactiveGuideline(),l=a.models.tooltip(),m={top:30,right:30,bottom:50,left:60},n=a.utils.defaultColor(),o=null,p=null,q=!0,r=!0,s=!0,t=!1,u=!0,v=!1,w=!0,x=f.id(),y=a.utils.state(),z=null,A=null,B=function(a){return a.average},C=d3.dispatch("stateChange","changeState","renderEnd"),D=250,E=!1;y.index=0,y.rescaleY=w,g.orient("bottom").tickPadding(7),h.orient(t?"right":"left"),l.valueFormatter(function(a,b){return h.tickFormat()(a,b)}).headerFormatter(function(a,b){return g.tickFormat()(a,b)}),j.updateState(!1);var F=d3.scale.linear(),G={i:0,x:0},H=a.utils.renderWatch(C,D),I=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),index:G.i,rescaleY:w}}},J=function(a){return function(b){void 0!==b.index&&(G.i=b.index),void 0!==b.rescaleY&&(w=b.rescaleY),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};f.dispatch.on("elementMouseover.tooltip",function(a){var c={x:b.x()(a.point),y:b.y()(a.point),color:a.point.color};a.point=c,l.data(a).position(a.pos).hidden(!1)}),f.dispatch.on("elementMouseout.tooltip",function(){l.hidden(!0)});var K=null;return b.dispatch=C,b.lines=f,b.legend=i,b.controls=j,b.xAxis=g,b.yAxis=h,b.interactiveLayer=k,b.state=y,b.tooltip=l,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return o},set:function(a){o=a}},height:{get:function(){return p},set:function(a){p=a}},rescaleY:{get:function(){return w},set:function(a){w=a}},showControls:{get:function(){return u},set:function(a){u=a}},showLegend:{get:function(){return q},set:function(a){q=a}},average:{get:function(){return B},set:function(a){B=a}},defaultState:{get:function(){return z},set:function(a){z=a}},noData:{get:function(){return A},set:function(a){A=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},noErrorCheck:{get:function(){return E},set:function(a){E=a}},tooltips:{get:function(){return l.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),l.enabled(!!b)}},tooltipContent:{get:function(){return l.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),l.contentGenerator(b)}},margin:{get:function(){return m},set:function(a){m.top=void 0!==a.top?a.top:m.top,m.right=void 0!==a.right?a.right:m.right,m.bottom=void 0!==a.bottom?a.bottom:m.bottom,m.left=void 0!==a.left?a.left:m.left}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),i.color(n)}},useInteractiveGuideline:{get:function(){return v},set:function(a){v=a,a===!0&&(b.interactive(!1),b.useVoronoi(!1))}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,h.orient(a?"right":"left")}},duration:{get:function(){return D},set:function(a){D=a,f.duration(D),g.duration(D),h.duration(D),H.reset(D)}}}),a.utils.inheritOptions(b,f),a.utils.initOptions(b),b},a.models.discreteBar=function(){"use strict";function b(m){return y.reset(),m.each(function(b){var m=k-j.left-j.right,x=l-j.top-j.bottom;c=d3.select(this),a.utils.initSVG(c),b.forEach(function(a,b){a.values.forEach(function(a){a.series=b})});var z=d&&e?[]:b.map(function(a){return a.values.map(function(a,b){return{x:p(a,b),y:q(a,b),y0:a.y0}})});n.domain(d||d3.merge(z).map(function(a){return a.x})).rangeBands(f||[0,m],.1),o.domain(e||d3.extent(d3.merge(z).map(function(a){return a.y}).concat(r))),o.range(t?g||[x-(o.domain()[0]<0?12:0),o.domain()[1]>0?12:0]:g||[x,0]),h=h||n,i=i||o.copy().range([o(0),o(0)]);{var A=c.selectAll("g.nv-wrap.nv-discretebar").data([b]),B=A.enter().append("g").attr("class","nvd3 nv-wrap nv-discretebar"),C=B.append("g");A.select("g")}C.append("g").attr("class","nv-groups"),A.attr("transform","translate("+j.left+","+j.top+")");var D=A.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});D.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),D.exit().watchTransition(y,"discreteBar: exit groups").style("stroke-opacity",1e-6).style("fill-opacity",1e-6).remove(),D.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}),D.watchTransition(y,"discreteBar: groups").style("stroke-opacity",1).style("fill-opacity",.75);var E=D.selectAll("g.nv-bar").data(function(a){return a.values});E.exit().remove();var F=E.enter().append("g").attr("transform",function(a,b){return"translate("+(n(p(a,b))+.05*n.rangeBand())+", "+o(0)+")"}).on("mouseover",function(a,b){d3.select(this).classed("hover",!0),v.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),v.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){v.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){v.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){v.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()});F.append("rect").attr("height",0).attr("width",.9*n.rangeBand()/b.length),t?(F.append("text").attr("text-anchor","middle"),E.select("text").text(function(a,b){return u(q(a,b))}).watchTransition(y,"discreteBar: bars text").attr("x",.9*n.rangeBand()/2).attr("y",function(a,b){return q(a,b)<0?o(q(a,b))-o(0)+12:-4})):E.selectAll("text").remove(),E.attr("class",function(a,b){return q(a,b)<0?"nv-bar negative":"nv-bar positive"}).style("fill",function(a,b){return a.color||s(a,b)}).style("stroke",function(a,b){return a.color||s(a,b)}).select("rect").attr("class",w).watchTransition(y,"discreteBar: bars rect").attr("width",.9*n.rangeBand()/b.length),E.watchTransition(y,"discreteBar: bars").attr("transform",function(a,b){var c=n(p(a,b))+.05*n.rangeBand(),d=q(a,b)<0?o(0):o(0)-o(q(a,b))<1?o(0)-1:o(q(a,b));return"translate("+c+", "+d+")"}).select("rect").attr("height",function(a,b){return Math.max(Math.abs(o(q(a,b))-o(e&&e[0]||0))||1)}),h=n.copy(),i=o.copy()}),y.renderEnd("discreteBar immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=Math.floor(1e4*Math.random()),n=d3.scale.ordinal(),o=d3.scale.linear(),p=function(a){return a.x},q=function(a){return a.y},r=[0],s=a.utils.defaultColor(),t=!1,u=d3.format(",.2f"),v=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),w="discreteBar",x=250,y=a.utils.renderWatch(v,x);return b.dispatch=v,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},forceY:{get:function(){return r},set:function(a){r=a}},showValues:{get:function(){return t},set:function(a){t=a}},x:{get:function(){return p},set:function(a){p=a}},y:{get:function(){return q},set:function(a){q=a}},xScale:{get:function(){return n},set:function(a){n=a}},yScale:{get:function(){return o},set:function(a){o=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},valueFormat:{get:function(){return u},set:function(a){u=a}},id:{get:function(){return m},set:function(a){m=a}},rectClass:{get:function(){return w},set:function(a){w=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},color:{get:function(){return s},set:function(b){s=a.utils.getColor(b)}},duration:{get:function(){return x},set:function(a){x=a,y.reset(x)}}}),a.utils.initOptions(b),b},a.models.discreteBarChart=function(){"use strict";function b(h){return t.reset(),t.models(e),m&&t.models(f),n&&t.models(g),h.each(function(h){var l=d3.select(this);a.utils.initSVG(l);var q=a.utils.availableWidth(j,l,i),t=a.utils.availableHeight(k,l,i);if(b.update=function(){r.beforeUpdate(),l.transition().duration(s).call(b)},b.container=this,!(h&&h.length&&h.filter(function(a){return a.values.length}).length))return a.utils.noData(b,l),b;l.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale().clamp(!0);var u=l.selectAll("g.nv-wrap.nv-discreteBarWithAxes").data([h]),v=u.enter().append("g").attr("class","nvd3 nv-wrap nv-discreteBarWithAxes").append("g"),w=v.append("defs"),x=u.select("g");v.append("g").attr("class","nv-x nv-axis"),v.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),v.append("g").attr("class","nv-barsWrap"),x.attr("transform","translate("+i.left+","+i.top+")"),o&&x.select(".nv-y.nv-axis").attr("transform","translate("+q+",0)"),e.width(q).height(t);var y=x.select(".nv-barsWrap").datum(h.filter(function(a){return!a.disabled}));if(y.transition().call(e),w.append("clipPath").attr("id","nv-x-label-clip-"+e.id()).append("rect"),x.select("#nv-x-label-clip-"+e.id()+" rect").attr("width",c.rangeBand()*(p?2:1)).attr("height",16).attr("x",-c.rangeBand()/(p?1:2)),m){f.scale(c)._ticks(a.utils.calcTicksX(q/100,h)).tickSize(-t,0),x.select(".nv-x.nv-axis").attr("transform","translate(0,"+(d.range()[0]+(e.showValues()&&d.domain()[0]<0?16:0))+")"),x.select(".nv-x.nv-axis").call(f);
var z=x.select(".nv-x.nv-axis").selectAll("g");p&&z.selectAll("text").attr("transform",function(a,b,c){return"translate(0,"+(c%2==0?"5":"17")+")"})}n&&(g.scale(d)._ticks(a.utils.calcTicksY(t/36,h)).tickSize(-q,0),x.select(".nv-y.nv-axis").call(g)),x.select(".nv-zeroLine line").attr("x1",0).attr("x2",q).attr("y1",d(0)).attr("y2",d(0))}),t.renderEnd("discreteBar chart immediate"),b}var c,d,e=a.models.discreteBar(),f=a.models.axis(),g=a.models.axis(),h=a.models.tooltip(),i={top:15,right:10,bottom:50,left:60},j=null,k=null,l=a.utils.getColor(),m=!0,n=!0,o=!1,p=!1,q=null,r=d3.dispatch("beforeUpdate","renderEnd"),s=250;f.orient("bottom").showMaxMin(!1).tickFormat(function(a){return a}),g.orient(o?"right":"left").tickFormat(d3.format(",.1f")),h.duration(0).headerEnabled(!1).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).keyFormatter(function(a,b){return f.tickFormat()(a,b)});var t=a.utils.renderWatch(r,s);return e.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:b.x()(a.data),value:b.y()(a.data),color:a.color},h.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(){h.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(){h.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=r,b.discretebar=e,b.xAxis=f,b.yAxis=g,b.tooltip=h,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return j},set:function(a){j=a}},height:{get:function(){return k},set:function(a){k=a}},staggerLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return m},set:function(a){m=a}},showYAxis:{get:function(){return n},set:function(a){n=a}},noData:{get:function(){return q},set:function(a){q=a}},tooltips:{get:function(){return h.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),h.enabled(!!b)}},tooltipContent:{get:function(){return h.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),h.contentGenerator(b)}},margin:{get:function(){return i},set:function(a){i.top=void 0!==a.top?a.top:i.top,i.right=void 0!==a.right?a.right:i.right,i.bottom=void 0!==a.bottom?a.bottom:i.bottom,i.left=void 0!==a.left?a.left:i.left}},duration:{get:function(){return s},set:function(a){s=a,t.reset(s),e.duration(s),f.duration(s),g.duration(s)}},color:{get:function(){return l},set:function(b){l=a.utils.getColor(b),e.color(l)}},rightAlignYAxis:{get:function(){return o},set:function(a){o=a,g.orient(a?"right":"left")}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.distribution=function(){"use strict";function b(k){return m.reset(),k.each(function(b){var k=(e-("x"===g?d.left+d.right:d.top+d.bottom),"x"==g?"y":"x"),l=d3.select(this);a.utils.initSVG(l),c=c||j;var n=l.selectAll("g.nv-distribution").data([b]),o=n.enter().append("g").attr("class","nvd3 nv-distribution"),p=(o.append("g"),n.select("g"));n.attr("transform","translate("+d.left+","+d.top+")");var q=p.selectAll("g.nv-dist").data(function(a){return a},function(a){return a.key});q.enter().append("g"),q.attr("class",function(a,b){return"nv-dist nv-series-"+b}).style("stroke",function(a,b){return i(a,b)});var r=q.selectAll("line.nv-dist"+g).data(function(a){return a.values});r.enter().append("line").attr(g+"1",function(a,b){return c(h(a,b))}).attr(g+"2",function(a,b){return c(h(a,b))}),m.transition(q.exit().selectAll("line.nv-dist"+g),"dist exit").attr(g+"1",function(a,b){return j(h(a,b))}).attr(g+"2",function(a,b){return j(h(a,b))}).style("stroke-opacity",0).remove(),r.attr("class",function(a,b){return"nv-dist"+g+" nv-dist"+g+"-"+b}).attr(k+"1",0).attr(k+"2",f),m.transition(r,"dist").attr(g+"1",function(a,b){return j(h(a,b))}).attr(g+"2",function(a,b){return j(h(a,b))}),c=j.copy()}),m.renderEnd("distribution immediate"),b}var c,d={top:0,right:0,bottom:0,left:0},e=400,f=8,g="x",h=function(a){return a[g]},i=a.utils.defaultColor(),j=d3.scale.linear(),k=250,l=d3.dispatch("renderEnd"),m=a.utils.renderWatch(l,k);return b.options=a.utils.optionsFunc.bind(b),b.dispatch=l,b.margin=function(a){return arguments.length?(d.top="undefined"!=typeof a.top?a.top:d.top,d.right="undefined"!=typeof a.right?a.right:d.right,d.bottom="undefined"!=typeof a.bottom?a.bottom:d.bottom,d.left="undefined"!=typeof a.left?a.left:d.left,b):d},b.width=function(a){return arguments.length?(e=a,b):e},b.axis=function(a){return arguments.length?(g=a,b):g},b.size=function(a){return arguments.length?(f=a,b):f},b.getData=function(a){return arguments.length?(h=d3.functor(a),b):h},b.scale=function(a){return arguments.length?(j=a,b):j},b.color=function(c){return arguments.length?(i=a.utils.getColor(c),b):i},b.duration=function(a){return arguments.length?(k=a,m.reset(k),b):k},b},a.models.furiousLegend=function(){"use strict";function b(p){function q(a,b){return"furious"!=o?"#000":m?a.disengaged?g(a,b):"#fff":m?void 0:a.disabled?g(a,b):"#fff"}function r(a,b){return m&&"furious"==o?a.disengaged?"#fff":g(a,b):a.disabled?"#fff":g(a,b)}return p.each(function(b){var p=d-c.left-c.right,s=d3.select(this);a.utils.initSVG(s);var t=s.selectAll("g.nv-legend").data([b]),u=(t.enter().append("g").attr("class","nvd3 nv-legend").append("g"),t.select("g"));t.attr("transform","translate("+c.left+","+c.top+")");var v,w=u.selectAll(".nv-series").data(function(a){return"furious"!=o?a:a.filter(function(a){return m?!0:!a.disengaged})}),x=w.enter().append("g").attr("class","nv-series");if("classic"==o)x.append("circle").style("stroke-width",2).attr("class","nv-legend-symbol").attr("r",5),v=w.select("circle");else if("furious"==o){x.append("rect").style("stroke-width",2).attr("class","nv-legend-symbol").attr("rx",3).attr("ry",3),v=w.select("rect"),x.append("g").attr("class","nv-check-box").property("innerHTML",'<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>').attr("transform","translate(-10,-8)scale(0.5)");var y=w.select(".nv-check-box");y.each(function(a,b){d3.select(this).selectAll("path").attr("stroke",q(a,b))})}x.append("text").attr("text-anchor","start").attr("class","nv-legend-text").attr("dy",".32em").attr("dx","8");var z=w.select("text.nv-legend-text");w.on("mouseover",function(a,b){n.legendMouseover(a,b)}).on("mouseout",function(a,b){n.legendMouseout(a,b)}).on("click",function(a,b){n.legendClick(a,b);var c=w.data();if(k){if("classic"==o)l?(c.forEach(function(a){a.disabled=!0}),a.disabled=!1):(a.disabled=!a.disabled,c.every(function(a){return a.disabled})&&c.forEach(function(a){a.disabled=!1}));else if("furious"==o)if(m)a.disengaged=!a.disengaged,a.userDisabled=void 0==a.userDisabled?!!a.disabled:a.userDisabled,a.disabled=a.disengaged||a.userDisabled;else if(!m){a.disabled=!a.disabled,a.userDisabled=a.disabled;var d=c.filter(function(a){return!a.disengaged});d.every(function(a){return a.userDisabled})&&c.forEach(function(a){a.disabled=a.userDisabled=!1})}n.stateChange({disabled:c.map(function(a){return!!a.disabled}),disengaged:c.map(function(a){return!!a.disengaged})})}}).on("dblclick",function(a,b){if(("furious"!=o||!m)&&(n.legendDblclick(a,b),k)){var c=w.data();c.forEach(function(a){a.disabled=!0,"furious"==o&&(a.userDisabled=a.disabled)}),a.disabled=!1,"furious"==o&&(a.userDisabled=a.disabled),n.stateChange({disabled:c.map(function(a){return!!a.disabled})})}}),w.classed("nv-disabled",function(a){return a.userDisabled}),w.exit().remove(),z.attr("fill",q).text(f);var A;switch(o){case"furious":A=23;break;case"classic":A=20}if(h){var B=[];w.each(function(){var b,c=d3.select(this).select("text");try{if(b=c.node().getComputedTextLength(),0>=b)throw Error()}catch(d){b=a.utils.calcApproxTextWidth(c)}B.push(b+i)});for(var C=0,D=0,E=[];p>D&&C<B.length;)E[C]=B[C],D+=B[C++];for(0===C&&(C=1);D>p&&C>1;){E=[],C--;for(var F=0;F<B.length;F++)B[F]>(E[F%C]||0)&&(E[F%C]=B[F]);D=E.reduce(function(a,b){return a+b})}for(var G=[],H=0,I=0;C>H;H++)G[H]=I,I+=E[H];w.attr("transform",function(a,b){return"translate("+G[b%C]+","+(5+Math.floor(b/C)*A)+")"}),j?u.attr("transform","translate("+(d-c.right-D)+","+c.top+")"):u.attr("transform","translate(0,"+c.top+")"),e=c.top+c.bottom+Math.ceil(B.length/C)*A}else{var J,K=5,L=5,M=0;w.attr("transform",function(){var a=d3.select(this).select("text").node().getComputedTextLength()+i;return J=L,d<c.left+c.right+J+a&&(L=J=5,K+=A),L+=a,L>M&&(M=L),"translate("+J+","+K+")"}),u.attr("transform","translate("+(d-c.right-M)+","+c.top+")"),e=c.top+c.bottom+K+15}"furious"==o&&v.attr("width",function(a,b){return z[0][b].getComputedTextLength()+27}).attr("height",18).attr("y",-9).attr("x",-15),v.style("fill",r).style("stroke",function(a,b){return a.color||g(a,b)})}),b}var c={top:5,right:0,bottom:5,left:0},d=400,e=20,f=function(a){return a.key},g=a.utils.getColor(),h=!0,i=28,j=!0,k=!0,l=!1,m=!1,n=d3.dispatch("legendClick","legendDblclick","legendMouseover","legendMouseout","stateChange"),o="classic";return b.dispatch=n,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},key:{get:function(){return f},set:function(a){f=a}},align:{get:function(){return h},set:function(a){h=a}},rightAlign:{get:function(){return j},set:function(a){j=a}},padding:{get:function(){return i},set:function(a){i=a}},updateState:{get:function(){return k},set:function(a){k=a}},radioButtonMode:{get:function(){return l},set:function(a){l=a}},expanded:{get:function(){return m},set:function(a){m=a}},vers:{get:function(){return o},set:function(a){o=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return g},set:function(b){g=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.historicalBar=function(){"use strict";function b(x){return x.each(function(b){w.reset(),k=d3.select(this);var x=a.utils.availableWidth(h,k,g),y=a.utils.availableHeight(i,k,g);a.utils.initSVG(k),l.domain(c||d3.extent(b[0].values.map(n).concat(p))),l.range(r?e||[.5*x/b[0].values.length,x*(b[0].values.length-.5)/b[0].values.length]:e||[0,x]),m.domain(d||d3.extent(b[0].values.map(o).concat(q))).range(f||[y,0]),l.domain()[0]===l.domain()[1]&&l.domain(l.domain()[0]?[l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]:[-1,1]),m.domain()[0]===m.domain()[1]&&m.domain(m.domain()[0]?[m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]:[-1,1]);var z=k.selectAll("g.nv-wrap.nv-historicalBar-"+j).data([b[0].values]),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-historicalBar-"+j),B=A.append("defs"),C=A.append("g"),D=z.select("g");C.append("g").attr("class","nv-bars"),z.attr("transform","translate("+g.left+","+g.top+")"),k.on("click",function(a,b){u.chartClick({data:a,index:b,pos:d3.event,id:j})}),B.append("clipPath").attr("id","nv-chart-clip-path-"+j).append("rect"),z.select("#nv-chart-clip-path-"+j+" rect").attr("width",x).attr("height",y),D.attr("clip-path",s?"url(#nv-chart-clip-path-"+j+")":"");var E=z.select(".nv-bars").selectAll(".nv-bar").data(function(a){return a},function(a,b){return n(a,b)});E.exit().remove(),E.enter().append("rect").attr("x",0).attr("y",function(b,c){return a.utils.NaNtoZero(m(Math.max(0,o(b,c))))}).attr("height",function(b,c){return a.utils.NaNtoZero(Math.abs(m(o(b,c))-m(0)))}).attr("transform",function(a,c){return"translate("+(l(n(a,c))-x/b[0].values.length*.45)+",0)"}).on("mouseover",function(a,b){v&&(d3.select(this).classed("hover",!0),u.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")}))}).on("mouseout",function(a,b){v&&(d3.select(this).classed("hover",!1),u.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")}))}).on("mousemove",function(a,b){v&&u.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){v&&(u.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation())}).on("dblclick",function(a,b){v&&(u.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation())}),E.attr("fill",function(a,b){return t(a,b)}).attr("class",function(a,b,c){return(o(a,b)<0?"nv-bar negative":"nv-bar positive")+" nv-bar-"+c+"-"+b}).watchTransition(w,"bars").attr("transform",function(a,c){return"translate("+(l(n(a,c))-x/b[0].values.length*.45)+",0)"}).attr("width",x/b[0].values.length*.9),E.watchTransition(w,"bars").attr("y",function(b,c){var d=o(b,c)<0?m(0):m(0)-m(o(b,c))<1?m(0)-1:m(o(b,c));return a.utils.NaNtoZero(d)}).attr("height",function(b,c){return a.utils.NaNtoZero(Math.max(Math.abs(m(o(b,c))-m(0)),1))})}),w.renderEnd("historicalBar immediate"),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=Math.floor(1e4*Math.random()),k=null,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=[],q=[0],r=!1,s=!0,t=a.utils.defaultColor(),u=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),v=!0,w=a.utils.renderWatch(u,0);return b.highlightPoint=function(a,b){k.select(".nv-bars .nv-bar-0-"+a).classed("hover",b)},b.clearHighlights=function(){k.select(".nv-bars .nv-bar.hover").classed("hover",!1)},b.dispatch=u,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},forceX:{get:function(){return p},set:function(a){p=a}},forceY:{get:function(){return q},set:function(a){q=a}},padData:{get:function(){return r},set:function(a){r=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},clipEdge:{get:function(){return s},set:function(a){s=a}},id:{get:function(){return j},set:function(a){j=a}},interactive:{get:function(){return v},set:function(a){v=a}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},color:{get:function(){return t},set:function(b){t=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.historicalBarChart=function(b){"use strict";function c(b){return b.each(function(k){z.reset(),z.models(f),q&&z.models(g),r&&z.models(h);var w=d3.select(this),A=this;a.utils.initSVG(w);var B=a.utils.availableWidth(n,w,l),C=a.utils.availableHeight(o,w,l);if(c.update=function(){w.transition().duration(y).call(c)},c.container=this,u.disabled=k.map(function(a){return!!a.disabled}),!v){var D;v={};for(D in u)v[D]=u[D]instanceof Array?u[D].slice(0):u[D]}if(!(k&&k.length&&k.filter(function(a){return a.values.length}).length))return a.utils.noData(c,w),c;w.selectAll(".nv-noData").remove(),d=f.xScale(),e=f.yScale();var E=w.selectAll("g.nv-wrap.nv-historicalBarChart").data([k]),F=E.enter().append("g").attr("class","nvd3 nv-wrap nv-historicalBarChart").append("g"),G=E.select("g");F.append("g").attr("class","nv-x nv-axis"),F.append("g").attr("class","nv-y nv-axis"),F.append("g").attr("class","nv-barsWrap"),F.append("g").attr("class","nv-legendWrap"),F.append("g").attr("class","nv-interactive"),p&&(i.width(B),G.select(".nv-legendWrap").datum(k).call(i),l.top!=i.height()&&(l.top=i.height(),C=a.utils.availableHeight(o,w,l)),E.select(".nv-legendWrap").attr("transform","translate(0,"+-l.top+")")),E.attr("transform","translate("+l.left+","+l.top+")"),s&&G.select(".nv-y.nv-axis").attr("transform","translate("+B+",0)"),t&&(j.width(B).height(C).margin({left:l.left,top:l.top}).svgContainer(w).xScale(d),E.select(".nv-interactive").call(j)),f.width(B).height(C).color(k.map(function(a,b){return a.color||m(a,b)}).filter(function(a,b){return!k[b].disabled}));var H=G.select(".nv-barsWrap").datum(k.filter(function(a){return!a.disabled}));H.transition().call(f),q&&(g.scale(d)._ticks(a.utils.calcTicksX(B/100,k)).tickSize(-C,0),G.select(".nv-x.nv-axis").attr("transform","translate(0,"+e.range()[0]+")"),G.select(".nv-x.nv-axis").transition().call(g)),r&&(h.scale(e)._ticks(a.utils.calcTicksY(C/36,k)).tickSize(-B,0),G.select(".nv-y.nv-axis").transition().call(h)),j.dispatch.on("elementMousemove",function(b){f.clearHighlights();var d,e,i,n=[];k.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(g){e=a.interactiveBisect(g.values,b.pointXValue,c.x()),f.highlightPoint(e,!0);var h=g.values[e];void 0!==h&&(void 0===d&&(d=h),void 0===i&&(i=c.xScale()(c.x()(h,e))),n.push({key:g.key,value:c.y()(h,e),color:m(g,g.seriesIndex),data:g.values[e]}))});var o=g.tickFormat()(c.x()(d,e));j.tooltip.position({left:i+l.left,top:b.mouseY+l.top}).chartContainer(A.parentNode).valueFormatter(function(a){return h.tickFormat()(a)}).data({value:o,index:e,series:n})(),j.renderGuideLine(i)}),j.dispatch.on("elementMouseout",function(){x.tooltipHide(),f.clearHighlights()}),i.dispatch.on("legendClick",function(a){a.disabled=!a.disabled,k.filter(function(a){return!a.disabled}).length||k.map(function(a){return a.disabled=!1,E.selectAll(".nv-series").classed("disabled",!1),a}),u.disabled=k.map(function(a){return!!a.disabled}),x.stateChange(u),b.transition().call(c)}),i.dispatch.on("legendDblclick",function(a){k.forEach(function(a){a.disabled=!0}),a.disabled=!1,u.disabled=k.map(function(a){return!!a.disabled}),x.stateChange(u),c.update()}),x.on("changeState",function(a){"undefined"!=typeof a.disabled&&(k.forEach(function(b,c){b.disabled=a.disabled[c]}),u.disabled=a.disabled),c.update()})}),z.renderEnd("historicalBarChart immediate"),c}var d,e,f=b||a.models.historicalBar(),g=a.models.axis(),h=a.models.axis(),i=a.models.legend(),j=a.interactiveGuideline(),k=a.models.tooltip(),l={top:30,right:90,bottom:50,left:90},m=a.utils.defaultColor(),n=null,o=null,p=!1,q=!0,r=!0,s=!1,t=!1,u={},v=null,w=null,x=d3.dispatch("tooltipHide","stateChange","changeState","renderEnd"),y=250;g.orient("bottom").tickPadding(7),h.orient(s?"right":"left"),k.duration(0).headerEnabled(!1).valueFormatter(function(a,b){return h.tickFormat()(a,b)}).headerFormatter(function(a,b){return g.tickFormat()(a,b)});var z=a.utils.renderWatch(x,0);return f.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:c.x()(a.data),value:c.y()(a.data),color:a.color},k.data(a).hidden(!1)}),f.dispatch.on("elementMouseout.tooltip",function(){k.hidden(!0)}),f.dispatch.on("elementMousemove.tooltip",function(){k.position({top:d3.event.pageY,left:d3.event.pageX})()}),c.dispatch=x,c.bars=f,c.legend=i,c.xAxis=g,c.yAxis=h,c.interactiveLayer=j,c.tooltip=k,c.options=a.utils.optionsFunc.bind(c),c._options=Object.create({},{width:{get:function(){return n},set:function(a){n=a}},height:{get:function(){return o},set:function(a){o=a}},showLegend:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return q},set:function(a){q=a}},showYAxis:{get:function(){return r},set:function(a){r=a}},defaultState:{get:function(){return v},set:function(a){v=a}},noData:{get:function(){return w},set:function(a){w=a}},tooltips:{get:function(){return k.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),k.enabled(!!b)}},tooltipContent:{get:function(){return k.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),k.contentGenerator(b)}},margin:{get:function(){return l},set:function(a){l.top=void 0!==a.top?a.top:l.top,l.right=void 0!==a.right?a.right:l.right,l.bottom=void 0!==a.bottom?a.bottom:l.bottom,l.left=void 0!==a.left?a.left:l.left}},color:{get:function(){return m},set:function(b){m=a.utils.getColor(b),i.color(m),f.color(m)}},duration:{get:function(){return y},set:function(a){y=a,z.reset(y),h.duration(y),g.duration(y)}},rightAlignYAxis:{get:function(){return s},set:function(a){s=a,h.orient(a?"right":"left")}},useInteractiveGuideline:{get:function(){return t},set:function(a){t=a,a===!0&&c.interactive(!1)}}}),a.utils.inheritOptions(c,f),a.utils.initOptions(c),c},a.models.ohlcBarChart=function(){var b=a.models.historicalBarChart(a.models.ohlcBar());return b.useInteractiveGuideline(!0),b.interactiveLayer.tooltip.contentGenerator(function(a){var c=a.series[0].data,d=c.open<c.close?"2ca02c":"d62728";return'<h3 style="color: #'+d+'">'+a.value+"</h3><table><tr><td>open:</td><td>"+b.yAxis.tickFormat()(c.open)+"</td></tr><tr><td>close:</td><td>"+b.yAxis.tickFormat()(c.close)+"</td></tr><tr><td>high</td><td>"+b.yAxis.tickFormat()(c.high)+"</td></tr><tr><td>low:</td><td>"+b.yAxis.tickFormat()(c.low)+"</td></tr></table>"}),b},a.models.candlestickBarChart=function(){var b=a.models.historicalBarChart(a.models.candlestickBar());return b.useInteractiveGuideline(!0),b.interactiveLayer.tooltip.contentGenerator(function(a){var c=a.series[0].data,d=c.open<c.close?"2ca02c":"d62728";return'<h3 style="color: #'+d+'">'+a.value+"</h3><table><tr><td>open:</td><td>"+b.yAxis.tickFormat()(c.open)+"</td></tr><tr><td>close:</td><td>"+b.yAxis.tickFormat()(c.close)+"</td></tr><tr><td>high</td><td>"+b.yAxis.tickFormat()(c.high)+"</td></tr><tr><td>low:</td><td>"+b.yAxis.tickFormat()(c.low)+"</td></tr></table>"}),b},a.models.legend=function(){"use strict";function b(p){function q(a,b){return"furious"!=o?"#000":m?a.disengaged?"#000":"#fff":m?void 0:(a.color||(a.color=g(a,b)),a.disabled?a.color:"#fff")}function r(a,b){return m&&"furious"==o&&a.disengaged?"#eee":a.color||g(a,b)}function s(a){return m&&"furious"==o?1:a.disabled?0:1}return p.each(function(b){var g=d-c.left-c.right,p=d3.select(this);a.utils.initSVG(p);var t=p.selectAll("g.nv-legend").data([b]),u=t.enter().append("g").attr("class","nvd3 nv-legend").append("g"),v=t.select("g");t.attr("transform","translate("+c.left+","+c.top+")");var w,x,y=v.selectAll(".nv-series").data(function(a){return"furious"!=o?a:a.filter(function(a){return m?!0:!a.disengaged})}),z=y.enter().append("g").attr("class","nv-series");switch(o){case"furious":x=23;break;case"classic":x=20}if("classic"==o)z.append("circle").style("stroke-width",2).attr("class","nv-legend-symbol").attr("r",5),w=y.select("circle");else if("furious"==o){z.append("rect").style("stroke-width",2).attr("class","nv-legend-symbol").attr("rx",3).attr("ry",3),w=y.select(".nv-legend-symbol"),z.append("g").attr("class","nv-check-box").property("innerHTML",'<path d="M0.5,5 L22.5,5 L22.5,26.5 L0.5,26.5 L0.5,5 Z" class="nv-box"></path><path d="M5.5,12.8618467 L11.9185089,19.2803556 L31,0.198864511" class="nv-check"></path>').attr("transform","translate(-10,-8)scale(0.5)");var A=y.select(".nv-check-box");A.each(function(a,b){d3.select(this).selectAll("path").attr("stroke",q(a,b))})}z.append("text").attr("text-anchor","start").attr("class","nv-legend-text").attr("dy",".32em").attr("dx","8");var B=y.select("text.nv-legend-text");y.on("mouseover",function(a,b){n.legendMouseover(a,b)}).on("mouseout",function(a,b){n.legendMouseout(a,b)}).on("click",function(a,b){n.legendClick(a,b);var c=y.data();if(k){if("classic"==o)l?(c.forEach(function(a){a.disabled=!0}),a.disabled=!1):(a.disabled=!a.disabled,c.every(function(a){return a.disabled})&&c.forEach(function(a){a.disabled=!1}));else if("furious"==o)if(m)a.disengaged=!a.disengaged,a.userDisabled=void 0==a.userDisabled?!!a.disabled:a.userDisabled,a.disabled=a.disengaged||a.userDisabled;else if(!m){a.disabled=!a.disabled,a.userDisabled=a.disabled;var d=c.filter(function(a){return!a.disengaged});d.every(function(a){return a.userDisabled})&&c.forEach(function(a){a.disabled=a.userDisabled=!1})}n.stateChange({disabled:c.map(function(a){return!!a.disabled}),disengaged:c.map(function(a){return!!a.disengaged})})}}).on("dblclick",function(a,b){if(("furious"!=o||!m)&&(n.legendDblclick(a,b),k)){var c=y.data();c.forEach(function(a){a.disabled=!0,"furious"==o&&(a.userDisabled=a.disabled)}),a.disabled=!1,"furious"==o&&(a.userDisabled=a.disabled),n.stateChange({disabled:c.map(function(a){return!!a.disabled})})}}),y.classed("nv-disabled",function(a){return a.userDisabled}),y.exit().remove(),B.attr("fill",q).text(f);var C=0;if(h){var D=[];y.each(function(){var b,c=d3.select(this).select("text");try{if(b=c.node().getComputedTextLength(),0>=b)throw Error()}catch(d){b=a.utils.calcApproxTextWidth(c)}D.push(b+i)});var E=0,F=[];for(C=0;g>C&&E<D.length;)F[E]=D[E],C+=D[E++];for(0===E&&(E=1);C>g&&E>1;){F=[],E--;for(var G=0;G<D.length;G++)D[G]>(F[G%E]||0)&&(F[G%E]=D[G]);C=F.reduce(function(a,b){return a+b})}for(var H=[],I=0,J=0;E>I;I++)H[I]=J,J+=F[I];y.attr("transform",function(a,b){return"translate("+H[b%E]+","+(5+Math.floor(b/E)*x)+")"}),j?v.attr("transform","translate("+(d-c.right-C)+","+c.top+")"):v.attr("transform","translate(0,"+c.top+")"),e=c.top+c.bottom+Math.ceil(D.length/E)*x}else{var K,L=5,M=5,N=0;y.attr("transform",function(){var a=d3.select(this).select("text").node().getComputedTextLength()+i;return K=M,d<c.left+c.right+K+a&&(M=K=5,L+=x),M+=a,M>N&&(N=M),K+N>C&&(C=K+N),"translate("+K+","+L+")"}),v.attr("transform","translate("+(d-c.right-N)+","+c.top+")"),e=c.top+c.bottom+L+15}if("furious"==o){w.attr("width",function(a,b){return B[0][b].getComputedTextLength()+27}).attr("height",18).attr("y",-9).attr("x",-15),u.insert("rect",":first-child").attr("class","nv-legend-bg").attr("fill","#eee").attr("opacity",0);var O=v.select(".nv-legend-bg");O.transition().duration(300).attr("x",-x).attr("width",C+x-12).attr("height",e+10).attr("y",-c.top-10).attr("opacity",m?1:0)}w.style("fill",r).style("fill-opacity",s).style("stroke",r)}),b}var c={top:5,right:0,bottom:5,left:0},d=400,e=20,f=function(a){return a.key},g=a.utils.getColor(),h=!0,i=32,j=!0,k=!0,l=!1,m=!1,n=d3.dispatch("legendClick","legendDblclick","legendMouseover","legendMouseout","stateChange"),o="classic";return b.dispatch=n,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},key:{get:function(){return f},set:function(a){f=a}},align:{get:function(){return h},set:function(a){h=a}},rightAlign:{get:function(){return j},set:function(a){j=a}},padding:{get:function(){return i},set:function(a){i=a}},updateState:{get:function(){return k},set:function(a){k=a}},radioButtonMode:{get:function(){return l},set:function(a){l=a}},expanded:{get:function(){return m},set:function(a){m=a}},vers:{get:function(){return o},set:function(a){o=a}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return g},set:function(b){g=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.line=function(){"use strict";function b(r){return v.reset(),v.models(e),r.each(function(b){i=d3.select(this);var r=a.utils.availableWidth(g,i,f),s=a.utils.availableHeight(h,i,f);a.utils.initSVG(i),c=e.xScale(),d=e.yScale(),t=t||c,u=u||d;var w=i.selectAll("g.nv-wrap.nv-line").data([b]),x=w.enter().append("g").attr("class","nvd3 nv-wrap nv-line"),y=x.append("defs"),z=x.append("g"),A=w.select("g");z.append("g").attr("class","nv-groups"),z.append("g").attr("class","nv-scatterWrap"),w.attr("transform","translate("+f.left+","+f.top+")"),e.width(r).height(s);var B=w.select(".nv-scatterWrap");B.call(e),y.append("clipPath").attr("id","nv-edge-clip-"+e.id()).append("rect"),w.select("#nv-edge-clip-"+e.id()+" rect").attr("width",r).attr("height",s>0?s:0),A.attr("clip-path",p?"url(#nv-edge-clip-"+e.id()+")":""),B.attr("clip-path",p?"url(#nv-edge-clip-"+e.id()+")":"");var C=w.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});C.enter().append("g").style("stroke-opacity",1e-6).style("stroke-width",function(a){return a.strokeWidth||j}).style("fill-opacity",1e-6),C.exit().remove(),C.attr("class",function(a,b){return(a.classed||"")+" nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return k(a,b)}).style("stroke",function(a,b){return k(a,b)}),C.watchTransition(v,"line: groups").style("stroke-opacity",1).style("fill-opacity",function(a){return a.fillOpacity||.5});var D=C.selectAll("path.nv-area").data(function(a){return o(a)?[a]:[]});D.enter().append("path").attr("class","nv-area").attr("d",function(b){return d3.svg.area().interpolate(q).defined(n).x(function(b,c){return a.utils.NaNtoZero(t(l(b,c)))}).y0(function(b,c){return a.utils.NaNtoZero(u(m(b,c)))}).y1(function(){return u(d.domain()[0]<=0?d.domain()[1]>=0?0:d.domain()[1]:d.domain()[0])}).apply(this,[b.values])}),C.exit().selectAll("path.nv-area").remove(),D.watchTransition(v,"line: areaPaths").attr("d",function(b){return d3.svg.area().interpolate(q).defined(n).x(function(b,d){return a.utils.NaNtoZero(c(l(b,d)))}).y0(function(b,c){return a.utils.NaNtoZero(d(m(b,c)))}).y1(function(){return d(d.domain()[0]<=0?d.domain()[1]>=0?0:d.domain()[1]:d.domain()[0])}).apply(this,[b.values])});var E=C.selectAll("path.nv-line").data(function(a){return[a.values]});E.enter().append("path").attr("class","nv-line").attr("d",d3.svg.line().interpolate(q).defined(n).x(function(b,c){return a.utils.NaNtoZero(t(l(b,c)))}).y(function(b,c){return a.utils.NaNtoZero(u(m(b,c)))})),E.watchTransition(v,"line: linePaths").attr("d",d3.svg.line().interpolate(q).defined(n).x(function(b,d){return a.utils.NaNtoZero(c(l(b,d)))}).y(function(b,c){return a.utils.NaNtoZero(d(m(b,c)))})),t=c.copy(),u=d.copy()}),v.renderEnd("line immediate"),b}var c,d,e=a.models.scatter(),f={top:0,right:0,bottom:0,left:0},g=960,h=500,i=null,j=1.5,k=a.utils.defaultColor(),l=function(a){return a.x},m=function(a){return a.y},n=function(a,b){return!isNaN(m(a,b))&&null!==m(a,b)},o=function(a){return a.area},p=!1,q="linear",r=250,s=d3.dispatch("elementClick","elementMouseover","elementMouseout","renderEnd");e.pointSize(16).pointDomain([16,256]);var t,u,v=a.utils.renderWatch(s,r);return b.dispatch=s,b.scatter=e,e.dispatch.on("elementClick",function(){s.elementClick.apply(this,arguments)}),e.dispatch.on("elementMouseover",function(){s.elementMouseover.apply(this,arguments)}),e.dispatch.on("elementMouseout",function(){s.elementMouseout.apply(this,arguments)}),b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},defined:{get:function(){return n},set:function(a){n=a}},interpolate:{get:function(){return q},set:function(a){q=a}},clipEdge:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}},duration:{get:function(){return r},set:function(a){r=a,v.reset(r),e.duration(r)}},isArea:{get:function(){return o},set:function(a){o=d3.functor(a)}},x:{get:function(){return l},set:function(a){l=a,e.x(a)}},y:{get:function(){return m},set:function(a){m=a,e.y(a)}},color:{get:function(){return k},set:function(b){k=a.utils.getColor(b),e.color(k)}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.lineChart=function(){"use strict";function b(j){return y.reset(),y.models(e),p&&y.models(f),q&&y.models(g),j.each(function(j){var v=d3.select(this),y=this;a.utils.initSVG(v);var B=a.utils.availableWidth(m,v,k),C=a.utils.availableHeight(n,v,k);if(b.update=function(){0===x?v.call(b):v.transition().duration(x).call(b)},b.container=this,t.setter(A(j),b.update).getter(z(j)).update(),t.disabled=j.map(function(a){return!!a.disabled}),!u){var D;u={};for(D in t)u[D]=t[D]instanceof Array?t[D].slice(0):t[D]
}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,v),b;v.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var E=v.selectAll("g.nv-wrap.nv-lineChart").data([j]),F=E.enter().append("g").attr("class","nvd3 nv-wrap nv-lineChart").append("g"),G=E.select("g");F.append("rect").style("opacity",0),F.append("g").attr("class","nv-x nv-axis"),F.append("g").attr("class","nv-y nv-axis"),F.append("g").attr("class","nv-linesWrap"),F.append("g").attr("class","nv-legendWrap"),F.append("g").attr("class","nv-interactive"),G.select("rect").attr("width",B).attr("height",C>0?C:0),o&&(h.width(B),G.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),C=a.utils.availableHeight(n,v,k)),E.select(".nv-legendWrap").attr("transform","translate(0,"+-k.top+")")),E.attr("transform","translate("+k.left+","+k.top+")"),r&&G.select(".nv-y.nv-axis").attr("transform","translate("+B+",0)"),s&&(i.width(B).height(C).margin({left:k.left,top:k.top}).svgContainer(v).xScale(c),E.select(".nv-interactive").call(i)),e.width(B).height(C).color(j.map(function(a,b){return a.color||l(a,b)}).filter(function(a,b){return!j[b].disabled}));var H=G.select(".nv-linesWrap").datum(j.filter(function(a){return!a.disabled}));H.call(e),p&&(f.scale(c)._ticks(a.utils.calcTicksX(B/100,j)).tickSize(-C,0),G.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),G.select(".nv-x.nv-axis").call(f)),q&&(g.scale(d)._ticks(a.utils.calcTicksY(C/36,j)).tickSize(-B,0),G.select(".nv-y.nv-axis").call(g)),h.dispatch.on("stateChange",function(a){for(var c in a)t[c]=a[c];w.stateChange(t),b.update()}),i.dispatch.on("elementMousemove",function(c){e.clearHighlights();var d,h,m,n=[];if(j.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(f,g){h=a.interactiveBisect(f.values,c.pointXValue,b.x());var i=f.values[h],j=b.y()(i,h);null!=j&&e.highlightPoint(g,h,!0),void 0!==i&&(void 0===d&&(d=i),void 0===m&&(m=b.xScale()(b.x()(i,h))),n.push({key:f.key,value:j,color:l(f,f.seriesIndex)}))}),n.length>2){var o=b.yScale().invert(c.mouseY),p=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),q=.03*p,r=a.nearestValueIndex(n.map(function(a){return a.value}),o,q);null!==r&&(n[r].highlight=!0)}var s=f.tickFormat()(b.x()(d,h));i.tooltip.position({left:c.mouseX+k.left,top:c.mouseY+k.top}).chartContainer(y.parentNode).valueFormatter(function(a){return null==a?"N/A":g.tickFormat()(a)}).data({value:s,index:h,series:n})(),i.renderGuideLine(m)}),i.dispatch.on("elementClick",function(c){var d,f=[];j.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(e){var g=a.interactiveBisect(e.values,c.pointXValue,b.x()),h=e.values[g];if("undefined"!=typeof h){"undefined"==typeof d&&(d=b.xScale()(b.x()(h,g)));var i=b.yScale()(b.y()(h,g));f.push({point:h,pointIndex:g,pos:[d,i],seriesIndex:e.seriesIndex,series:e})}}),e.dispatch.elementClick(f)}),i.dispatch.on("elementMouseout",function(){e.clearHighlights()}),w.on("changeState",function(a){"undefined"!=typeof a.disabled&&j.length===a.disabled.length&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),t.disabled=a.disabled),b.update()})}),y.renderEnd("lineChart immediate"),b}var c,d,e=a.models.line(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.interactiveGuideline(),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=a.utils.defaultColor(),m=null,n=null,o=!0,p=!0,q=!0,r=!1,s=!1,t=a.utils.state(),u=null,v=null,w=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd"),x=250;f.orient("bottom").tickPadding(7),g.orient(r?"right":"left"),j.valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)});var y=a.utils.renderWatch(w,x),z=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},A=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return e.dispatch.on("elementMouseover.tooltip",function(a){j.data(a).position(a.pos).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(){j.hidden(!0)}),b.dispatch=w,b.lines=e,b.legend=h,b.xAxis=f,b.yAxis=g,b.interactiveLayer=i,b.tooltip=j,b.dispatch=w,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return o},set:function(a){o=a}},showXAxis:{get:function(){return p},set:function(a){p=a}},showYAxis:{get:function(){return q},set:function(a){q=a}},defaultState:{get:function(){return u},set:function(a){u=a}},noData:{get:function(){return v},set:function(a){v=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return x},set:function(a){x=a,y.reset(x),e.duration(x),f.duration(x),g.duration(x)}},color:{get:function(){return l},set:function(b){l=a.utils.getColor(b),h.color(l),e.color(l)}},rightAlignYAxis:{get:function(){return r},set:function(a){r=a,g.orient(r?"right":"left")}},useInteractiveGuideline:{get:function(){return s},set:function(a){s=a,s&&(e.interactive(!1),e.useVoronoi(!1))}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.linePlusBarChart=function(){"use strict";function b(v){return v.each(function(v){function J(a){var b=+("e"==a),c=b?1:-1,d=X/3;return"M"+.5*c+","+d+"A6,6 0 0 "+b+" "+6.5*c+","+(d+6)+"V"+(2*d-6)+"A6,6 0 0 "+b+" "+.5*c+","+2*d+"ZM"+2.5*c+","+(d+8)+"V"+(2*d-8)+"M"+4.5*c+","+(d+8)+"V"+(2*d-8)}function S(){u.empty()||u.extent(I),kb.data([u.empty()?e.domain():I]).each(function(a){var b=e(a[0])-e.range()[0],c=e.range()[1]-e(a[1]);d3.select(this).select(".left").attr("width",0>b?0:b),d3.select(this).select(".right").attr("x",e(a[1])).attr("width",0>c?0:c)})}function T(){I=u.empty()?null:u.extent(),c=u.empty()?e.domain():u.extent(),K.brush({extent:c,brush:u}),S(),l.width(V).height(W).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&v[b].bar})),j.width(V).height(W).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&!v[b].bar}));var b=db.select(".nv-focus .nv-barsWrap").datum(Z.length?Z.map(function(a){return{key:a.key,values:a.values.filter(function(a,b){return l.x()(a,b)>=c[0]&&l.x()(a,b)<=c[1]})}}):[{values:[]}]),h=db.select(".nv-focus .nv-linesWrap").datum($[0].disabled?[{values:[]}]:$.map(function(a){return{area:a.area,fillOpacity:a.fillOpacity,key:a.key,values:a.values.filter(function(a,b){return j.x()(a,b)>=c[0]&&j.x()(a,b)<=c[1]})}}));d=Z.length?l.xScale():j.xScale(),n.scale(d)._ticks(a.utils.calcTicksX(V/100,v)).tickSize(-W,0),n.domain([Math.ceil(c[0]),Math.floor(c[1])]),db.select(".nv-x.nv-axis").transition().duration(L).call(n),b.transition().duration(L).call(l),h.transition().duration(L).call(j),db.select(".nv-focus .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),p.scale(f)._ticks(a.utils.calcTicksY(W/36,v)).tickSize(-V,0),q.scale(g)._ticks(a.utils.calcTicksY(W/36,v)).tickSize(Z.length?0:-V,0),db.select(".nv-focus .nv-y1.nv-axis").style("opacity",Z.length?1:0),db.select(".nv-focus .nv-y2.nv-axis").style("opacity",$.length&&!$[0].disabled?1:0).attr("transform","translate("+d.range()[1]+",0)"),db.select(".nv-focus .nv-y1.nv-axis").transition().duration(L).call(p),db.select(".nv-focus .nv-y2.nv-axis").transition().duration(L).call(q)}var U=d3.select(this);a.utils.initSVG(U);var V=a.utils.availableWidth(y,U,w),W=a.utils.availableHeight(z,U,w)-(E?H:0),X=H-x.top-x.bottom;if(b.update=function(){U.transition().duration(L).call(b)},b.container=this,M.setter(R(v),b.update).getter(Q(v)).update(),M.disabled=v.map(function(a){return!!a.disabled}),!N){var Y;N={};for(Y in M)N[Y]=M[Y]instanceof Array?M[Y].slice(0):M[Y]}if(!(v&&v.length&&v.filter(function(a){return a.values.length}).length))return a.utils.noData(b,U),b;U.selectAll(".nv-noData").remove();var Z=v.filter(function(a){return!a.disabled&&a.bar}),$=v.filter(function(a){return!a.bar});d=l.xScale(),e=o.scale(),f=l.yScale(),g=j.yScale(),h=m.yScale(),i=k.yScale();var _=v.filter(function(a){return!a.disabled&&a.bar}).map(function(a){return a.values.map(function(a,b){return{x:A(a,b),y:B(a,b)}})}),ab=v.filter(function(a){return!a.disabled&&!a.bar}).map(function(a){return a.values.map(function(a,b){return{x:A(a,b),y:B(a,b)}})});d.range([0,V]),e.domain(d3.extent(d3.merge(_.concat(ab)),function(a){return a.x})).range([0,V]);var bb=U.selectAll("g.nv-wrap.nv-linePlusBar").data([v]),cb=bb.enter().append("g").attr("class","nvd3 nv-wrap nv-linePlusBar").append("g"),db=bb.select("g");cb.append("g").attr("class","nv-legendWrap");var eb=cb.append("g").attr("class","nv-focus");eb.append("g").attr("class","nv-x nv-axis"),eb.append("g").attr("class","nv-y1 nv-axis"),eb.append("g").attr("class","nv-y2 nv-axis"),eb.append("g").attr("class","nv-barsWrap"),eb.append("g").attr("class","nv-linesWrap");var fb=cb.append("g").attr("class","nv-context");if(fb.append("g").attr("class","nv-x nv-axis"),fb.append("g").attr("class","nv-y1 nv-axis"),fb.append("g").attr("class","nv-y2 nv-axis"),fb.append("g").attr("class","nv-barsWrap"),fb.append("g").attr("class","nv-linesWrap"),fb.append("g").attr("class","nv-brushBackground"),fb.append("g").attr("class","nv-x nv-brush"),D){var gb=t.align()?V/2:V,hb=t.align()?gb:0;t.width(gb),db.select(".nv-legendWrap").datum(v.map(function(a){return a.originalKey=void 0===a.originalKey?a.key:a.originalKey,a.key=a.originalKey+(a.bar?O:P),a})).call(t),w.top!=t.height()&&(w.top=t.height(),W=a.utils.availableHeight(z,U,w)-H),db.select(".nv-legendWrap").attr("transform","translate("+hb+","+-w.top+")")}bb.attr("transform","translate("+w.left+","+w.top+")"),db.select(".nv-context").style("display",E?"initial":"none"),m.width(V).height(X).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&v[b].bar})),k.width(V).height(X).color(v.map(function(a,b){return a.color||C(a,b)}).filter(function(a,b){return!v[b].disabled&&!v[b].bar}));var ib=db.select(".nv-context .nv-barsWrap").datum(Z.length?Z:[{values:[]}]),jb=db.select(".nv-context .nv-linesWrap").datum($[0].disabled?[{values:[]}]:$);db.select(".nv-context").attr("transform","translate(0,"+(W+w.bottom+x.top)+")"),ib.transition().call(m),jb.transition().call(k),G&&(o._ticks(a.utils.calcTicksX(V/100,v)).tickSize(-X,0),db.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+h.range()[0]+")"),db.select(".nv-context .nv-x.nv-axis").transition().call(o)),F&&(r.scale(h)._ticks(X/36).tickSize(-V,0),s.scale(i)._ticks(X/36).tickSize(Z.length?0:-V,0),db.select(".nv-context .nv-y3.nv-axis").style("opacity",Z.length?1:0).attr("transform","translate(0,"+e.range()[0]+")"),db.select(".nv-context .nv-y2.nv-axis").style("opacity",$.length?1:0).attr("transform","translate("+e.range()[1]+",0)"),db.select(".nv-context .nv-y1.nv-axis").transition().call(r),db.select(".nv-context .nv-y2.nv-axis").transition().call(s)),u.x(e).on("brush",T),I&&u.extent(I);var kb=db.select(".nv-brushBackground").selectAll("g").data([I||u.extent()]),lb=kb.enter().append("g");lb.append("rect").attr("class","left").attr("x",0).attr("y",0).attr("height",X),lb.append("rect").attr("class","right").attr("x",0).attr("y",0).attr("height",X);var mb=db.select(".nv-x.nv-brush").call(u);mb.selectAll("rect").attr("height",X),mb.selectAll(".resize").append("path").attr("d",J),t.dispatch.on("stateChange",function(a){for(var c in a)M[c]=a[c];K.stateChange(M),b.update()}),K.on("changeState",function(a){"undefined"!=typeof a.disabled&&(v.forEach(function(b,c){b.disabled=a.disabled[c]}),M.disabled=a.disabled),b.update()}),T()}),b}var c,d,e,f,g,h,i,j=a.models.line(),k=a.models.line(),l=a.models.historicalBar(),m=a.models.historicalBar(),n=a.models.axis(),o=a.models.axis(),p=a.models.axis(),q=a.models.axis(),r=a.models.axis(),s=a.models.axis(),t=a.models.legend(),u=d3.svg.brush(),v=a.models.tooltip(),w={top:30,right:30,bottom:30,left:60},x={top:0,right:30,bottom:20,left:60},y=null,z=null,A=function(a){return a.x},B=function(a){return a.y},C=a.utils.defaultColor(),D=!0,E=!0,F=!1,G=!0,H=50,I=null,J=null,K=d3.dispatch("brush","stateChange","changeState"),L=0,M=a.utils.state(),N=null,O=" (left axis)",P=" (right axis)";j.clipEdge(!0),k.interactive(!1),n.orient("bottom").tickPadding(5),p.orient("left"),q.orient("right"),o.orient("bottom").tickPadding(5),r.orient("left"),s.orient("right"),v.headerEnabled(!0).headerFormatter(function(a,b){return n.tickFormat()(a,b)});var Q=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},R=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return j.dispatch.on("elementMouseover.tooltip",function(a){v.duration(100).valueFormatter(function(a,b){return q.tickFormat()(a,b)}).data(a).position(a.pos).hidden(!1)}),j.dispatch.on("elementMouseout.tooltip",function(){v.hidden(!0)}),l.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={value:b.y()(a.data),color:a.color},v.duration(0).valueFormatter(function(a,b){return p.tickFormat()(a,b)}).data(a).hidden(!1)}),l.dispatch.on("elementMouseout.tooltip",function(){v.hidden(!0)}),l.dispatch.on("elementMousemove.tooltip",function(){v.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=K,b.legend=t,b.lines=j,b.lines2=k,b.bars=l,b.bars2=m,b.xAxis=n,b.x2Axis=o,b.y1Axis=p,b.y2Axis=q,b.y3Axis=r,b.y4Axis=s,b.tooltip=v,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return y},set:function(a){y=a}},height:{get:function(){return z},set:function(a){z=a}},showLegend:{get:function(){return D},set:function(a){D=a}},brushExtent:{get:function(){return I},set:function(a){I=a}},noData:{get:function(){return J},set:function(a){J=a}},focusEnable:{get:function(){return E},set:function(a){E=a}},focusHeight:{get:function(){return H},set:function(a){H=a}},focusShowAxisX:{get:function(){return G},set:function(a){G=a}},focusShowAxisY:{get:function(){return F},set:function(a){F=a}},legendLeftAxisHint:{get:function(){return O},set:function(a){O=a}},legendRightAxisHint:{get:function(){return P},set:function(a){P=a}},tooltips:{get:function(){return v.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),v.enabled(!!b)}},tooltipContent:{get:function(){return v.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),v.contentGenerator(b)}},margin:{get:function(){return w},set:function(a){w.top=void 0!==a.top?a.top:w.top,w.right=void 0!==a.right?a.right:w.right,w.bottom=void 0!==a.bottom?a.bottom:w.bottom,w.left=void 0!==a.left?a.left:w.left}},duration:{get:function(){return L},set:function(a){L=a}},color:{get:function(){return C},set:function(b){C=a.utils.getColor(b),t.color(C)}},x:{get:function(){return A},set:function(a){A=a,j.x(a),k.x(a),l.x(a),m.x(a)}},y:{get:function(){return B},set:function(a){B=a,j.y(a),k.y(a),l.y(a),m.y(a)}}}),a.utils.inheritOptions(b,j),a.utils.initOptions(b),b},a.models.lineWithFocusChart=function(){"use strict";function b(o){return o.each(function(o){function z(a){var b=+("e"==a),c=b?1:-1,d=M/3;return"M"+.5*c+","+d+"A6,6 0 0 "+b+" "+6.5*c+","+(d+6)+"V"+(2*d-6)+"A6,6 0 0 "+b+" "+.5*c+","+2*d+"ZM"+2.5*c+","+(d+8)+"V"+(2*d-8)+"M"+4.5*c+","+(d+8)+"V"+(2*d-8)}function G(){n.empty()||n.extent(y),U.data([n.empty()?e.domain():y]).each(function(a){var b=e(a[0])-c.range()[0],d=K-e(a[1]);d3.select(this).select(".left").attr("width",0>b?0:b),d3.select(this).select(".right").attr("x",e(a[1])).attr("width",0>d?0:d)})}function H(){y=n.empty()?null:n.extent();var a=n.empty()?e.domain():n.extent();if(!(Math.abs(a[0]-a[1])<=1)){A.brush({extent:a,brush:n}),G();var b=Q.select(".nv-focus .nv-linesWrap").datum(o.filter(function(a){return!a.disabled}).map(function(b){return{key:b.key,area:b.area,values:b.values.filter(function(b,c){return g.x()(b,c)>=a[0]&&g.x()(b,c)<=a[1]})}}));b.transition().duration(B).call(g),Q.select(".nv-focus .nv-x.nv-axis").transition().duration(B).call(i),Q.select(".nv-focus .nv-y.nv-axis").transition().duration(B).call(j)}}var I=d3.select(this),J=this;a.utils.initSVG(I);var K=a.utils.availableWidth(t,I,q),L=a.utils.availableHeight(u,I,q)-v,M=v-r.top-r.bottom;if(b.update=function(){I.transition().duration(B).call(b)},b.container=this,C.setter(F(o),b.update).getter(E(o)).update(),C.disabled=o.map(function(a){return!!a.disabled}),!D){var N;D={};for(N in C)D[N]=C[N]instanceof Array?C[N].slice(0):C[N]}if(!(o&&o.length&&o.filter(function(a){return a.values.length}).length))return a.utils.noData(b,I),b;I.selectAll(".nv-noData").remove(),c=g.xScale(),d=g.yScale(),e=h.xScale(),f=h.yScale();var O=I.selectAll("g.nv-wrap.nv-lineWithFocusChart").data([o]),P=O.enter().append("g").attr("class","nvd3 nv-wrap nv-lineWithFocusChart").append("g"),Q=O.select("g");P.append("g").attr("class","nv-legendWrap");var R=P.append("g").attr("class","nv-focus");R.append("g").attr("class","nv-x nv-axis"),R.append("g").attr("class","nv-y nv-axis"),R.append("g").attr("class","nv-linesWrap"),R.append("g").attr("class","nv-interactive");var S=P.append("g").attr("class","nv-context");S.append("g").attr("class","nv-x nv-axis"),S.append("g").attr("class","nv-y nv-axis"),S.append("g").attr("class","nv-linesWrap"),S.append("g").attr("class","nv-brushBackground"),S.append("g").attr("class","nv-x nv-brush"),x&&(m.width(K),Q.select(".nv-legendWrap").datum(o).call(m),q.top!=m.height()&&(q.top=m.height(),L=a.utils.availableHeight(u,I,q)-v),Q.select(".nv-legendWrap").attr("transform","translate(0,"+-q.top+")")),O.attr("transform","translate("+q.left+","+q.top+")"),w&&(p.width(K).height(L).margin({left:q.left,top:q.top}).svgContainer(I).xScale(c),O.select(".nv-interactive").call(p)),g.width(K).height(L).color(o.map(function(a,b){return a.color||s(a,b)}).filter(function(a,b){return!o[b].disabled})),h.defined(g.defined()).width(K).height(M).color(o.map(function(a,b){return a.color||s(a,b)}).filter(function(a,b){return!o[b].disabled})),Q.select(".nv-context").attr("transform","translate(0,"+(L+q.bottom+r.top)+")");var T=Q.select(".nv-context .nv-linesWrap").datum(o.filter(function(a){return!a.disabled}));d3.transition(T).call(h),i.scale(c)._ticks(a.utils.calcTicksX(K/100,o)).tickSize(-L,0),j.scale(d)._ticks(a.utils.calcTicksY(L/36,o)).tickSize(-K,0),Q.select(".nv-focus .nv-x.nv-axis").attr("transform","translate(0,"+L+")"),n.x(e).on("brush",function(){H()}),y&&n.extent(y);var U=Q.select(".nv-brushBackground").selectAll("g").data([y||n.extent()]),V=U.enter().append("g");V.append("rect").attr("class","left").attr("x",0).attr("y",0).attr("height",M),V.append("rect").attr("class","right").attr("x",0).attr("y",0).attr("height",M);var W=Q.select(".nv-x.nv-brush").call(n);W.selectAll("rect").attr("height",M),W.selectAll(".resize").append("path").attr("d",z),H(),k.scale(e)._ticks(a.utils.calcTicksX(K/100,o)).tickSize(-M,0),Q.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),d3.transition(Q.select(".nv-context .nv-x.nv-axis")).call(k),l.scale(f)._ticks(a.utils.calcTicksY(M/36,o)).tickSize(-K,0),d3.transition(Q.select(".nv-context .nv-y.nv-axis")).call(l),Q.select(".nv-context .nv-x.nv-axis").attr("transform","translate(0,"+f.range()[0]+")"),m.dispatch.on("stateChange",function(a){for(var c in a)C[c]=a[c];A.stateChange(C),b.update()}),p.dispatch.on("elementMousemove",function(c){g.clearHighlights();var d,f,h,k=[];if(o.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(i,j){var l=n.empty()?e.domain():n.extent(),m=i.values.filter(function(a,b){return g.x()(a,b)>=l[0]&&g.x()(a,b)<=l[1]});f=a.interactiveBisect(m,c.pointXValue,g.x());var o=m[f],p=b.y()(o,f);null!=p&&g.highlightPoint(j,f,!0),void 0!==o&&(void 0===d&&(d=o),void 0===h&&(h=b.xScale()(b.x()(o,f))),k.push({key:i.key,value:b.y()(o,f),color:s(i,i.seriesIndex)}))}),k.length>2){var l=b.yScale().invert(c.mouseY),m=Math.abs(b.yScale().domain()[0]-b.yScale().domain()[1]),r=.03*m,t=a.nearestValueIndex(k.map(function(a){return a.value}),l,r);null!==t&&(k[t].highlight=!0)}var u=i.tickFormat()(b.x()(d,f));p.tooltip.position({left:c.mouseX+q.left,top:c.mouseY+q.top}).chartContainer(J.parentNode).valueFormatter(function(a){return null==a?"N/A":j.tickFormat()(a)}).data({value:u,index:f,series:k})(),p.renderGuideLine(h)}),p.dispatch.on("elementMouseout",function(){g.clearHighlights()}),A.on("changeState",function(a){"undefined"!=typeof a.disabled&&o.forEach(function(b,c){b.disabled=a.disabled[c]}),b.update()})}),b}var c,d,e,f,g=a.models.line(),h=a.models.line(),i=a.models.axis(),j=a.models.axis(),k=a.models.axis(),l=a.models.axis(),m=a.models.legend(),n=d3.svg.brush(),o=a.models.tooltip(),p=a.interactiveGuideline(),q={top:30,right:30,bottom:30,left:60},r={top:0,right:30,bottom:20,left:60},s=a.utils.defaultColor(),t=null,u=null,v=50,w=!1,x=!0,y=null,z=null,A=d3.dispatch("brush","stateChange","changeState"),B=250,C=a.utils.state(),D=null;g.clipEdge(!0).duration(0),h.interactive(!1),i.orient("bottom").tickPadding(5),j.orient("left"),k.orient("bottom").tickPadding(5),l.orient("left"),o.valueFormatter(function(a,b){return j.tickFormat()(a,b)}).headerFormatter(function(a,b){return i.tickFormat()(a,b)});var E=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},F=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return g.dispatch.on("elementMouseover.tooltip",function(a){o.data(a).position(a.pos).hidden(!1)}),g.dispatch.on("elementMouseout.tooltip",function(){o.hidden(!0)}),b.dispatch=A,b.legend=m,b.lines=g,b.lines2=h,b.xAxis=i,b.yAxis=j,b.x2Axis=k,b.y2Axis=l,b.interactiveLayer=p,b.tooltip=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return t},set:function(a){t=a}},height:{get:function(){return u},set:function(a){u=a}},focusHeight:{get:function(){return v},set:function(a){v=a}},showLegend:{get:function(){return x},set:function(a){x=a}},brushExtent:{get:function(){return y},set:function(a){y=a}},defaultState:{get:function(){return D},set:function(a){D=a}},noData:{get:function(){return z},set:function(a){z=a}},tooltips:{get:function(){return o.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),o.enabled(!!b)}},tooltipContent:{get:function(){return o.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),o.contentGenerator(b)}},margin:{get:function(){return q},set:function(a){q.top=void 0!==a.top?a.top:q.top,q.right=void 0!==a.right?a.right:q.right,q.bottom=void 0!==a.bottom?a.bottom:q.bottom,q.left=void 0!==a.left?a.left:q.left}},color:{get:function(){return s},set:function(b){s=a.utils.getColor(b),m.color(s)}},interpolate:{get:function(){return g.interpolate()},set:function(a){g.interpolate(a),h.interpolate(a)}},xTickFormat:{get:function(){return i.tickFormat()},set:function(a){i.tickFormat(a),k.tickFormat(a)}},yTickFormat:{get:function(){return j.tickFormat()},set:function(a){j.tickFormat(a),l.tickFormat(a)}},duration:{get:function(){return B},set:function(a){B=a,j.duration(B),l.duration(B),i.duration(B),k.duration(B)}},x:{get:function(){return g.x()},set:function(a){g.x(a),h.x(a)}},y:{get:function(){return g.y()},set:function(a){g.y(a),h.y(a)}},useInteractiveGuideline:{get:function(){return w},set:function(a){w=a,w&&(g.interactive(!1),g.useVoronoi(!1))}}}),a.utils.inheritOptions(b,g),a.utils.initOptions(b),b},a.models.multiBar=function(){"use strict";function b(E){return C.reset(),E.each(function(b){var E=k-j.left-j.right,F=l-j.top-j.bottom;p=d3.select(this),a.utils.initSVG(p);var G=0;if(x&&b.length&&(x=[{values:b[0].values.map(function(a){return{x:a.x,y:0,series:a.series,size:.01}})}]),u){var H=d3.layout.stack().offset(v).values(function(a){return a.values}).y(r)(!b.length&&x?x:b);H.forEach(function(a,c){a.nonStackable?(b[c].nonStackableSeries=G++,H[c]=b[c]):c>0&&H[c-1].nonStackable&&H[c].values.map(function(a,b){a.y0-=H[c-1].values[b].y,a.y1=a.y0+a.y})}),b=H}b.forEach(function(a,b){a.values.forEach(function(c){c.series=b,c.key=a.key})}),u&&b[0].values.map(function(a,c){var d=0,e=0;b.map(function(a,f){if(!b[f].nonStackable){var g=a.values[c];g.size=Math.abs(g.y),g.y<0?(g.y1=e,e-=g.size):(g.y1=g.size+d,d+=g.size)}})});var I=d&&e?[]:b.map(function(a,b){return a.values.map(function(a,c){return{x:q(a,c),y:r(a,c),y0:a.y0,y1:a.y1,idx:b}})});m.domain(d||d3.merge(I).map(function(a){return a.x})).rangeBands(f||[0,E],A),n.domain(e||d3.extent(d3.merge(I).map(function(a){var c=a.y;return u&&!b[a.idx].nonStackable&&(c=a.y>0?a.y1:a.y1+a.y),c}).concat(s))).range(g||[F,0]),m.domain()[0]===m.domain()[1]&&m.domain(m.domain()[0]?[m.domain()[0]-.01*m.domain()[0],m.domain()[1]+.01*m.domain()[1]]:[-1,1]),n.domain()[0]===n.domain()[1]&&n.domain(n.domain()[0]?[n.domain()[0]+.01*n.domain()[0],n.domain()[1]-.01*n.domain()[1]]:[-1,1]),h=h||m,i=i||n;var J=p.selectAll("g.nv-wrap.nv-multibar").data([b]),K=J.enter().append("g").attr("class","nvd3 nv-wrap nv-multibar"),L=K.append("defs"),M=K.append("g"),N=J.select("g");M.append("g").attr("class","nv-groups"),J.attr("transform","translate("+j.left+","+j.top+")"),L.append("clipPath").attr("id","nv-edge-clip-"+o).append("rect"),J.select("#nv-edge-clip-"+o+" rect").attr("width",E).attr("height",F),N.attr("clip-path",t?"url(#nv-edge-clip-"+o+")":"");var O=J.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a,b){return b});O.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6);var P=C.transition(O.exit().selectAll("rect.nv-bar"),"multibarExit",Math.min(100,z)).attr("y",function(a){var c=i(0)||0;return u&&b[a.series]&&!b[a.series].nonStackable&&(c=i(a.y0)),c}).attr("height",0).remove();P.delay&&P.delay(function(a,b){var c=b*(z/(D+1))-b;return c}),O.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return w(a,b)}).style("stroke",function(a,b){return w(a,b)}),O.style("stroke-opacity",1).style("fill-opacity",.75);var Q=O.selectAll("rect.nv-bar").data(function(a){return x&&!b.length?x.values:a.values});Q.exit().remove();Q.enter().append("rect").attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}).attr("x",function(a,c,d){return u&&!b[d].nonStackable?0:d*m.rangeBand()/b.length}).attr("y",function(a,c,d){return i(u&&!b[d].nonStackable?a.y0:0)||0}).attr("height",0).attr("width",function(a,c,d){return m.rangeBand()/(u&&!b[d].nonStackable?1:b.length)}).attr("transform",function(a,b){return"translate("+m(q(a,b))+",0)"});Q.style("fill",function(a,b,c){return w(a,c,b)}).style("stroke",function(a,b,c){return w(a,c,b)}).on("mouseover",function(a,b){d3.select(this).classed("hover",!0),B.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),B.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){B.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){B.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){B.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}),Q.attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}).attr("transform",function(a,b){return"translate("+m(q(a,b))+",0)"}),y&&(c||(c=b.map(function(){return!0})),Q.style("fill",function(a,b,d){return d3.rgb(y(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}).style("stroke",function(a,b,d){return d3.rgb(y(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}));var R=Q.watchTransition(C,"multibar",Math.min(250,z)).delay(function(a,c){return c*z/b[0].values.length});u?R.attr("y",function(a,c,d){var e=0;return e=b[d].nonStackable?r(a,c)<0?n(0):n(0)-n(r(a,c))<-1?n(0)-1:n(r(a,c))||0:n(a.y1)}).attr("height",function(a,c,d){return b[d].nonStackable?Math.max(Math.abs(n(r(a,c))-n(0)),1)||0:Math.max(Math.abs(n(a.y+a.y0)-n(a.y0)),1)}).attr("x",function(a,c,d){var e=0;return b[d].nonStackable&&(e=a.series*m.rangeBand()/b.length,b.length!==G&&(e=b[d].nonStackableSeries*m.rangeBand()/(2*G))),e}).attr("width",function(a,c,d){if(b[d].nonStackable){var e=m.rangeBand()/G;return b.length!==G&&(e=m.rangeBand()/(2*G)),e}return m.rangeBand()}):R.attr("x",function(a){return a.series*m.rangeBand()/b.length}).attr("width",m.rangeBand()/b.length).attr("y",function(a,b){return r(a,b)<0?n(0):n(0)-n(r(a,b))<1?n(0)-1:n(r(a,b))||0}).attr("height",function(a,b){return Math.max(Math.abs(n(r(a,b))-n(0)),1)||0}),h=m.copy(),i=n.copy(),b[0]&&b[0].values&&(D=b[0].values.length)}),C.renderEnd("multibar immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=d3.scale.ordinal(),n=d3.scale.linear(),o=Math.floor(1e4*Math.random()),p=null,q=function(a){return a.x},r=function(a){return a.y},s=[0],t=!0,u=!1,v="zero",w=a.utils.defaultColor(),x=!1,y=null,z=500,A=.1,B=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),C=a.utils.renderWatch(B,z),D=0;return b.dispatch=B,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},x:{get:function(){return q},set:function(a){q=a}},y:{get:function(){return r},set:function(a){r=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceY:{get:function(){return s},set:function(a){s=a}},stacked:{get:function(){return u},set:function(a){u=a}},stackOffset:{get:function(){return v},set:function(a){v=a}},clipEdge:{get:function(){return t},set:function(a){t=a}},disabled:{get:function(){return c},set:function(a){c=a}},id:{get:function(){return o},set:function(a){o=a}},hideable:{get:function(){return x},set:function(a){x=a}},groupSpacing:{get:function(){return A},set:function(a){A=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},duration:{get:function(){return z},set:function(a){z=a,C.reset(z)}},color:{get:function(){return w},set:function(b){w=a.utils.getColor(b)}},barColor:{get:function(){return y},set:function(b){y=b?a.utils.getColor(b):null}}}),a.utils.initOptions(b),b},a.models.multiBarChart=function(){"use strict";function b(j){return D.reset(),D.models(e),r&&D.models(f),s&&D.models(g),j.each(function(j){var z=d3.select(this);a.utils.initSVG(z);var D=a.utils.availableWidth(l,z,k),H=a.utils.availableHeight(m,z,k);if(b.update=function(){0===C?z.call(b):z.transition().duration(C).call(b)},b.container=this,x.setter(G(j),b.update).getter(F(j)).update(),x.disabled=j.map(function(a){return!!a.disabled}),!y){var I;y={};for(I in x)y[I]=x[I]instanceof Array?x[I].slice(0):x[I]}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,z),b;z.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();
var J=z.selectAll("g.nv-wrap.nv-multiBarWithLegend").data([j]),K=J.enter().append("g").attr("class","nvd3 nv-wrap nv-multiBarWithLegend").append("g"),L=J.select("g");if(K.append("g").attr("class","nv-x nv-axis"),K.append("g").attr("class","nv-y nv-axis"),K.append("g").attr("class","nv-barsWrap"),K.append("g").attr("class","nv-legendWrap"),K.append("g").attr("class","nv-controlsWrap"),q&&(h.width(D-B()),L.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),H=a.utils.availableHeight(m,z,k)),L.select(".nv-legendWrap").attr("transform","translate("+B()+","+-k.top+")")),o){var M=[{key:p.grouped||"Grouped",disabled:e.stacked()},{key:p.stacked||"Stacked",disabled:!e.stacked()}];i.width(B()).color(["#444","#444","#444"]),L.select(".nv-controlsWrap").datum(M).attr("transform","translate(0,"+-k.top+")").call(i)}J.attr("transform","translate("+k.left+","+k.top+")"),t&&L.select(".nv-y.nv-axis").attr("transform","translate("+D+",0)"),e.disabled(j.map(function(a){return a.disabled})).width(D).height(H).color(j.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!j[b].disabled}));var N=L.select(".nv-barsWrap").datum(j.filter(function(a){return!a.disabled}));if(N.call(e),r){f.scale(c)._ticks(a.utils.calcTicksX(D/100,j)).tickSize(-H,0),L.select(".nv-x.nv-axis").attr("transform","translate(0,"+d.range()[0]+")"),L.select(".nv-x.nv-axis").call(f);var O=L.select(".nv-x.nv-axis > g").selectAll("g");if(O.selectAll("line, text").style("opacity",1),v){var P=function(a,b){return"translate("+a+","+b+")"},Q=5,R=17;O.selectAll("text").attr("transform",function(a,b,c){return P(0,c%2==0?Q:R)});var S=d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;L.selectAll(".nv-x.nv-axis .nv-axisMaxMin text").attr("transform",function(a,b){return P(0,0===b||S%2!==0?R:Q)})}u&&O.filter(function(a,b){return b%Math.ceil(j[0].values.length/(D/100))!==0}).selectAll("text, line").style("opacity",0),w&&O.selectAll(".tick text").attr("transform","rotate("+w+" 0,0)").style("text-anchor",w>0?"start":"end"),L.select(".nv-x.nv-axis").selectAll("g.nv-axisMaxMin text").style("opacity",1)}s&&(g.scale(d)._ticks(a.utils.calcTicksY(H/36,j)).tickSize(-D,0),L.select(".nv-y.nv-axis").call(g)),h.dispatch.on("stateChange",function(a){for(var c in a)x[c]=a[c];A.stateChange(x),b.update()}),i.dispatch.on("legendClick",function(a){if(a.disabled){switch(M=M.map(function(a){return a.disabled=!0,a}),a.disabled=!1,a.key){case"Grouped":case p.grouped:e.stacked(!1);break;case"Stacked":case p.stacked:e.stacked(!0)}x.stacked=e.stacked(),A.stateChange(x),b.update()}}),A.on("changeState",function(a){"undefined"!=typeof a.disabled&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),x.disabled=a.disabled),"undefined"!=typeof a.stacked&&(e.stacked(a.stacked),x.stacked=a.stacked,E=a.stacked),b.update()})}),D.renderEnd("multibarchart immediate"),b}var c,d,e=a.models.multiBar(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.models.legend(),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=null,m=null,n=a.utils.defaultColor(),o=!0,p={},q=!0,r=!0,s=!0,t=!1,u=!0,v=!1,w=0,x=a.utils.state(),y=null,z=null,A=d3.dispatch("stateChange","changeState","renderEnd"),B=function(){return o?180:0},C=250;x.stacked=!1,e.stacked(!1),f.orient("bottom").tickPadding(7).showMaxMin(!1).tickFormat(function(a){return a}),g.orient(t?"right":"left").tickFormat(d3.format(",.1f")),j.duration(0).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)}),i.updateState(!1);var D=a.utils.renderWatch(A),E=!1,F=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),stacked:E}}},G=function(a){return function(b){void 0!==b.stacked&&(E=b.stacked),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return e.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={key:a.data.key,value:b.y()(a.data),color:a.color},j.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(){j.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(){j.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=A,b.multibar=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.state=x,b.tooltip=j,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return l},set:function(a){l=a}},height:{get:function(){return m},set:function(a){m=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showControls:{get:function(){return o},set:function(a){o=a}},controlLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return y},set:function(a){y=a}},noData:{get:function(){return z},set:function(a){z=a}},reduceXTicks:{get:function(){return u},set:function(a){u=a}},rotateLabels:{get:function(){return w},set:function(a){w=a}},staggerLabels:{get:function(){return v},set:function(a){v=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return C},set:function(a){C=a,e.duration(C),f.duration(C),g.duration(C),D.reset(C)}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),h.color(n)}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,g.orient(t?"right":"left")}},barColor:{get:function(){return e.barColor},set:function(a){e.barColor(a),h.color(function(a,b){return d3.rgb("#ccc").darker(1.5*b).toString()})}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.multiBarHorizontal=function(){"use strict";function b(m){return E.reset(),m.each(function(b){var m=k-j.left-j.right,C=l-j.top-j.bottom;n=d3.select(this),a.utils.initSVG(n),w&&(b=d3.layout.stack().offset("zero").values(function(a){return a.values}).y(r)(b)),b.forEach(function(a,b){a.values.forEach(function(c){c.series=b,c.key=a.key})}),w&&b[0].values.map(function(a,c){var d=0,e=0;b.map(function(a){var b=a.values[c];b.size=Math.abs(b.y),b.y<0?(b.y1=e-b.size,e-=b.size):(b.y1=d,d+=b.size)})});var F=d&&e?[]:b.map(function(a){return a.values.map(function(a,b){return{x:q(a,b),y:r(a,b),y0:a.y0,y1:a.y1}})});o.domain(d||d3.merge(F).map(function(a){return a.x})).rangeBands(f||[0,C],A),p.domain(e||d3.extent(d3.merge(F).map(function(a){return w?a.y>0?a.y1+a.y:a.y1:a.y}).concat(t))),p.range(x&&!w?g||[p.domain()[0]<0?z:0,m-(p.domain()[1]>0?z:0)]:g||[0,m]),h=h||o,i=i||d3.scale.linear().domain(p.domain()).range([p(0),p(0)]);{var G=d3.select(this).selectAll("g.nv-wrap.nv-multibarHorizontal").data([b]),H=G.enter().append("g").attr("class","nvd3 nv-wrap nv-multibarHorizontal"),I=(H.append("defs"),H.append("g"));G.select("g")}I.append("g").attr("class","nv-groups"),G.attr("transform","translate("+j.left+","+j.top+")");var J=G.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a,b){return b});J.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),J.exit().watchTransition(E,"multibarhorizontal: exit groups").style("stroke-opacity",1e-6).style("fill-opacity",1e-6).remove(),J.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}).style("fill",function(a,b){return u(a,b)}).style("stroke",function(a,b){return u(a,b)}),J.watchTransition(E,"multibarhorizontal: groups").style("stroke-opacity",1).style("fill-opacity",.75);var K=J.selectAll("g.nv-bar").data(function(a){return a.values});K.exit().remove();var L=K.enter().append("g").attr("transform",function(a,c,d){return"translate("+i(w?a.y0:0)+","+(w?0:d*o.rangeBand()/b.length+o(q(a,c)))+")"});L.append("rect").attr("width",0).attr("height",o.rangeBand()/(w?1:b.length)),K.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),D.elementMouseover({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){d3.select(this).classed("hover",!1),D.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mouseout",function(a,b){D.elementMouseout({data:a,index:b,color:d3.select(this).style("fill")})}).on("mousemove",function(a,b){D.elementMousemove({data:a,index:b,color:d3.select(this).style("fill")})}).on("click",function(a,b){D.elementClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}).on("dblclick",function(a,b){D.elementDblClick({data:a,index:b,color:d3.select(this).style("fill")}),d3.event.stopPropagation()}),s(b[0],0)&&(L.append("polyline"),K.select("polyline").attr("fill","none").attr("points",function(a,c){var d=s(a,c),e=.8*o.rangeBand()/(2*(w?1:b.length));d=d.length?d:[-Math.abs(d),Math.abs(d)],d=d.map(function(a){return p(a)-p(0)});var f=[[d[0],-e],[d[0],e],[d[0],0],[d[1],0],[d[1],-e],[d[1],e]];return f.map(function(a){return a.join(",")}).join(" ")}).attr("transform",function(a,c){var d=o.rangeBand()/(2*(w?1:b.length));return"translate("+(r(a,c)<0?0:p(r(a,c))-p(0))+", "+d+")"})),L.append("text"),x&&!w?(K.select("text").attr("text-anchor",function(a,b){return r(a,b)<0?"end":"start"}).attr("y",o.rangeBand()/(2*b.length)).attr("dy",".32em").text(function(a,b){var c=B(r(a,b)),d=s(a,b);return void 0===d?c:d.length?c+"+"+B(Math.abs(d[1]))+"-"+B(Math.abs(d[0])):c+"±"+B(Math.abs(d))}),K.watchTransition(E,"multibarhorizontal: bars").select("text").attr("x",function(a,b){return r(a,b)<0?-4:p(r(a,b))-p(0)+4})):K.selectAll("text").text(""),y&&!w?(L.append("text").classed("nv-bar-label",!0),K.select("text.nv-bar-label").attr("text-anchor",function(a,b){return r(a,b)<0?"start":"end"}).attr("y",o.rangeBand()/(2*b.length)).attr("dy",".32em").text(function(a,b){return q(a,b)}),K.watchTransition(E,"multibarhorizontal: bars").select("text.nv-bar-label").attr("x",function(a,b){return r(a,b)<0?p(0)-p(r(a,b))+4:-4})):K.selectAll("text.nv-bar-label").text(""),K.attr("class",function(a,b){return r(a,b)<0?"nv-bar negative":"nv-bar positive"}),v&&(c||(c=b.map(function(){return!0})),K.style("fill",function(a,b,d){return d3.rgb(v(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()}).style("stroke",function(a,b,d){return d3.rgb(v(a,b)).darker(c.map(function(a,b){return b}).filter(function(a,b){return!c[b]})[d]).toString()})),w?K.watchTransition(E,"multibarhorizontal: bars").attr("transform",function(a,b){return"translate("+p(a.y1)+","+o(q(a,b))+")"}).select("rect").attr("width",function(a,b){return Math.abs(p(r(a,b)+a.y0)-p(a.y0))}).attr("height",o.rangeBand()):K.watchTransition(E,"multibarhorizontal: bars").attr("transform",function(a,c){return"translate("+p(r(a,c)<0?r(a,c):0)+","+(a.series*o.rangeBand()/b.length+o(q(a,c)))+")"}).select("rect").attr("height",o.rangeBand()/b.length).attr("width",function(a,b){return Math.max(Math.abs(p(r(a,b))-p(0)),1)}),h=o.copy(),i=p.copy()}),E.renderEnd("multibarHorizontal immediate"),b}var c,d,e,f,g,h,i,j={top:0,right:0,bottom:0,left:0},k=960,l=500,m=Math.floor(1e4*Math.random()),n=null,o=d3.scale.ordinal(),p=d3.scale.linear(),q=function(a){return a.x},r=function(a){return a.y},s=function(a){return a.yErr},t=[0],u=a.utils.defaultColor(),v=null,w=!1,x=!1,y=!1,z=60,A=.1,B=d3.format(",.2f"),C=250,D=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),E=a.utils.renderWatch(D,C);return b.dispatch=D,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},x:{get:function(){return q},set:function(a){q=a}},y:{get:function(){return r},set:function(a){r=a}},yErr:{get:function(){return s},set:function(a){s=a}},xScale:{get:function(){return o},set:function(a){o=a}},yScale:{get:function(){return p},set:function(a){p=a}},xDomain:{get:function(){return d},set:function(a){d=a}},yDomain:{get:function(){return e},set:function(a){e=a}},xRange:{get:function(){return f},set:function(a){f=a}},yRange:{get:function(){return g},set:function(a){g=a}},forceY:{get:function(){return t},set:function(a){t=a}},stacked:{get:function(){return w},set:function(a){w=a}},showValues:{get:function(){return x},set:function(a){x=a}},disabled:{get:function(){return c},set:function(a){c=a}},id:{get:function(){return m},set:function(a){m=a}},valueFormat:{get:function(){return B},set:function(a){B=a}},valuePadding:{get:function(){return z},set:function(a){z=a}},groupSpacing:{get:function(){return A},set:function(a){A=a}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},duration:{get:function(){return C},set:function(a){C=a,E.reset(C)}},color:{get:function(){return u},set:function(b){u=a.utils.getColor(b)}},barColor:{get:function(){return v},set:function(b){v=b?a.utils.getColor(b):null}}}),a.utils.initOptions(b),b},a.models.multiBarHorizontalChart=function(){"use strict";function b(j){return C.reset(),C.models(e),r&&C.models(f),s&&C.models(g),j.each(function(j){var w=d3.select(this);a.utils.initSVG(w);var C=a.utils.availableWidth(l,w,k),D=a.utils.availableHeight(m,w,k);if(b.update=function(){w.transition().duration(z).call(b)},b.container=this,t=e.stacked(),u.setter(B(j),b.update).getter(A(j)).update(),u.disabled=j.map(function(a){return!!a.disabled}),!v){var E;v={};for(E in u)v[E]=u[E]instanceof Array?u[E].slice(0):u[E]}if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,w),b;w.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var F=w.selectAll("g.nv-wrap.nv-multiBarHorizontalChart").data([j]),G=F.enter().append("g").attr("class","nvd3 nv-wrap nv-multiBarHorizontalChart").append("g"),H=F.select("g");if(G.append("g").attr("class","nv-x nv-axis"),G.append("g").attr("class","nv-y nv-axis").append("g").attr("class","nv-zeroLine").append("line"),G.append("g").attr("class","nv-barsWrap"),G.append("g").attr("class","nv-legendWrap"),G.append("g").attr("class","nv-controlsWrap"),q&&(h.width(C-y()),H.select(".nv-legendWrap").datum(j).call(h),k.top!=h.height()&&(k.top=h.height(),D=a.utils.availableHeight(m,w,k)),H.select(".nv-legendWrap").attr("transform","translate("+y()+","+-k.top+")")),o){var I=[{key:p.grouped||"Grouped",disabled:e.stacked()},{key:p.stacked||"Stacked",disabled:!e.stacked()}];i.width(y()).color(["#444","#444","#444"]),H.select(".nv-controlsWrap").datum(I).attr("transform","translate(0,"+-k.top+")").call(i)}F.attr("transform","translate("+k.left+","+k.top+")"),e.disabled(j.map(function(a){return a.disabled})).width(C).height(D).color(j.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!j[b].disabled}));var J=H.select(".nv-barsWrap").datum(j.filter(function(a){return!a.disabled}));if(J.transition().call(e),r){f.scale(c)._ticks(a.utils.calcTicksY(D/24,j)).tickSize(-C,0),H.select(".nv-x.nv-axis").call(f);var K=H.select(".nv-x.nv-axis").selectAll("g");K.selectAll("line, text")}s&&(g.scale(d)._ticks(a.utils.calcTicksX(C/100,j)).tickSize(-D,0),H.select(".nv-y.nv-axis").attr("transform","translate(0,"+D+")"),H.select(".nv-y.nv-axis").call(g)),H.select(".nv-zeroLine line").attr("x1",d(0)).attr("x2",d(0)).attr("y1",0).attr("y2",-D),h.dispatch.on("stateChange",function(a){for(var c in a)u[c]=a[c];x.stateChange(u),b.update()}),i.dispatch.on("legendClick",function(a){if(a.disabled){switch(I=I.map(function(a){return a.disabled=!0,a}),a.disabled=!1,a.key){case"Grouped":e.stacked(!1);break;case"Stacked":e.stacked(!0)}u.stacked=e.stacked(),x.stateChange(u),t=e.stacked(),b.update()}}),x.on("changeState",function(a){"undefined"!=typeof a.disabled&&(j.forEach(function(b,c){b.disabled=a.disabled[c]}),u.disabled=a.disabled),"undefined"!=typeof a.stacked&&(e.stacked(a.stacked),u.stacked=a.stacked,t=a.stacked),b.update()})}),C.renderEnd("multibar horizontal chart immediate"),b}var c,d,e=a.models.multiBarHorizontal(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend().height(30),i=a.models.legend().height(30),j=a.models.tooltip(),k={top:30,right:20,bottom:50,left:60},l=null,m=null,n=a.utils.defaultColor(),o=!0,p={},q=!0,r=!0,s=!0,t=!1,u=a.utils.state(),v=null,w=null,x=d3.dispatch("stateChange","changeState","renderEnd"),y=function(){return o?180:0},z=250;u.stacked=!1,e.stacked(t),f.orient("left").tickPadding(5).showMaxMin(!1).tickFormat(function(a){return a}),g.orient("bottom").tickFormat(d3.format(",.1f")),j.duration(0).valueFormatter(function(a,b){return g.tickFormat()(a,b)}).headerFormatter(function(a,b){return f.tickFormat()(a,b)}),i.updateState(!1);var A=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),stacked:t}}},B=function(a){return function(b){void 0!==b.stacked&&(t=b.stacked),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}},C=a.utils.renderWatch(x,z);return e.dispatch.on("elementMouseover.tooltip",function(a){a.value=b.x()(a.data),a.series={key:a.data.key,value:b.y()(a.data),color:a.color},j.data(a).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(){j.hidden(!0)}),e.dispatch.on("elementMousemove.tooltip",function(){j.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=x,b.multibar=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.state=u,b.tooltip=j,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return l},set:function(a){l=a}},height:{get:function(){return m},set:function(a){m=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showControls:{get:function(){return o},set:function(a){o=a}},controlLabels:{get:function(){return p},set:function(a){p=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return v},set:function(a){v=a}},noData:{get:function(){return w},set:function(a){w=a}},tooltips:{get:function(){return j.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),j.enabled(!!b)}},tooltipContent:{get:function(){return j.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),j.contentGenerator(b)}},margin:{get:function(){return k},set:function(a){k.top=void 0!==a.top?a.top:k.top,k.right=void 0!==a.right?a.right:k.right,k.bottom=void 0!==a.bottom?a.bottom:k.bottom,k.left=void 0!==a.left?a.left:k.left}},duration:{get:function(){return z},set:function(a){z=a,C.reset(z),e.duration(z),f.duration(z),g.duration(z)}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),h.color(n)}},barColor:{get:function(){return e.barColor},set:function(a){e.barColor(a),h.color(function(a,b){return d3.rgb("#ccc").darker(1.5*b).toString()})}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.multiChart=function(){"use strict";function b(j){return j.each(function(j){function k(a){var b=2===j[a.seriesIndex].yAxis?z:y;a.value=a.point.x,a.series={value:a.point.y,color:a.point.color},B.duration(100).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).position(a.pos).hidden(!1)}function l(a){var b=2===j[a.seriesIndex].yAxis?z:y;a.point.x=v.x()(a.point),a.point.y=v.y()(a.point),B.duration(100).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).position(a.pos).hidden(!1)}function n(a){var b=2===j[a.data.series].yAxis?z:y;a.value=t.x()(a.data),a.series={value:t.y()(a.data),color:a.color},B.duration(0).valueFormatter(function(a,c){return b.tickFormat()(a,c)}).data(a).hidden(!1)}var C=d3.select(this);a.utils.initSVG(C),b.update=function(){C.transition().call(b)},b.container=this;var D=a.utils.availableWidth(g,C,e),E=a.utils.availableHeight(h,C,e),F=j.filter(function(a){return"line"==a.type&&1==a.yAxis}),G=j.filter(function(a){return"line"==a.type&&2==a.yAxis}),H=j.filter(function(a){return"bar"==a.type&&1==a.yAxis}),I=j.filter(function(a){return"bar"==a.type&&2==a.yAxis}),J=j.filter(function(a){return"area"==a.type&&1==a.yAxis}),K=j.filter(function(a){return"area"==a.type&&2==a.yAxis});if(!(j&&j.length&&j.filter(function(a){return a.values.length}).length))return a.utils.noData(b,C),b;C.selectAll(".nv-noData").remove();var L=j.filter(function(a){return!a.disabled&&1==a.yAxis}).map(function(a){return a.values.map(function(a){return{x:a.x,y:a.y}})}),M=j.filter(function(a){return!a.disabled&&2==a.yAxis}).map(function(a){return a.values.map(function(a){return{x:a.x,y:a.y}})});o.domain(d3.extent(d3.merge(L.concat(M)),function(a){return a.x})).range([0,D]);var N=C.selectAll("g.wrap.multiChart").data([j]),O=N.enter().append("g").attr("class","wrap nvd3 multiChart").append("g");O.append("g").attr("class","nv-x nv-axis"),O.append("g").attr("class","nv-y1 nv-axis"),O.append("g").attr("class","nv-y2 nv-axis"),O.append("g").attr("class","lines1Wrap"),O.append("g").attr("class","lines2Wrap"),O.append("g").attr("class","bars1Wrap"),O.append("g").attr("class","bars2Wrap"),O.append("g").attr("class","stack1Wrap"),O.append("g").attr("class","stack2Wrap"),O.append("g").attr("class","legendWrap");var P=N.select("g"),Q=j.map(function(a,b){return j[b].color||f(a,b)});if(i){var R=A.align()?D/2:D,S=A.align()?R:0;A.width(R),A.color(Q),P.select(".legendWrap").datum(j.map(function(a){return a.originalKey=void 0===a.originalKey?a.key:a.originalKey,a.key=a.originalKey+(1==a.yAxis?"":" (right axis)"),a})).call(A),e.top!=A.height()&&(e.top=A.height(),E=a.utils.availableHeight(h,C,e)),P.select(".legendWrap").attr("transform","translate("+S+","+-e.top+")")}r.width(D).height(E).interpolate(m).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"line"==j[b].type})),s.width(D).height(E).interpolate(m).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"line"==j[b].type})),t.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"bar"==j[b].type})),u.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"bar"==j[b].type})),v.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&1==j[b].yAxis&&"area"==j[b].type})),w.width(D).height(E).color(Q.filter(function(a,b){return!j[b].disabled&&2==j[b].yAxis&&"area"==j[b].type})),P.attr("transform","translate("+e.left+","+e.top+")");var T=P.select(".lines1Wrap").datum(F.filter(function(a){return!a.disabled})),U=P.select(".bars1Wrap").datum(H.filter(function(a){return!a.disabled})),V=P.select(".stack1Wrap").datum(J.filter(function(a){return!a.disabled})),W=P.select(".lines2Wrap").datum(G.filter(function(a){return!a.disabled})),X=P.select(".bars2Wrap").datum(I.filter(function(a){return!a.disabled})),Y=P.select(".stack2Wrap").datum(K.filter(function(a){return!a.disabled})),Z=J.length?J.map(function(a){return a.values}).reduce(function(a,b){return a.map(function(a,c){return{x:a.x,y:a.y+b[c].y}})}).concat([{x:0,y:0}]):[],$=K.length?K.map(function(a){return a.values}).reduce(function(a,b){return a.map(function(a,c){return{x:a.x,y:a.y+b[c].y}})}).concat([{x:0,y:0}]):[];p.domain(c||d3.extent(d3.merge(L).concat(Z),function(a){return a.y})).range([0,E]),q.domain(d||d3.extent(d3.merge(M).concat($),function(a){return a.y})).range([0,E]),r.yDomain(p.domain()),t.yDomain(p.domain()),v.yDomain(p.domain()),s.yDomain(q.domain()),u.yDomain(q.domain()),w.yDomain(q.domain()),J.length&&d3.transition(V).call(v),K.length&&d3.transition(Y).call(w),H.length&&d3.transition(U).call(t),I.length&&d3.transition(X).call(u),F.length&&d3.transition(T).call(r),G.length&&d3.transition(W).call(s),x._ticks(a.utils.calcTicksX(D/100,j)).tickSize(-E,0),P.select(".nv-x.nv-axis").attr("transform","translate(0,"+E+")"),d3.transition(P.select(".nv-x.nv-axis")).call(x),y._ticks(a.utils.calcTicksY(E/36,j)).tickSize(-D,0),d3.transition(P.select(".nv-y1.nv-axis")).call(y),z._ticks(a.utils.calcTicksY(E/36,j)).tickSize(-D,0),d3.transition(P.select(".nv-y2.nv-axis")).call(z),P.select(".nv-y1.nv-axis").classed("nv-disabled",L.length?!1:!0).attr("transform","translate("+o.range()[0]+",0)"),P.select(".nv-y2.nv-axis").classed("nv-disabled",M.length?!1:!0).attr("transform","translate("+o.range()[1]+",0)"),A.dispatch.on("stateChange",function(){b.update()}),r.dispatch.on("elementMouseover.tooltip",k),s.dispatch.on("elementMouseover.tooltip",k),r.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),s.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),v.dispatch.on("elementMouseover.tooltip",l),w.dispatch.on("elementMouseover.tooltip",l),v.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),w.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),t.dispatch.on("elementMouseover.tooltip",n),u.dispatch.on("elementMouseover.tooltip",n),t.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),u.dispatch.on("elementMouseout.tooltip",function(){B.hidden(!0)}),t.dispatch.on("elementMousemove.tooltip",function(){B.position({top:d3.event.pageY,left:d3.event.pageX})()}),u.dispatch.on("elementMousemove.tooltip",function(){B.position({top:d3.event.pageY,left:d3.event.pageX})()})}),b}var c,d,e={top:30,right:20,bottom:50,left:60},f=a.utils.defaultColor(),g=null,h=null,i=!0,j=null,k=function(a){return a.x},l=function(a){return a.y},m="monotone",n=!0,o=d3.scale.linear(),p=d3.scale.linear(),q=d3.scale.linear(),r=a.models.line().yScale(p),s=a.models.line().yScale(q),t=a.models.multiBar().stacked(!1).yScale(p),u=a.models.multiBar().stacked(!1).yScale(q),v=a.models.stackedArea().yScale(p),w=a.models.stackedArea().yScale(q),x=a.models.axis().scale(o).orient("bottom").tickPadding(5),y=a.models.axis().scale(p).orient("left"),z=a.models.axis().scale(q).orient("right"),A=a.models.legend().height(30),B=a.models.tooltip(),C=d3.dispatch();return b.dispatch=C,b.lines1=r,b.lines2=s,b.bars1=t,b.bars2=u,b.stack1=v,b.stack2=w,b.xAxis=x,b.yAxis1=y,b.yAxis2=z,b.tooltip=B,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},showLegend:{get:function(){return i},set:function(a){i=a}},yDomain1:{get:function(){return c},set:function(a){c=a}},yDomain2:{get:function(){return d},set:function(a){d=a}},noData:{get:function(){return j},set:function(a){j=a}},interpolate:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return B.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),B.enabled(!!b)}},tooltipContent:{get:function(){return B.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),B.contentGenerator(b)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},color:{get:function(){return f},set:function(b){f=a.utils.getColor(b)}},x:{get:function(){return k},set:function(a){k=a,r.x(a),s.x(a),t.x(a),u.x(a),v.x(a),w.x(a)}},y:{get:function(){return l},set:function(a){l=a,r.y(a),s.y(a),v.y(a),w.y(a),t.y(a),u.y(a)}},useVoronoi:{get:function(){return n},set:function(a){n=a,r.useVoronoi(a),s.useVoronoi(a),v.useVoronoi(a),w.useVoronoi(a)}}}),a.utils.initOptions(b),b},a.models.ohlcBar=function(){"use strict";function b(y){return y.each(function(b){k=d3.select(this);var y=a.utils.availableWidth(h,k,g),A=a.utils.availableHeight(i,k,g);a.utils.initSVG(k);var B=y/b[0].values.length*.9;l.domain(c||d3.extent(b[0].values.map(n).concat(t))),l.range(v?e||[.5*y/b[0].values.length,y*(b[0].values.length-.5)/b[0].values.length]:e||[5+B/2,y-B/2-5]),m.domain(d||[d3.min(b[0].values.map(s).concat(u)),d3.max(b[0].values.map(r).concat(u))]).range(f||[A,0]),l.domain()[0]===l.domain()[1]&&l.domain(l.domain()[0]?[l.domain()[0]-.01*l.domain()[0],l.domain()[1]+.01*l.domain()[1]]:[-1,1]),m.domain()[0]===m.domain()[1]&&m.domain(m.domain()[0]?[m.domain()[0]+.01*m.domain()[0],m.domain()[1]-.01*m.domain()[1]]:[-1,1]);var C=d3.select(this).selectAll("g.nv-wrap.nv-ohlcBar").data([b[0].values]),D=C.enter().append("g").attr("class","nvd3 nv-wrap nv-ohlcBar"),E=D.append("defs"),F=D.append("g"),G=C.select("g");F.append("g").attr("class","nv-ticks"),C.attr("transform","translate("+g.left+","+g.top+")"),k.on("click",function(a,b){z.chartClick({data:a,index:b,pos:d3.event,id:j})}),E.append("clipPath").attr("id","nv-chart-clip-path-"+j).append("rect"),C.select("#nv-chart-clip-path-"+j+" rect").attr("width",y).attr("height",A),G.attr("clip-path",w?"url(#nv-chart-clip-path-"+j+")":"");var H=C.select(".nv-ticks").selectAll(".nv-tick").data(function(a){return a});H.exit().remove(),H.enter().append("path").attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b}).attr("d",function(a,b){return"m0,0l0,"+(m(p(a,b))-m(r(a,b)))+"l"+-B/2+",0l"+B/2+",0l0,"+(m(s(a,b))-m(p(a,b)))+"l0,"+(m(q(a,b))-m(s(a,b)))+"l"+B/2+",0l"+-B/2+",0z"}).attr("transform",function(a,b){return"translate("+l(n(a,b))+","+m(r(a,b))+")"}).attr("fill",function(){return x[0]}).attr("stroke",function(){return x[0]}).attr("x",0).attr("y",function(a,b){return m(Math.max(0,o(a,b)))}).attr("height",function(a,b){return Math.abs(m(o(a,b))-m(0))}),H.attr("class",function(a,b,c){return(p(a,b)>q(a,b)?"nv-tick negative":"nv-tick positive")+" nv-tick-"+c+"-"+b}),d3.transition(H).attr("transform",function(a,b){return"translate("+l(n(a,b))+","+m(r(a,b))+")"}).attr("d",function(a,c){var d=y/b[0].values.length*.9;return"m0,0l0,"+(m(p(a,c))-m(r(a,c)))+"l"+-d/2+",0l"+d/2+",0l0,"+(m(s(a,c))-m(p(a,c)))+"l0,"+(m(q(a,c))-m(s(a,c)))+"l"+d/2+",0l"+-d/2+",0z"})}),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=Math.floor(1e4*Math.random()),k=null,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=function(a){return a.open},q=function(a){return a.close},r=function(a){return a.high},s=function(a){return a.low},t=[],u=[],v=!1,w=!0,x=a.utils.defaultColor(),y=!1,z=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd","chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove");return b.highlightPoint=function(a,c){b.clearHighlights(),k.select(".nv-ohlcBar .nv-tick-0-"+a).classed("hover",c)},b.clearHighlights=function(){k.select(".nv-ohlcBar .nv-tick.hover").classed("hover",!1)},b.dispatch=z,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},padData:{get:function(){return v},set:function(a){v=a}},clipEdge:{get:function(){return w},set:function(a){w=a}},id:{get:function(){return j},set:function(a){j=a}},interactive:{get:function(){return y},set:function(a){y=a}},x:{get:function(){return n},set:function(a){n=a}},y:{get:function(){return o},set:function(a){o=a}},open:{get:function(){return p()},set:function(a){p=a}},close:{get:function(){return q()},set:function(a){q=a}},high:{get:function(){return r},set:function(a){r=a}},low:{get:function(){return s},set:function(a){s=a}},margin:{get:function(){return g},set:function(a){g.top=void 0!=a.top?a.top:g.top,g.right=void 0!=a.right?a.right:g.right,g.bottom=void 0!=a.bottom?a.bottom:g.bottom,g.left=void 0!=a.left?a.left:g.left
}},color:{get:function(){return x},set:function(b){x=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.parallelCoordinates=function(){"use strict";function b(p){return p.each(function(b){function p(a){return F(h.map(function(b){if(isNaN(a[b])||isNaN(parseFloat(a[b]))){var c=g[b].domain(),d=g[b].range(),e=c[0]-(c[1]-c[0])/9;if(J.indexOf(b)<0){var h=d3.scale.linear().domain([e,c[1]]).range([x-12,d[1]]);g[b].brush.y(h),J.push(b)}return[f(b),g[b](e)]}return J.length>0?(D.style("display","inline"),E.style("display","inline")):(D.style("display","none"),E.style("display","none")),[f(b),g[b](a[b])]}))}function q(){var a=h.filter(function(a){return!g[a].brush.empty()}),b=a.map(function(a){return g[a].brush.extent()});k=[],a.forEach(function(a,c){k[c]={dimension:a,extent:b[c]}}),l=[],M.style("display",function(c){var d=a.every(function(a,d){return isNaN(c[a])&&b[d][0]==g[a].brush.y().domain()[0]?!0:b[d][0]<=c[a]&&c[a]<=b[d][1]});return d&&l.push(c),d?null:"none"}),o.brush({filters:k,active:l})}function r(a){m[a]=this.parentNode.__origin__=f(a),L.attr("visibility","hidden")}function s(a){m[a]=Math.min(w,Math.max(0,this.parentNode.__origin__+=d3.event.x)),M.attr("d",p),h.sort(function(a,b){return u(a)-u(b)}),f.domain(h),N.attr("transform",function(a){return"translate("+u(a)+")"})}function t(a){delete this.parentNode.__origin__,delete m[a],d3.select(this.parentNode).attr("transform","translate("+f(a)+")"),M.attr("d",p),L.attr("d",p).attr("visibility",null)}function u(a){var b=m[a];return null==b?f(a):b}var v=d3.select(this),w=a.utils.availableWidth(d,v,c),x=a.utils.availableHeight(e,v,c);a.utils.initSVG(v),l=b,f.rangePoints([0,w],1).domain(h);var y={};h.forEach(function(a){var c=d3.extent(b,function(b){return+b[a]});return y[a]=!1,void 0===c[0]&&(y[a]=!0,c[0]=0,c[1]=0),c[0]===c[1]&&(c[0]=c[0]-1,c[1]=c[1]+1),g[a]=d3.scale.linear().domain(c).range([.9*(x-12),0]),g[a].brush=d3.svg.brush().y(g[a]).on("brush",q),"name"!=a});var z=v.selectAll("g.nv-wrap.nv-parallelCoordinates").data([b]),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-parallelCoordinates"),B=A.append("g"),C=z.select("g");B.append("g").attr("class","nv-parallelCoordinates background"),B.append("g").attr("class","nv-parallelCoordinates foreground"),B.append("g").attr("class","nv-parallelCoordinates missingValuesline"),z.attr("transform","translate("+c.left+","+c.top+")");var D,E,F=d3.svg.line().interpolate("cardinal").tension(n),G=d3.svg.axis().orient("left"),H=d3.behavior.drag().on("dragstart",r).on("drag",s).on("dragend",t),I=f.range()[1]-f.range()[0],J=[],K=[0+I/2,x-12,w-I/2,x-12];D=z.select(".missingValuesline").selectAll("line").data([K]),D.enter().append("line"),D.exit().remove(),D.attr("x1",function(a){return a[0]}).attr("y1",function(a){return a[1]}).attr("x2",function(a){return a[2]}).attr("y2",function(a){return a[3]}),E=z.select(".missingValuesline").selectAll("text").data(["undefined values"]),E.append("text").data(["undefined values"]),E.enter().append("text"),E.exit().remove(),E.attr("y",x).attr("x",w-92-I/2).text(function(a){return a});var L=z.select(".background").selectAll("path").data(b);L.enter().append("path"),L.exit().remove(),L.attr("d",p);var M=z.select(".foreground").selectAll("path").data(b);M.enter().append("path"),M.exit().remove(),M.attr("d",p).attr("stroke",j),M.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),o.elementMouseover({label:a.name,data:a.data,index:b,pos:[d3.mouse(this.parentNode)[0],d3.mouse(this.parentNode)[1]]})}),M.on("mouseout",function(a,b){d3.select(this).classed("hover",!1),o.elementMouseout({label:a.name,data:a.data,index:b})});var N=C.selectAll(".dimension").data(h),O=N.enter().append("g").attr("class","nv-parallelCoordinates dimension");O.append("g").attr("class","nv-parallelCoordinates nv-axis"),O.append("g").attr("class","nv-parallelCoordinates-brush"),O.append("text").attr("class","nv-parallelCoordinates nv-label"),N.attr("transform",function(a){return"translate("+f(a)+",0)"}),N.exit().remove(),N.select(".nv-label").style("cursor","move").attr("dy","-1em").attr("text-anchor","middle").text(String).on("mouseover",function(a){o.elementMouseover({dim:a,pos:[d3.mouse(this.parentNode.parentNode)[0],d3.mouse(this.parentNode.parentNode)[1]]})}).on("mouseout",function(a){o.elementMouseout({dim:a})}).call(H),N.select(".nv-axis").each(function(a,b){d3.select(this).call(G.scale(g[a]).tickFormat(d3.format(i[b])))}),N.select(".nv-parallelCoordinates-brush").each(function(a){d3.select(this).call(g[a].brush)}).selectAll("rect").attr("x",-8).attr("width",16)}),b}var c={top:30,right:0,bottom:10,left:0},d=null,e=null,f=d3.scale.ordinal(),g={},h=[],i=[],j=a.utils.defaultColor(),k=[],l=[],m=[],n=1,o=d3.dispatch("brush","elementMouseover","elementMouseout");return b.dispatch=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},dimensionNames:{get:function(){return h},set:function(a){h=a}},dimensionFormats:{get:function(){return i},set:function(a){i=a}},lineTension:{get:function(){return n},set:function(a){n=a}},dimensions:{get:function(){return h},set:function(b){a.deprecated("dimensions","use dimensionNames instead"),h=b}},margin:{get:function(){return c},set:function(a){c.top=void 0!==a.top?a.top:c.top,c.right=void 0!==a.right?a.right:c.right,c.bottom=void 0!==a.bottom?a.bottom:c.bottom,c.left=void 0!==a.left?a.left:c.left}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.pie=function(){"use strict";function b(E){return D.reset(),E.each(function(b){function E(a,b){a.endAngle=isNaN(a.endAngle)?0:a.endAngle,a.startAngle=isNaN(a.startAngle)?0:a.startAngle,p||(a.innerRadius=0);var c=d3.interpolate(this._current,a);return this._current=c(0),function(a){return B[b](c(a))}}var F=d-c.left-c.right,G=e-c.top-c.bottom,H=Math.min(F,G)/2,I=[],J=[];if(i=d3.select(this),0===z.length)for(var K=H-H/5,L=y*H,M=0;M<b[0].length;M++)I.push(K),J.push(L);else I=z.map(function(a){return(a.outer-a.outer/5)*H}),J=z.map(function(a){return(a.inner-a.inner/5)*H}),y=d3.min(z.map(function(a){return a.inner-a.inner/5}));a.utils.initSVG(i);var N=i.selectAll(".nv-wrap.nv-pie").data(b),O=N.enter().append("g").attr("class","nvd3 nv-wrap nv-pie nv-chart-"+h),P=O.append("g"),Q=N.select("g"),R=P.append("g").attr("class","nv-pie");P.append("g").attr("class","nv-pieLabels"),N.attr("transform","translate("+c.left+","+c.top+")"),Q.select(".nv-pie").attr("transform","translate("+F/2+","+G/2+")"),Q.select(".nv-pieLabels").attr("transform","translate("+F/2+","+G/2+")"),i.on("click",function(a,b){A.chartClick({data:a,index:b,pos:d3.event,id:h})}),B=[],C=[];for(var M=0;M<b[0].length;M++){var S=d3.svg.arc().outerRadius(I[M]),T=d3.svg.arc().outerRadius(I[M]+5);u!==!1&&(S.startAngle(u),T.startAngle(u)),w!==!1&&(S.endAngle(w),T.endAngle(w)),p&&(S.innerRadius(J[M]),T.innerRadius(J[M])),S.cornerRadius&&x&&(S.cornerRadius(x),T.cornerRadius(x)),B.push(S),C.push(T)}var U=d3.layout.pie().sort(null).value(function(a){return a.disabled?0:g(a)});U.padAngle&&v&&U.padAngle(v),p&&q&&(R.append("text").attr("class","nv-pie-title"),N.select(".nv-pie-title").style("text-anchor","middle").text(function(){return q}).style("font-size",Math.min(F,G)*y*2/(q.length+2)+"px").attr("dy","0.35em").attr("transform",function(){return"translate(0, "+s+")"}));var V=N.select(".nv-pie").selectAll(".nv-slice").data(U),W=N.select(".nv-pieLabels").selectAll(".nv-label").data(U);V.exit().remove(),W.exit().remove();var X=V.enter().append("g");X.attr("class","nv-slice"),X.on("mouseover",function(a,b){d3.select(this).classed("hover",!0),r&&d3.select(this).select("path").transition().duration(70).attr("d",C[b]),A.elementMouseover({data:a.data,index:b,color:d3.select(this).style("fill")})}),X.on("mouseout",function(a,b){d3.select(this).classed("hover",!1),r&&d3.select(this).select("path").transition().duration(50).attr("d",B[b]),A.elementMouseout({data:a.data,index:b})}),X.on("mousemove",function(a,b){A.elementMousemove({data:a.data,index:b})}),X.on("click",function(a,b){A.elementClick({data:a.data,index:b,color:d3.select(this).style("fill")})}),X.on("dblclick",function(a,b){A.elementDblClick({data:a.data,index:b,color:d3.select(this).style("fill")})}),V.attr("fill",function(a,b){return j(a.data,b)}),V.attr("stroke",function(a,b){return j(a.data,b)});X.append("path").each(function(a){this._current=a});if(V.select("path").transition().attr("d",function(a,b){return B[b](a)}).attrTween("d",E),l){for(var Y=[],M=0;M<b[0].length;M++)Y.push(B[M]),m?p&&(Y[M]=d3.svg.arc().outerRadius(B[M].outerRadius()),u!==!1&&Y[M].startAngle(u),w!==!1&&Y[M].endAngle(w)):p||Y[M].innerRadius(0);W.enter().append("g").classed("nv-label",!0).each(function(a){var b=d3.select(this);b.attr("transform",function(a,b){if(t){a.outerRadius=I[b]+10,a.innerRadius=I[b]+15;var c=(a.startAngle+a.endAngle)/2*(180/Math.PI);return(a.startAngle+a.endAngle)/2<Math.PI?c-=90:c+=90,"translate("+Y[b].centroid(a)+") rotate("+c+")"}return a.outerRadius=H+10,a.innerRadius=H+15,"translate("+Y[b].centroid(a)+")"}),b.append("rect").style("stroke","#fff").style("fill","#fff").attr("rx",3).attr("ry",3),b.append("text").style("text-anchor",t?(a.startAngle+a.endAngle)/2<Math.PI?"start":"end":"middle").style("fill","#000")});var Z={},$=14,_=140,ab=function(a){return Math.floor(a[0]/_)*_+","+Math.floor(a[1]/$)*$};W.watchTransition(D,"pie labels").attr("transform",function(a,b){if(t){a.outerRadius=I[b]+10,a.innerRadius=I[b]+15;var c=(a.startAngle+a.endAngle)/2*(180/Math.PI);return(a.startAngle+a.endAngle)/2<Math.PI?c-=90:c+=90,"translate("+Y[b].centroid(a)+") rotate("+c+")"}a.outerRadius=H+10,a.innerRadius=H+15;var d=Y[b].centroid(a);if(a.value){var e=ab(d);Z[e]&&(d[1]-=$),Z[ab(d)]=!0}return"translate("+d+")"}),W.select(".nv-label text").style("text-anchor",function(a){return t?(a.startAngle+a.endAngle)/2<Math.PI?"start":"end":"middle"}).text(function(a,b){var c=(a.endAngle-a.startAngle)/(2*Math.PI),d="";if(!a.value||o>c)return"";if("function"==typeof n)d=n(a,b,{key:f(a.data),value:g(a.data),percent:k(c)});else switch(n){case"key":d=f(a.data);break;case"value":d=k(g(a.data));break;case"percent":d=d3.format("%")(c)}return d})}}),D.renderEnd("pie immediate"),b}var c={top:0,right:0,bottom:0,left:0},d=500,e=500,f=function(a){return a.x},g=function(a){return a.y},h=Math.floor(1e4*Math.random()),i=null,j=a.utils.defaultColor(),k=d3.format(",.2f"),l=!0,m=!1,n="key",o=.02,p=!1,q=!1,r=!0,s=0,t=!1,u=!1,v=!1,w=!1,x=0,y=.5,z=[],A=d3.dispatch("chartClick","elementClick","elementDblClick","elementMouseover","elementMouseout","elementMousemove","renderEnd"),B=[],C=[],D=a.utils.renderWatch(A);return b.dispatch=A,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{arcsRadius:{get:function(){return z},set:function(a){z=a}},width:{get:function(){return d},set:function(a){d=a}},height:{get:function(){return e},set:function(a){e=a}},showLabels:{get:function(){return l},set:function(a){l=a}},title:{get:function(){return q},set:function(a){q=a}},titleOffset:{get:function(){return s},set:function(a){s=a}},labelThreshold:{get:function(){return o},set:function(a){o=a}},valueFormat:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return f},set:function(a){f=a}},id:{get:function(){return h},set:function(a){h=a}},endAngle:{get:function(){return w},set:function(a){w=a}},startAngle:{get:function(){return u},set:function(a){u=a}},padAngle:{get:function(){return v},set:function(a){v=a}},cornerRadius:{get:function(){return x},set:function(a){x=a}},donutRatio:{get:function(){return y},set:function(a){y=a}},labelsOutside:{get:function(){return m},set:function(a){m=a}},labelSunbeamLayout:{get:function(){return t},set:function(a){t=a}},donut:{get:function(){return p},set:function(a){p=a}},growOnHover:{get:function(){return r},set:function(a){r=a}},pieLabelsOutside:{get:function(){return m},set:function(b){m=b,a.deprecated("pieLabelsOutside","use labelsOutside instead")}},donutLabelsOutside:{get:function(){return m},set:function(b){m=b,a.deprecated("donutLabelsOutside","use labelsOutside instead")}},labelFormat:{get:function(){return k},set:function(b){k=b,a.deprecated("labelFormat","use valueFormat instead")}},margin:{get:function(){return c},set:function(a){c.top="undefined"!=typeof a.top?a.top:c.top,c.right="undefined"!=typeof a.right?a.right:c.right,c.bottom="undefined"!=typeof a.bottom?a.bottom:c.bottom,c.left="undefined"!=typeof a.left?a.left:c.left}},y:{get:function(){return g},set:function(a){g=d3.functor(a)}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}},labelType:{get:function(){return n},set:function(a){n=a||"key"}}}),a.utils.initOptions(b),b},a.models.pieChart=function(){"use strict";function b(e){return q.reset(),q.models(c),e.each(function(e){var k=d3.select(this);a.utils.initSVG(k);var n=a.utils.availableWidth(g,k,f),o=a.utils.availableHeight(h,k,f);if(b.update=function(){k.transition().call(b)},b.container=this,l.setter(s(e),b.update).getter(r(e)).update(),l.disabled=e.map(function(a){return!!a.disabled}),!m){var q;m={};for(q in l)m[q]=l[q]instanceof Array?l[q].slice(0):l[q]}if(!e||!e.length)return a.utils.noData(b,k),b;k.selectAll(".nv-noData").remove();var t=k.selectAll("g.nv-wrap.nv-pieChart").data([e]),u=t.enter().append("g").attr("class","nvd3 nv-wrap nv-pieChart").append("g"),v=t.select("g");if(u.append("g").attr("class","nv-pieWrap"),u.append("g").attr("class","nv-legendWrap"),i)if("top"===j)d.width(n).key(c.x()),t.select(".nv-legendWrap").datum(e).call(d),f.top!=d.height()&&(f.top=d.height(),o=a.utils.availableHeight(h,k,f)),t.select(".nv-legendWrap").attr("transform","translate(0,"+-f.top+")");else if("right"===j){var w=a.models.legend().width();w>n/2&&(w=n/2),d.height(o).key(c.x()),d.width(w),n-=d.width(),t.select(".nv-legendWrap").datum(e).call(d).attr("transform","translate("+n+",0)")}t.attr("transform","translate("+f.left+","+f.top+")"),c.width(n).height(o);var x=v.select(".nv-pieWrap").datum([e]);d3.transition(x).call(c),d.dispatch.on("stateChange",function(a){for(var c in a)l[c]=a[c];p.stateChange(l),b.update()}),p.on("changeState",function(a){"undefined"!=typeof a.disabled&&(e.forEach(function(b,c){b.disabled=a.disabled[c]}),l.disabled=a.disabled),b.update()})}),q.renderEnd("pieChart immediate"),b}var c=a.models.pie(),d=a.models.legend(),e=a.models.tooltip(),f={top:30,right:20,bottom:20,left:20},g=null,h=null,i=!0,j="top",k=a.utils.defaultColor(),l=a.utils.state(),m=null,n=null,o=250,p=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd");e.headerEnabled(!1).duration(0).valueFormatter(function(a,b){return c.valueFormat()(a,b)});var q=a.utils.renderWatch(p),r=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},s=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:b.x()(a.data),value:b.y()(a.data),color:a.color},e.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(){e.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(){e.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.legend=d,b.dispatch=p,b.pie=c,b.tooltip=e,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{noData:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return i},set:function(a){i=a}},legendPosition:{get:function(){return j},set:function(a){j=a}},defaultState:{get:function(){return m},set:function(a){m=a}},tooltips:{get:function(){return e.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),e.enabled(!!b)}},tooltipContent:{get:function(){return e.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),e.contentGenerator(b)}},color:{get:function(){return k},set:function(a){k=a,d.color(k),c.color(k)}},duration:{get:function(){return o},set:function(a){o=a,q.reset(o)}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.scatter=function(){"use strict";function b(N){return P.reset(),N.each(function(b){function N(){if(O=!1,!w)return!1;if(M===!0){var a=d3.merge(b.map(function(a,b){return a.values.map(function(a,c){var d=p(a,c),e=q(a,c);return[m(d)+1e-4*Math.random(),n(e)+1e-4*Math.random(),b,c,a]}).filter(function(a,b){return x(a[4],b)})}));if(0==a.length)return!1;a.length<3&&(a.push([m.range()[0]-20,n.range()[0]-20,null,null]),a.push([m.range()[1]+20,n.range()[1]+20,null,null]),a.push([m.range()[0]-20,n.range()[0]+20,null,null]),a.push([m.range()[1]+20,n.range()[1]-20,null,null]));var c=d3.geom.polygon([[-10,-10],[-10,i+10],[h+10,i+10],[h+10,-10]]),d=d3.geom.voronoi(a).map(function(b,d){return{data:c.clip(b),series:a[d][2],point:a[d][3]}});U.select(".nv-point-paths").selectAll("path").remove();var e=U.select(".nv-point-paths").selectAll("path").data(d),f=e.enter().append("svg:path").attr("d",function(a){return a&&a.data&&0!==a.data.length?"M"+a.data.join(",")+"Z":"M 0 0"}).attr("id",function(a,b){return"nv-path-"+b}).attr("clip-path",function(a,b){return"url(#nv-clip-"+b+")"});C&&f.style("fill",d3.rgb(230,230,230)).style("fill-opacity",.4).style("stroke-opacity",1).style("stroke",d3.rgb(200,200,200)),B&&(U.select(".nv-point-clips").selectAll("clipPath").remove(),U.select(".nv-point-clips").selectAll("clipPath").data(a).enter().append("svg:clipPath").attr("id",function(a,b){return"nv-clip-"+b}).append("svg:circle").attr("cx",function(a){return a[0]}).attr("cy",function(a){return a[1]}).attr("r",D));var k=function(a,c){if(O)return 0;var d=b[a.series];if(void 0!==d){var e=d.values[a.point];e.color=j(d,a.series),e.x=p(e),e.y=q(e);var f=l.node().getBoundingClientRect(),h=window.pageYOffset||document.documentElement.scrollTop,i=window.pageXOffset||document.documentElement.scrollLeft,k={left:m(p(e,a.point))+f.left+i+g.left+10,top:n(q(e,a.point))+f.top+h+g.top+10};c({point:e,series:d,pos:k,seriesIndex:a.series,pointIndex:a.point})}};e.on("click",function(a){k(a,L.elementClick)}).on("dblclick",function(a){k(a,L.elementDblClick)}).on("mouseover",function(a){k(a,L.elementMouseover)}).on("mouseout",function(a){k(a,L.elementMouseout)})}else U.select(".nv-groups").selectAll(".nv-group").selectAll(".nv-point").on("click",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementClick({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c})}).on("dblclick",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementDblClick({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c})}).on("mouseover",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementMouseover({point:e,series:d,pos:[m(p(e,c))+g.left,n(q(e,c))+g.top],seriesIndex:a.series,pointIndex:c,color:j(a,c)})}).on("mouseout",function(a,c){if(O||!b[a.series])return 0;var d=b[a.series],e=d.values[c];L.elementMouseout({point:e,series:d,seriesIndex:a.series,pointIndex:c,color:j(a,c)})})}l=d3.select(this);var R=a.utils.availableWidth(h,l,g),S=a.utils.availableHeight(i,l,g);a.utils.initSVG(l),b.forEach(function(a,b){a.values.forEach(function(a){a.series=b})});var T=E&&F&&I?[]:d3.merge(b.map(function(a){return a.values.map(function(a,b){return{x:p(a,b),y:q(a,b),size:r(a,b)}})}));m.domain(E||d3.extent(T.map(function(a){return a.x}).concat(t))),m.range(y&&b[0]?G||[(R*z+R)/(2*b[0].values.length),R-R*(1+z)/(2*b[0].values.length)]:G||[0,R]),n.domain(F||d3.extent(T.map(function(a){return a.y}).concat(u))).range(H||[S,0]),o.domain(I||d3.extent(T.map(function(a){return a.size}).concat(v))).range(J||Q),K=m.domain()[0]===m.domain()[1]||n.domain()[0]===n.domain()[1],m.domain()[0]===m.domain()[1]&&m.domain(m.domain()[0]?[m.domain()[0]-.01*m.domain()[0],m.domain()[1]+.01*m.domain()[1]]:[-1,1]),n.domain()[0]===n.domain()[1]&&n.domain(n.domain()[0]?[n.domain()[0]-.01*n.domain()[0],n.domain()[1]+.01*n.domain()[1]]:[-1,1]),isNaN(m.domain()[0])&&m.domain([-1,1]),isNaN(n.domain()[0])&&n.domain([-1,1]),c=c||m,d=d||n,e=e||o;var U=l.selectAll("g.nv-wrap.nv-scatter").data([b]),V=U.enter().append("g").attr("class","nvd3 nv-wrap nv-scatter nv-chart-"+k),W=V.append("defs"),X=V.append("g"),Y=U.select("g");U.classed("nv-single-point",K),X.append("g").attr("class","nv-groups"),X.append("g").attr("class","nv-point-paths"),V.append("g").attr("class","nv-point-clips"),U.attr("transform","translate("+g.left+","+g.top+")"),W.append("clipPath").attr("id","nv-edge-clip-"+k).append("rect"),U.select("#nv-edge-clip-"+k+" rect").attr("width",R).attr("height",S>0?S:0),Y.attr("clip-path",A?"url(#nv-edge-clip-"+k+")":""),O=!0;var Z=U.select(".nv-groups").selectAll(".nv-group").data(function(a){return a},function(a){return a.key});Z.enter().append("g").style("stroke-opacity",1e-6).style("fill-opacity",1e-6),Z.exit().remove(),Z.attr("class",function(a,b){return"nv-group nv-series-"+b}).classed("hover",function(a){return a.hover}),Z.watchTransition(P,"scatter: groups").style("fill",function(a,b){return j(a,b)}).style("stroke",function(a,b){return j(a,b)}).style("stroke-opacity",1).style("fill-opacity",.5);var $=Z.selectAll("path.nv-point").data(function(a){return a.values.map(function(a,b){return[a,b]}).filter(function(a,b){return x(a[0],b)})});$.enter().append("path").style("fill",function(a){return a.color}).style("stroke",function(a){return a.color}).attr("transform",function(a){return"translate("+c(p(a[0],a[1]))+","+d(q(a[0],a[1]))+")"}).attr("d",a.utils.symbol().type(function(a){return s(a[0])}).size(function(a){return o(r(a[0],a[1]))})),$.exit().remove(),Z.exit().selectAll("path.nv-point").watchTransition(P,"scatter exit").attr("transform",function(a){return"translate("+m(p(a[0],a[1]))+","+n(q(a[0],a[1]))+")"}).remove(),$.each(function(a){d3.select(this).classed("nv-point",!0).classed("nv-point-"+a[1],!0).classed("nv-noninteractive",!w).classed("hover",!1)}),$.watchTransition(P,"scatter points").attr("transform",function(a){return"translate("+m(p(a[0],a[1]))+","+n(q(a[0],a[1]))+")"}).attr("d",a.utils.symbol().type(function(a){return s(a[0])}).size(function(a){return o(r(a[0],a[1]))})),clearTimeout(f),f=setTimeout(N,300),c=m.copy(),d=n.copy(),e=o.copy()}),P.renderEnd("scatter immediate"),b}var c,d,e,f,g={top:0,right:0,bottom:0,left:0},h=null,i=null,j=a.utils.defaultColor(),k=Math.floor(1e5*Math.random()),l=null,m=d3.scale.linear(),n=d3.scale.linear(),o=d3.scale.linear(),p=function(a){return a.x},q=function(a){return a.y},r=function(a){return a.size||1},s=function(a){return a.shape||"circle"},t=[],u=[],v=[],w=!0,x=function(a){return!a.notActive},y=!1,z=.1,A=!1,B=!0,C=!1,D=function(){return 25},E=null,F=null,G=null,H=null,I=null,J=null,K=!1,L=d3.dispatch("elementClick","elementDblClick","elementMouseover","elementMouseout","renderEnd"),M=!0,N=250,O=!1,P=a.utils.renderWatch(L,N),Q=[16,256];return b.dispatch=L,b.options=a.utils.optionsFunc.bind(b),b._calls=new function(){this.clearHighlights=function(){return a.dom.write(function(){l.selectAll(".nv-point.hover").classed("hover",!1)}),null},this.highlightPoint=function(b,c,d){a.dom.write(function(){l.select(" .nv-series-"+b+" .nv-point-"+c).classed("hover",d)})}},L.on("elementMouseover.point",function(a){w&&b._calls.highlightPoint(a.seriesIndex,a.pointIndex,!0)}),L.on("elementMouseout.point",function(a){w&&b._calls.highlightPoint(a.seriesIndex,a.pointIndex,!1)}),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xScale:{get:function(){return m},set:function(a){m=a}},yScale:{get:function(){return n},set:function(a){n=a}},pointScale:{get:function(){return o},set:function(a){o=a}},xDomain:{get:function(){return E},set:function(a){E=a}},yDomain:{get:function(){return F},set:function(a){F=a}},pointDomain:{get:function(){return I},set:function(a){I=a}},xRange:{get:function(){return G},set:function(a){G=a}},yRange:{get:function(){return H},set:function(a){H=a}},pointRange:{get:function(){return J},set:function(a){J=a}},forceX:{get:function(){return t},set:function(a){t=a}},forceY:{get:function(){return u},set:function(a){u=a}},forcePoint:{get:function(){return v},set:function(a){v=a}},interactive:{get:function(){return w},set:function(a){w=a}},pointActive:{get:function(){return x},set:function(a){x=a}},padDataOuter:{get:function(){return z},set:function(a){z=a}},padData:{get:function(){return y},set:function(a){y=a}},clipEdge:{get:function(){return A},set:function(a){A=a}},clipVoronoi:{get:function(){return B},set:function(a){B=a}},clipRadius:{get:function(){return D},set:function(a){D=a}},showVoronoi:{get:function(){return C},set:function(a){C=a}},id:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return p},set:function(a){p=d3.functor(a)}},y:{get:function(){return q},set:function(a){q=d3.functor(a)}},pointSize:{get:function(){return r},set:function(a){r=d3.functor(a)}},pointShape:{get:function(){return s},set:function(a){s=d3.functor(a)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},duration:{get:function(){return N},set:function(a){N=a,P.reset(N)}},color:{get:function(){return j},set:function(b){j=a.utils.getColor(b)}},useVoronoi:{get:function(){return M},set:function(a){M=a,M===!1&&(B=!1)}}}),a.utils.initOptions(b),b},a.models.scatterChart=function(){"use strict";function b(z){return D.reset(),D.models(c),t&&D.models(d),u&&D.models(e),q&&D.models(g),r&&D.models(h),z.each(function(z){m=d3.select(this),a.utils.initSVG(m);var G=a.utils.availableWidth(k,m,j),H=a.utils.availableHeight(l,m,j);if(b.update=function(){0===A?m.call(b):m.transition().duration(A).call(b)},b.container=this,w.setter(F(z),b.update).getter(E(z)).update(),w.disabled=z.map(function(a){return!!a.disabled}),!x){var I;x={};for(I in w)x[I]=w[I]instanceof Array?w[I].slice(0):w[I]}if(!(z&&z.length&&z.filter(function(a){return a.values.length}).length))return a.utils.noData(b,m),D.renderEnd("scatter immediate"),b;m.selectAll(".nv-noData").remove(),o=c.xScale(),p=c.yScale();var J=m.selectAll("g.nv-wrap.nv-scatterChart").data([z]),K=J.enter().append("g").attr("class","nvd3 nv-wrap nv-scatterChart nv-chart-"+c.id()),L=K.append("g"),M=J.select("g");if(L.append("rect").attr("class","nvd3 nv-background").style("pointer-events","none"),L.append("g").attr("class","nv-x nv-axis"),L.append("g").attr("class","nv-y nv-axis"),L.append("g").attr("class","nv-scatterWrap"),L.append("g").attr("class","nv-regressionLinesWrap"),L.append("g").attr("class","nv-distWrap"),L.append("g").attr("class","nv-legendWrap"),v&&M.select(".nv-y.nv-axis").attr("transform","translate("+G+",0)"),s){var N=G;f.width(N),J.select(".nv-legendWrap").datum(z).call(f),j.top!=f.height()&&(j.top=f.height(),H=a.utils.availableHeight(l,m,j)),J.select(".nv-legendWrap").attr("transform","translate(0,"+-j.top+")")}J.attr("transform","translate("+j.left+","+j.top+")"),c.width(G).height(H).color(z.map(function(a,b){return a.color=a.color||n(a,b),a.color}).filter(function(a,b){return!z[b].disabled})),J.select(".nv-scatterWrap").datum(z.filter(function(a){return!a.disabled})).call(c),J.select(".nv-regressionLinesWrap").attr("clip-path","url(#nv-edge-clip-"+c.id()+")");var O=J.select(".nv-regressionLinesWrap").selectAll(".nv-regLines").data(function(a){return a});O.enter().append("g").attr("class","nv-regLines");var P=O.selectAll(".nv-regLine").data(function(a){return[a]});P.enter().append("line").attr("class","nv-regLine").style("stroke-opacity",0),P.filter(function(a){return a.intercept&&a.slope}).watchTransition(D,"scatterPlusLineChart: regline").attr("x1",o.range()[0]).attr("x2",o.range()[1]).attr("y1",function(a){return p(o.domain()[0]*a.slope+a.intercept)}).attr("y2",function(a){return p(o.domain()[1]*a.slope+a.intercept)}).style("stroke",function(a,b,c){return n(a,c)}).style("stroke-opacity",function(a){return a.disabled||"undefined"==typeof a.slope||"undefined"==typeof a.intercept?0:1}),t&&(d.scale(o)._ticks(a.utils.calcTicksX(G/100,z)).tickSize(-H,0),M.select(".nv-x.nv-axis").attr("transform","translate(0,"+p.range()[0]+")").call(d)),u&&(e.scale(p)._ticks(a.utils.calcTicksY(H/36,z)).tickSize(-G,0),M.select(".nv-y.nv-axis").call(e)),q&&(g.getData(c.x()).scale(o).width(G).color(z.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!z[b].disabled})),L.select(".nv-distWrap").append("g").attr("class","nv-distributionX"),M.select(".nv-distributionX").attr("transform","translate(0,"+p.range()[0]+")").datum(z.filter(function(a){return!a.disabled})).call(g)),r&&(h.getData(c.y()).scale(p).width(H).color(z.map(function(a,b){return a.color||n(a,b)}).filter(function(a,b){return!z[b].disabled})),L.select(".nv-distWrap").append("g").attr("class","nv-distributionY"),M.select(".nv-distributionY").attr("transform","translate("+(v?G:-h.size())+",0)").datum(z.filter(function(a){return!a.disabled})).call(h)),f.dispatch.on("stateChange",function(a){for(var c in a)w[c]=a[c];y.stateChange(w),b.update()}),y.on("changeState",function(a){"undefined"!=typeof a.disabled&&(z.forEach(function(b,c){b.disabled=a.disabled[c]}),w.disabled=a.disabled),b.update()}),c.dispatch.on("elementMouseout.tooltip",function(a){i.hidden(!0),m.select(".nv-chart-"+c.id()+" .nv-series-"+a.seriesIndex+" .nv-distx-"+a.pointIndex).attr("y1",0),m.select(".nv-chart-"+c.id()+" .nv-series-"+a.seriesIndex+" .nv-disty-"+a.pointIndex).attr("x2",h.size())}),c.dispatch.on("elementMouseover.tooltip",function(a){m.select(".nv-series-"+a.seriesIndex+" .nv-distx-"+a.pointIndex).attr("y1",a.pos.top-H-j.top),m.select(".nv-series-"+a.seriesIndex+" .nv-disty-"+a.pointIndex).attr("x2",a.pos.left+g.size()-j.left),i.position(a.pos).data(a).hidden(!1)}),B=o.copy(),C=p.copy()}),D.renderEnd("scatter with line immediate"),b}var c=a.models.scatter(),d=a.models.axis(),e=a.models.axis(),f=a.models.legend(),g=a.models.distribution(),h=a.models.distribution(),i=a.models.tooltip(),j={top:30,right:20,bottom:50,left:75},k=null,l=null,m=null,n=a.utils.defaultColor(),o=c.xScale(),p=c.yScale(),q=!1,r=!1,s=!0,t=!0,u=!0,v=!1,w=a.utils.state(),x=null,y=d3.dispatch("stateChange","changeState","renderEnd"),z=null,A=250;c.xScale(o).yScale(p),d.orient("bottom").tickPadding(10),e.orient(v?"right":"left").tickPadding(10),g.axis("x"),h.axis("y"),i.headerFormatter(function(a,b){return d.tickFormat()(a,b)}).valueFormatter(function(a,b){return e.tickFormat()(a,b)});var B,C,D=a.utils.renderWatch(y,A),E=function(a){return function(){return{active:a.map(function(a){return!a.disabled})}}},F=function(a){return function(b){void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}};return b.dispatch=y,b.scatter=c,b.legend=f,b.xAxis=d,b.yAxis=e,b.distX=g,b.distY=h,b.tooltip=i,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return k},set:function(a){k=a}},height:{get:function(){return l},set:function(a){l=a}},container:{get:function(){return m},set:function(a){m=a}},showDistX:{get:function(){return q},set:function(a){q=a}},showDistY:{get:function(){return r},set:function(a){r=a}},showLegend:{get:function(){return s},set:function(a){s=a}},showXAxis:{get:function(){return t},set:function(a){t=a}},showYAxis:{get:function(){return u},set:function(a){u=a}},defaultState:{get:function(){return x},set:function(a){x=a}},noData:{get:function(){return z},set:function(a){z=a}},duration:{get:function(){return A},set:function(a){A=a}},tooltips:{get:function(){return i.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),i.enabled(!!b)
}},tooltipContent:{get:function(){return i.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),i.contentGenerator(b)}},tooltipXContent:{get:function(){return i.contentGenerator()},set:function(){a.deprecated("tooltipContent","This option is removed, put values into main tooltip.")}},tooltipYContent:{get:function(){return i.contentGenerator()},set:function(){a.deprecated("tooltipContent","This option is removed, put values into main tooltip.")}},margin:{get:function(){return j},set:function(a){j.top=void 0!==a.top?a.top:j.top,j.right=void 0!==a.right?a.right:j.right,j.bottom=void 0!==a.bottom?a.bottom:j.bottom,j.left=void 0!==a.left?a.left:j.left}},rightAlignYAxis:{get:function(){return v},set:function(a){v=a,e.orient(a?"right":"left")}},color:{get:function(){return n},set:function(b){n=a.utils.getColor(b),f.color(n),g.color(n),h.color(n)}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.models.sparkline=function(){"use strict";function b(k){return k.each(function(b){var k=h-g.left-g.right,q=i-g.top-g.bottom;j=d3.select(this),a.utils.initSVG(j),l.domain(c||d3.extent(b,n)).range(e||[0,k]),m.domain(d||d3.extent(b,o)).range(f||[q,0]);{var r=j.selectAll("g.nv-wrap.nv-sparkline").data([b]),s=r.enter().append("g").attr("class","nvd3 nv-wrap nv-sparkline");s.append("g"),r.select("g")}r.attr("transform","translate("+g.left+","+g.top+")");var t=r.selectAll("path").data(function(a){return[a]});t.enter().append("path"),t.exit().remove(),t.style("stroke",function(a,b){return a.color||p(a,b)}).attr("d",d3.svg.line().x(function(a,b){return l(n(a,b))}).y(function(a,b){return m(o(a,b))}));var u=r.selectAll("circle.nv-point").data(function(a){function b(b){if(-1!=b){var c=a[b];return c.pointIndex=b,c}return null}var c=a.map(function(a,b){return o(a,b)}),d=b(c.lastIndexOf(m.domain()[1])),e=b(c.indexOf(m.domain()[0])),f=b(c.length-1);return[e,d,f].filter(function(a){return null!=a})});u.enter().append("circle"),u.exit().remove(),u.attr("cx",function(a){return l(n(a,a.pointIndex))}).attr("cy",function(a){return m(o(a,a.pointIndex))}).attr("r",2).attr("class",function(a){return n(a,a.pointIndex)==l.domain()[1]?"nv-point nv-currentValue":o(a,a.pointIndex)==m.domain()[0]?"nv-point nv-minValue":"nv-point nv-maxValue"})}),b}var c,d,e,f,g={top:2,right:0,bottom:2,left:0},h=400,i=32,j=null,k=!0,l=d3.scale.linear(),m=d3.scale.linear(),n=function(a){return a.x},o=function(a){return a.y},p=a.utils.getColor(["#000"]);return b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return h},set:function(a){h=a}},height:{get:function(){return i},set:function(a){i=a}},xDomain:{get:function(){return c},set:function(a){c=a}},yDomain:{get:function(){return d},set:function(a){d=a}},xRange:{get:function(){return e},set:function(a){e=a}},yRange:{get:function(){return f},set:function(a){f=a}},xScale:{get:function(){return l},set:function(a){l=a}},yScale:{get:function(){return m},set:function(a){m=a}},animate:{get:function(){return k},set:function(a){k=a}},x:{get:function(){return n},set:function(a){n=d3.functor(a)}},y:{get:function(){return o},set:function(a){o=d3.functor(a)}},margin:{get:function(){return g},set:function(a){g.top=void 0!==a.top?a.top:g.top,g.right=void 0!==a.right?a.right:g.right,g.bottom=void 0!==a.bottom?a.bottom:g.bottom,g.left=void 0!==a.left?a.left:g.left}},color:{get:function(){return p},set:function(b){p=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.sparklinePlus=function(){"use strict";function b(p){return p.each(function(p){function q(){if(!j){var a=z.selectAll(".nv-hoverValue").data(i),b=a.enter().append("g").attr("class","nv-hoverValue").style("stroke-opacity",0).style("fill-opacity",0);a.exit().transition().duration(250).style("stroke-opacity",0).style("fill-opacity",0).remove(),a.attr("transform",function(a){return"translate("+c(e.x()(p[a],a))+",0)"}).transition().duration(250).style("stroke-opacity",1).style("fill-opacity",1),i.length&&(b.append("line").attr("x1",0).attr("y1",-f.top).attr("x2",0).attr("y2",u),b.append("text").attr("class","nv-xValue").attr("x",-6).attr("y",-f.top).attr("text-anchor","end").attr("dy",".9em"),z.select(".nv-hoverValue .nv-xValue").text(k(e.x()(p[i[0]],i[0]))),b.append("text").attr("class","nv-yValue").attr("x",6).attr("y",-f.top).attr("text-anchor","start").attr("dy",".9em"),z.select(".nv-hoverValue .nv-yValue").text(l(e.y()(p[i[0]],i[0]))))}}function r(){function a(a,b){for(var c=Math.abs(e.x()(a[0],0)-b),d=0,f=0;f<a.length;f++)Math.abs(e.x()(a[f],f)-b)<c&&(c=Math.abs(e.x()(a[f],f)-b),d=f);return d}if(!j){var b=d3.mouse(this)[0]-f.left;i=[a(p,Math.round(c.invert(b)))],q()}}var s=d3.select(this);a.utils.initSVG(s);var t=a.utils.availableWidth(g,s,f),u=a.utils.availableHeight(h,s,f);if(b.update=function(){s.call(b)},b.container=this,!p||!p.length)return a.utils.noData(b,s),b;s.selectAll(".nv-noData").remove();var v=e.y()(p[p.length-1],p.length-1);c=e.xScale(),d=e.yScale();var w=s.selectAll("g.nv-wrap.nv-sparklineplus").data([p]),x=w.enter().append("g").attr("class","nvd3 nv-wrap nv-sparklineplus"),y=x.append("g"),z=w.select("g");y.append("g").attr("class","nv-sparklineWrap"),y.append("g").attr("class","nv-valueWrap"),y.append("g").attr("class","nv-hoverArea"),w.attr("transform","translate("+f.left+","+f.top+")");var A=z.select(".nv-sparklineWrap");if(e.width(t).height(u),A.call(e),m){var B=z.select(".nv-valueWrap"),C=B.selectAll(".nv-currentValue").data([v]);C.enter().append("text").attr("class","nv-currentValue").attr("dx",o?-8:8).attr("dy",".9em").style("text-anchor",o?"end":"start"),C.attr("x",t+(o?f.right:0)).attr("y",n?function(a){return d(a)}:0).style("fill",e.color()(p[p.length-1],p.length-1)).text(l(v))}y.select(".nv-hoverArea").append("rect").on("mousemove",r).on("click",function(){j=!j}).on("mouseout",function(){i=[],q()}),z.select(".nv-hoverArea rect").attr("transform",function(){return"translate("+-f.left+","+-f.top+")"}).attr("width",t+f.left+f.right).attr("height",u+f.top)}),b}var c,d,e=a.models.sparkline(),f={top:15,right:100,bottom:10,left:50},g=null,h=null,i=[],j=!1,k=d3.format(",r"),l=d3.format(",.2f"),m=!0,n=!0,o=!1,p=null;return b.sparkline=e,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},xTickFormat:{get:function(){return k},set:function(a){k=a}},yTickFormat:{get:function(){return l},set:function(a){l=a}},showLastValue:{get:function(){return m},set:function(a){m=a}},alignValue:{get:function(){return n},set:function(a){n=a}},rightAlignValue:{get:function(){return o},set:function(a){o=a}},noData:{get:function(){return p},set:function(a){p=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!==a.top?a.top:f.top,f.right=void 0!==a.right?a.right:f.right,f.bottom=void 0!==a.bottom?a.bottom:f.bottom,f.left=void 0!==a.left?a.left:f.left}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.stackedArea=function(){"use strict";function b(m){return u.reset(),u.models(r),m.each(function(m){var s=f-e.left-e.right,v=g-e.top-e.bottom;j=d3.select(this),a.utils.initSVG(j),c=r.xScale(),d=r.yScale();var w=m;m.forEach(function(a,b){a.seriesIndex=b,a.values=a.values.map(function(a,c){return a.index=c,a.seriesIndex=b,a})});var x=m.filter(function(a){return!a.disabled});m=d3.layout.stack().order(o).offset(n).values(function(a){return a.values}).x(k).y(l).out(function(a,b,c){a.display={y:c,y0:b}})(x);var y=j.selectAll("g.nv-wrap.nv-stackedarea").data([m]),z=y.enter().append("g").attr("class","nvd3 nv-wrap nv-stackedarea"),A=z.append("defs"),B=z.append("g"),C=y.select("g");B.append("g").attr("class","nv-areaWrap"),B.append("g").attr("class","nv-scatterWrap"),y.attr("transform","translate("+e.left+","+e.top+")"),0==r.forceY().length&&r.forceY().push(0),r.width(s).height(v).x(k).y(function(a){return a.display.y+a.display.y0}).forceY([0]).color(m.map(function(a){return a.color||h(a,a.seriesIndex)}));var D=C.select(".nv-scatterWrap").datum(m);D.call(r),A.append("clipPath").attr("id","nv-edge-clip-"+i).append("rect"),y.select("#nv-edge-clip-"+i+" rect").attr("width",s).attr("height",v),C.attr("clip-path",q?"url(#nv-edge-clip-"+i+")":"");var E=d3.svg.area().x(function(a,b){return c(k(a,b))}).y0(function(a){return d(a.display.y0)}).y1(function(a){return d(a.display.y+a.display.y0)}).interpolate(p),F=d3.svg.area().x(function(a,b){return c(k(a,b))}).y0(function(a){return d(a.display.y0)}).y1(function(a){return d(a.display.y0)}),G=C.select(".nv-areaWrap").selectAll("path.nv-area").data(function(a){return a});G.enter().append("path").attr("class",function(a,b){return"nv-area nv-area-"+b}).attr("d",function(a){return F(a.values,a.seriesIndex)}).on("mouseover",function(a){d3.select(this).classed("hover",!0),t.areaMouseover({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}).on("mouseout",function(a){d3.select(this).classed("hover",!1),t.areaMouseout({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}).on("click",function(a){d3.select(this).classed("hover",!1),t.areaClick({point:a,series:a.key,pos:[d3.event.pageX,d3.event.pageY],seriesIndex:a.seriesIndex})}),G.exit().remove(),G.style("fill",function(a){return a.color||h(a,a.seriesIndex)}).style("stroke",function(a){return a.color||h(a,a.seriesIndex)}),G.watchTransition(u,"stackedArea path").attr("d",function(a,b){return E(a.values,b)}),r.dispatch.on("elementMouseover.area",function(a){C.select(".nv-chart-"+i+" .nv-area-"+a.seriesIndex).classed("hover",!0)}),r.dispatch.on("elementMouseout.area",function(a){C.select(".nv-chart-"+i+" .nv-area-"+a.seriesIndex).classed("hover",!1)}),b.d3_stackedOffset_stackPercent=function(a){var b,c,d,e=a.length,f=a[0].length,g=[];for(c=0;f>c;++c){for(b=0,d=0;b<w.length;b++)d+=l(w[b].values[c]);if(d)for(b=0;e>b;b++)a[b][c][1]/=d;else for(b=0;e>b;b++)a[b][c][1]=0}for(c=0;f>c;++c)g[c]=0;return g}}),u.renderEnd("stackedArea immediate"),b}var c,d,e={top:0,right:0,bottom:0,left:0},f=960,g=500,h=a.utils.defaultColor(),i=Math.floor(1e5*Math.random()),j=null,k=function(a){return a.x},l=function(a){return a.y},m="stack",n="zero",o="default",p="linear",q=!1,r=a.models.scatter(),s=250,t=d3.dispatch("areaClick","areaMouseover","areaMouseout","renderEnd","elementClick","elementMouseover","elementMouseout");r.pointSize(2.2).pointDomain([2.2,2.2]);var u=a.utils.renderWatch(t,s);return b.dispatch=t,b.scatter=r,r.dispatch.on("elementClick",function(){t.elementClick.apply(this,arguments)}),r.dispatch.on("elementMouseover",function(){t.elementMouseover.apply(this,arguments)}),r.dispatch.on("elementMouseout",function(){t.elementMouseout.apply(this,arguments)}),b.interpolate=function(a){return arguments.length?(p=a,b):p},b.duration=function(a){return arguments.length?(s=a,u.reset(s),r.duration(s),b):s},b.dispatch=t,b.scatter=r,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return f},set:function(a){f=a}},height:{get:function(){return g},set:function(a){g=a}},clipEdge:{get:function(){return q},set:function(a){q=a}},offset:{get:function(){return n},set:function(a){n=a}},order:{get:function(){return o},set:function(a){o=a}},interpolate:{get:function(){return p},set:function(a){p=a}},x:{get:function(){return k},set:function(a){k=d3.functor(a)}},y:{get:function(){return l},set:function(a){l=d3.functor(a)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}},color:{get:function(){return h},set:function(b){h=a.utils.getColor(b)}},style:{get:function(){return m},set:function(a){switch(m=a){case"stack":b.offset("zero"),b.order("default");break;case"stream":b.offset("wiggle"),b.order("inside-out");break;case"stream-center":b.offset("silhouette"),b.order("inside-out");break;case"expand":b.offset("expand"),b.order("default");break;case"stack_percent":b.offset(b.d3_stackedOffset_stackPercent),b.order("default")}}},duration:{get:function(){return s},set:function(a){s=a,u.reset(s),r.duration(s)}}}),a.utils.inheritOptions(b,r),a.utils.initOptions(b),b},a.models.stackedAreaChart=function(){"use strict";function b(k){return F.reset(),F.models(e),r&&F.models(f),s&&F.models(g),k.each(function(k){var x=d3.select(this),F=this;a.utils.initSVG(x);var K=a.utils.availableWidth(m,x,l),L=a.utils.availableHeight(n,x,l);if(b.update=function(){x.transition().duration(C).call(b)},b.container=this,v.setter(I(k),b.update).getter(H(k)).update(),v.disabled=k.map(function(a){return!!a.disabled}),!w){var M;w={};for(M in v)w[M]=v[M]instanceof Array?v[M].slice(0):v[M]}if(!(k&&k.length&&k.filter(function(a){return a.values.length}).length))return a.utils.noData(b,x),b;x.selectAll(".nv-noData").remove(),c=e.xScale(),d=e.yScale();var N=x.selectAll("g.nv-wrap.nv-stackedAreaChart").data([k]),O=N.enter().append("g").attr("class","nvd3 nv-wrap nv-stackedAreaChart").append("g"),P=N.select("g");if(O.append("rect").style("opacity",0),O.append("g").attr("class","nv-x nv-axis"),O.append("g").attr("class","nv-y nv-axis"),O.append("g").attr("class","nv-stackedWrap"),O.append("g").attr("class","nv-legendWrap"),O.append("g").attr("class","nv-controlsWrap"),O.append("g").attr("class","nv-interactive"),P.select("rect").attr("width",K).attr("height",L),q){var Q=p?K-z:K;h.width(Q),P.select(".nv-legendWrap").datum(k).call(h),l.top!=h.height()&&(l.top=h.height(),L=a.utils.availableHeight(n,x,l)),P.select(".nv-legendWrap").attr("transform","translate("+(K-Q)+","+-l.top+")")}if(p){var R=[{key:B.stacked||"Stacked",metaKey:"Stacked",disabled:"stack"!=e.style(),style:"stack"},{key:B.stream||"Stream",metaKey:"Stream",disabled:"stream"!=e.style(),style:"stream"},{key:B.expanded||"Expanded",metaKey:"Expanded",disabled:"expand"!=e.style(),style:"expand"},{key:B.stack_percent||"Stack %",metaKey:"Stack_Percent",disabled:"stack_percent"!=e.style(),style:"stack_percent"}];z=A.length/3*260,R=R.filter(function(a){return-1!==A.indexOf(a.metaKey)}),i.width(z).color(["#444","#444","#444"]),P.select(".nv-controlsWrap").datum(R).call(i),l.top!=Math.max(i.height(),h.height())&&(l.top=Math.max(i.height(),h.height()),L=a.utils.availableHeight(n,x,l)),P.select(".nv-controlsWrap").attr("transform","translate(0,"+-l.top+")")}N.attr("transform","translate("+l.left+","+l.top+")"),t&&P.select(".nv-y.nv-axis").attr("transform","translate("+K+",0)"),u&&(j.width(K).height(L).margin({left:l.left,top:l.top}).svgContainer(x).xScale(c),N.select(".nv-interactive").call(j)),e.width(K).height(L);var S=P.select(".nv-stackedWrap").datum(k);if(S.transition().call(e),r&&(f.scale(c)._ticks(a.utils.calcTicksX(K/100,k)).tickSize(-L,0),P.select(".nv-x.nv-axis").attr("transform","translate(0,"+L+")"),P.select(".nv-x.nv-axis").transition().duration(0).call(f)),s){var T;if(T="wiggle"===e.offset()?0:a.utils.calcTicksY(L/36,k),g.scale(d)._ticks(T).tickSize(-K,0),"expand"===e.style()||"stack_percent"===e.style()){var U=g.tickFormat();D&&U===J||(D=U),g.tickFormat(J)}else D&&(g.tickFormat(D),D=null);P.select(".nv-y.nv-axis").transition().duration(0).call(g)}e.dispatch.on("areaClick.toggle",function(a){k.forEach(1===k.filter(function(a){return!a.disabled}).length?function(a){a.disabled=!1}:function(b,c){b.disabled=c!=a.seriesIndex}),v.disabled=k.map(function(a){return!!a.disabled}),y.stateChange(v),b.update()}),h.dispatch.on("stateChange",function(a){for(var c in a)v[c]=a[c];y.stateChange(v),b.update()}),i.dispatch.on("legendClick",function(a){a.disabled&&(R=R.map(function(a){return a.disabled=!0,a}),a.disabled=!1,e.style(a.style),v.style=e.style(),y.stateChange(v),b.update())}),j.dispatch.on("elementMousemove",function(c){e.clearHighlights();var d,g,h,i=[];if(k.filter(function(a,b){return a.seriesIndex=b,!a.disabled}).forEach(function(f,j){g=a.interactiveBisect(f.values,c.pointXValue,b.x());var k=f.values[g],l=b.y()(k,g);if(null!=l&&e.highlightPoint(j,g,!0),"undefined"!=typeof k){"undefined"==typeof d&&(d=k),"undefined"==typeof h&&(h=b.xScale()(b.x()(k,g)));var m="expand"==e.style()?k.display.y:b.y()(k,g);i.push({key:f.key,value:m,color:o(f,f.seriesIndex),stackedValue:k.display})}}),i.reverse(),i.length>2){var m=b.yScale().invert(c.mouseY),n=null;i.forEach(function(a,b){m=Math.abs(m);var c=Math.abs(a.stackedValue.y0),d=Math.abs(a.stackedValue.y);return m>=c&&d+c>=m?void(n=b):void 0}),null!=n&&(i[n].highlight=!0)}var p=f.tickFormat()(b.x()(d,g)),q=j.tooltip.valueFormatter();"expand"===e.style()||"stack_percent"===e.style()?(E||(E=q),q=d3.format(".1%")):E&&(q=E,E=null),j.tooltip.position({left:h+l.left,top:c.mouseY+l.top}).chartContainer(F.parentNode).valueFormatter(q).data({value:p,series:i})(),j.renderGuideLine(h)}),j.dispatch.on("elementMouseout",function(){e.clearHighlights()}),y.on("changeState",function(a){"undefined"!=typeof a.disabled&&k.length===a.disabled.length&&(k.forEach(function(b,c){b.disabled=a.disabled[c]}),v.disabled=a.disabled),"undefined"!=typeof a.style&&(e.style(a.style),G=a.style),b.update()})}),F.renderEnd("stacked Area chart immediate"),b}var c,d,e=a.models.stackedArea(),f=a.models.axis(),g=a.models.axis(),h=a.models.legend(),i=a.models.legend(),j=a.interactiveGuideline(),k=a.models.tooltip(),l={top:30,right:25,bottom:50,left:60},m=null,n=null,o=a.utils.defaultColor(),p=!0,q=!0,r=!0,s=!0,t=!1,u=!1,v=a.utils.state(),w=null,x=null,y=d3.dispatch("stateChange","changeState","renderEnd"),z=250,A=["Stacked","Stream","Expanded"],B={},C=250;v.style=e.style(),f.orient("bottom").tickPadding(7),g.orient(t?"right":"left"),k.headerFormatter(function(a,b){return f.tickFormat()(a,b)}).valueFormatter(function(a,b){return g.tickFormat()(a,b)}),j.tooltip.headerFormatter(function(a,b){return f.tickFormat()(a,b)}).valueFormatter(function(a,b){return g.tickFormat()(a,b)});var D=null,E=null;i.updateState(!1);var F=a.utils.renderWatch(y),G=e.style(),H=function(a){return function(){return{active:a.map(function(a){return!a.disabled}),style:e.style()}}},I=function(a){return function(b){void 0!==b.style&&(G=b.style),void 0!==b.active&&a.forEach(function(a,c){a.disabled=!b.active[c]})}},J=d3.format("%");return e.dispatch.on("elementMouseover.tooltip",function(a){a.point.x=e.x()(a.point),a.point.y=e.y()(a.point),k.data(a).position(a.pos).hidden(!1)}),e.dispatch.on("elementMouseout.tooltip",function(){k.hidden(!0)}),b.dispatch=y,b.stacked=e,b.legend=h,b.controls=i,b.xAxis=f,b.yAxis=g,b.interactiveLayer=j,b.tooltip=k,b.dispatch=y,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return m},set:function(a){m=a}},height:{get:function(){return n},set:function(a){n=a}},showLegend:{get:function(){return q},set:function(a){q=a}},showXAxis:{get:function(){return r},set:function(a){r=a}},showYAxis:{get:function(){return s},set:function(a){s=a}},defaultState:{get:function(){return w},set:function(a){w=a}},noData:{get:function(){return x},set:function(a){x=a}},showControls:{get:function(){return p},set:function(a){p=a}},controlLabels:{get:function(){return B},set:function(a){B=a}},controlOptions:{get:function(){return A},set:function(a){A=a}},tooltips:{get:function(){return k.enabled()},set:function(b){a.deprecated("tooltips","use chart.tooltip.enabled() instead"),k.enabled(!!b)}},tooltipContent:{get:function(){return k.contentGenerator()},set:function(b){a.deprecated("tooltipContent","use chart.tooltip.contentGenerator() instead"),k.contentGenerator(b)}},margin:{get:function(){return l},set:function(a){l.top=void 0!==a.top?a.top:l.top,l.right=void 0!==a.right?a.right:l.right,l.bottom=void 0!==a.bottom?a.bottom:l.bottom,l.left=void 0!==a.left?a.left:l.left}},duration:{get:function(){return C},set:function(a){C=a,F.reset(C),e.duration(C),f.duration(C),g.duration(C)}},color:{get:function(){return o},set:function(b){o=a.utils.getColor(b),h.color(o),e.color(o)}},rightAlignYAxis:{get:function(){return t},set:function(a){t=a,g.orient(t?"right":"left")}},useInteractiveGuideline:{get:function(){return u},set:function(a){u=!!a,b.interactive(!a),b.useVoronoi(!a),e.scatter.interactive(!a)}}}),a.utils.inheritOptions(b,e),a.utils.initOptions(b),b},a.models.sunburst=function(){"use strict";function b(u){return t.reset(),u.each(function(b){function t(a){a.x0=a.x,a.dx0=a.dx}function u(a){var b=d3.interpolate(p.domain(),[a.x,a.x+a.dx]),c=d3.interpolate(q.domain(),[a.y,1]),d=d3.interpolate(q.range(),[a.y?20:0,y]);return function(a,e){return e?function(){return s(a)}:function(e){return p.domain(b(e)),q.domain(c(e)).range(d(e)),s(a)}}}l=d3.select(this);var v,w=a.utils.availableWidth(g,l,f),x=a.utils.availableHeight(h,l,f),y=Math.min(w,x)/2;a.utils.initSVG(l);var z=l.selectAll(".nv-wrap.nv-sunburst").data(b),A=z.enter().append("g").attr("class","nvd3 nv-wrap nv-sunburst nv-chart-"+k),B=A.selectAll("nv-sunburst");z.attr("transform","translate("+w/2+","+x/2+")"),l.on("click",function(a,b){o.chartClick({data:a,index:b,pos:d3.event,id:k})}),q.range([0,y]),c=c||b,e=b[0],r.value(j[i]||j.count),v=B.data(r.nodes).enter().append("path").attr("d",s).style("fill",function(a){return m((a.children?a:a.parent).name)}).style("stroke","#FFF").on("click",function(a){d!==c&&c!==a&&(d=c),c=a,v.transition().duration(n).attrTween("d",u(a))}).each(t).on("dblclick",function(a){d.parent==a&&v.transition().duration(n).attrTween("d",u(e))}).each(t).on("mouseover",function(a){d3.select(this).classed("hover",!0).style("opacity",.8),o.elementMouseover({data:a,color:d3.select(this).style("fill")})}).on("mouseout",function(a){d3.select(this).classed("hover",!1).style("opacity",1),o.elementMouseout({data:a})}).on("mousemove",function(a){o.elementMousemove({data:a})})}),t.renderEnd("sunburst immediate"),b}var c,d,e,f={top:0,right:0,bottom:0,left:0},g=null,h=null,i="count",j={count:function(){return 1},size:function(a){return a.size}},k=Math.floor(1e4*Math.random()),l=null,m=a.utils.defaultColor(),n=500,o=d3.dispatch("chartClick","elementClick","elementDblClick","elementMousemove","elementMouseover","elementMouseout","renderEnd"),p=d3.scale.linear().range([0,2*Math.PI]),q=d3.scale.sqrt(),r=d3.layout.partition().sort(null).value(function(){return 1}),s=d3.svg.arc().startAngle(function(a){return Math.max(0,Math.min(2*Math.PI,p(a.x)))}).endAngle(function(a){return Math.max(0,Math.min(2*Math.PI,p(a.x+a.dx)))}).innerRadius(function(a){return Math.max(0,q(a.y))}).outerRadius(function(a){return Math.max(0,q(a.y+a.dy))}),t=a.utils.renderWatch(o);return b.dispatch=o,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{width:{get:function(){return g},set:function(a){g=a}},height:{get:function(){return h},set:function(a){h=a}},mode:{get:function(){return i},set:function(a){i=a}},id:{get:function(){return k},set:function(a){k=a}},duration:{get:function(){return n},set:function(a){n=a}},margin:{get:function(){return f},set:function(a){f.top=void 0!=a.top?a.top:f.top,f.right=void 0!=a.right?a.right:f.right,f.bottom=void 0!=a.bottom?a.bottom:f.bottom,f.left=void 0!=a.left?a.left:f.left}},color:{get:function(){return m},set:function(b){m=a.utils.getColor(b)}}}),a.utils.initOptions(b),b},a.models.sunburstChart=function(){"use strict";function b(d){return m.reset(),m.models(c),d.each(function(d){var h=d3.select(this);a.utils.initSVG(h);var i=a.utils.availableWidth(f,h,e),j=a.utils.availableHeight(g,h,e);if(b.update=function(){0===k?h.call(b):h.transition().duration(k).call(b)},b.container=this,!d||!d.length)return a.utils.noData(b,h),b;h.selectAll(".nv-noData").remove();var l=h.selectAll("g.nv-wrap.nv-sunburstChart").data(d),m=l.enter().append("g").attr("class","nvd3 nv-wrap nv-sunburstChart").append("g"),n=l.select("g");m.append("g").attr("class","nv-sunburstWrap"),l.attr("transform","translate("+e.left+","+e.top+")"),c.width(i).height(j);var o=n.select(".nv-sunburstWrap").datum(d);d3.transition(o).call(c)}),m.renderEnd("sunburstChart immediate"),b}var c=a.models.sunburst(),d=a.models.tooltip(),e={top:30,right:20,bottom:20,left:20},f=null,g=null,h=a.utils.defaultColor(),i=(Math.round(1e5*Math.random()),null),j=null,k=250,l=d3.dispatch("tooltipShow","tooltipHide","stateChange","changeState","renderEnd"),m=a.utils.renderWatch(l);return d.headerEnabled(!1).duration(0).valueFormatter(function(a){return a}),c.dispatch.on("elementMouseover.tooltip",function(a){a.series={key:a.data.name,value:a.data.size,color:a.color},d.data(a).hidden(!1)}),c.dispatch.on("elementMouseout.tooltip",function(){d.hidden(!0)}),c.dispatch.on("elementMousemove.tooltip",function(){d.position({top:d3.event.pageY,left:d3.event.pageX})()}),b.dispatch=l,b.sunburst=c,b.tooltip=d,b.options=a.utils.optionsFunc.bind(b),b._options=Object.create({},{noData:{get:function(){return j},set:function(a){j=a}},defaultState:{get:function(){return i},set:function(a){i=a}},color:{get:function(){return h},set:function(a){h=a,c.color(h)}},duration:{get:function(){return k},set:function(a){k=a,m.reset(k),c.duration(k)}},margin:{get:function(){return e},set:function(a){e.top=void 0!==a.top?a.top:e.top,e.right=void 0!==a.right?a.right:e.right,e.bottom=void 0!==a.bottom?a.bottom:e.bottom,e.left=void 0!==a.left?a.left:e.left}}}),a.utils.inheritOptions(b,c),a.utils.initOptions(b),b},a.version="1.8.1"}();!function(){function n(n){return n&&(n.ownerDocument||n.document||n).documentElement}function t(n){return n&&(n.ownerDocument&&n.ownerDocument.defaultView||n.document&&n||n.defaultView)}function e(n,t){return t>n?-1:n>t?1:n>=t?0:NaN}function r(n){return null===n?NaN:+n}function i(n){return!isNaN(n)}function u(n){return{left:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)<0?r=u+1:i=u}return r},right:function(t,e,r,i){for(arguments.length<3&&(r=0),arguments.length<4&&(i=t.length);i>r;){var u=r+i>>>1;n(t[u],e)>0?i=u:r=u+1}return r}}}function o(n){return n.length}function a(n){for(var t=1;n*t%1;)t*=10;return t}function l(n,t){for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}function c(){this._=Object.create(null)}function f(n){return(n+="")===bo||n[0]===_o?_o+n:n}function s(n){return(n+="")[0]===_o?n.slice(1):n}function h(n){return f(n)in this._}function p(n){return(n=f(n))in this._&&delete this._[n]}function g(){var n=[];for(var t in this._)n.push(s(t));return n}function v(){var n=0;for(var t in this._)++n;return n}function d(){for(var n in this._)return!1;return!0}function y(){this._=Object.create(null)}function m(n){return n}function M(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function x(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e=0,r=wo.length;r>e;++e){var i=wo[e]+t;if(i in n)return i}}function b(){}function _(){}function w(n){function t(){for(var t,r=e,i=-1,u=r.length;++i<u;)(t=r[i].on)&&t.apply(this,arguments);return n}var e=[],r=new c;return t.on=function(t,i){var u,o=r.get(t);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,u=e.indexOf(o)).concat(e.slice(u+1)),r.remove(t)),i&&e.push(r.set(t,{on:i})),n)},t}function S(){ao.event.preventDefault()}function k(){for(var n,t=ao.event;n=t.sourceEvent;)t=n;return t}function N(n){for(var t=new _,e=0,r=arguments.length;++e<r;)t[arguments[e]]=w(t);return t.of=function(e,r){return function(i){try{var u=i.sourceEvent=ao.event;i.target=n,ao.event=i,t[i.type].apply(e,r)}finally{ao.event=u}}},t}function E(n){return ko(n,Co),n}function A(n){return"function"==typeof n?n:function(){return No(n,this)}}function C(n){return"function"==typeof n?n:function(){return Eo(n,this)}}function z(n,t){function e(){this.removeAttribute(n)}function r(){this.removeAttributeNS(n.space,n.local)}function i(){this.setAttribute(n,t)}function u(){this.setAttributeNS(n.space,n.local,t)}function o(){var e=t.apply(this,arguments);null==e?this.removeAttribute(n):this.setAttribute(n,e)}function a(){var e=t.apply(this,arguments);null==e?this.removeAttributeNS(n.space,n.local):this.setAttributeNS(n.space,n.local,e)}return n=ao.ns.qualify(n),null==t?n.local?r:e:"function"==typeof t?n.local?a:o:n.local?u:i}function L(n){return n.trim().replace(/\s+/g," ")}function q(n){return new RegExp("(?:^|\\s+)"+ao.requote(n)+"(?:\\s+|$)","g")}function T(n){return(n+"").trim().split(/^|\s+/)}function R(n,t){function e(){for(var e=-1;++e<i;)n[e](this,t)}function r(){for(var e=-1,r=t.apply(this,arguments);++e<i;)n[e](this,r)}n=T(n).map(D);var i=n.length;return"function"==typeof t?r:e}function D(n){var t=q(n);return function(e,r){if(i=e.classList)return r?i.add(n):i.remove(n);var i=e.getAttribute("class")||"";r?(t.lastIndex=0,t.test(i)||e.setAttribute("class",L(i+" "+n))):e.setAttribute("class",L(i.replace(t," ")))}}function P(n,t,e){function r(){this.style.removeProperty(n)}function i(){this.style.setProperty(n,t,e)}function u(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(n):this.style.setProperty(n,r,e)}return null==t?r:"function"==typeof t?u:i}function U(n,t){function e(){delete this[n]}function r(){this[n]=t}function i(){var e=t.apply(this,arguments);null==e?delete this[n]:this[n]=e}return null==t?e:"function"==typeof t?i:r}function j(n){function t(){var t=this.ownerDocument,e=this.namespaceURI;return e===zo&&t.documentElement.namespaceURI===zo?t.createElement(n):t.createElementNS(e,n)}function e(){return this.ownerDocument.createElementNS(n.space,n.local)}return"function"==typeof n?n:(n=ao.ns.qualify(n)).local?e:t}function F(){var n=this.parentNode;n&&n.removeChild(this)}function H(n){return{__data__:n}}function O(n){return function(){return Ao(this,n)}}function I(n){return arguments.length||(n=e),function(t,e){return t&&e?n(t.__data__,e.__data__):!t-!e}}function Y(n,t){for(var e=0,r=n.length;r>e;e++)for(var i,u=n[e],o=0,a=u.length;a>o;o++)(i=u[o])&&t(i,o,e);return n}function Z(n){return ko(n,qo),n}function V(n){var t,e;return function(r,i,u){var o,a=n[u].update,l=a.length;for(u!=e&&(e=u,t=0),i>=t&&(t=i+1);!(o=a[t])&&++t<l;);return o}}function X(n,t,e){function r(){var t=this[o];t&&(this.removeEventListener(n,t,t.$),delete this[o])}function i(){var i=l(t,co(arguments));r.call(this),this.addEventListener(n,this[o]=i,i.$=e),i._=t}function u(){var t,e=new RegExp("^__on([^.]+)"+ao.requote(n)+"$");for(var r in this)if(t=r.match(e)){var i=this[r];this.removeEventListener(t[1],i,i.$),delete this[r]}}var o="__on"+n,a=n.indexOf("."),l=$;a>0&&(n=n.slice(0,a));var c=To.get(n);return c&&(n=c,l=B),a?t?i:r:t?b:u}function $(n,t){return function(e){var r=ao.event;ao.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{ao.event=r}}}function B(n,t){var e=$(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function W(e){var r=".dragsuppress-"+ ++Do,i="click"+r,u=ao.select(t(e)).on("touchmove"+r,S).on("dragstart"+r,S).on("selectstart"+r,S);if(null==Ro&&(Ro="onselectstart"in e?!1:x(e.style,"userSelect")),Ro){var o=n(e).style,a=o[Ro];o[Ro]="none"}return function(n){if(u.on(r,null),Ro&&(o[Ro]=a),n){var t=function(){u.on(i,null)};u.on(i,function(){S(),t()},!0),setTimeout(t,0)}}}function J(n,e){e.changedTouches&&(e=e.changedTouches[0]);var r=n.ownerSVGElement||n;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Po){var u=t(n);if(u.scrollX||u.scrollY){r=ao.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Po=!(o.f||o.e),r.remove()}}return Po?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(n.getScreenCTM().inverse()),[i.x,i.y]}var a=n.getBoundingClientRect();return[e.clientX-a.left-n.clientLeft,e.clientY-a.top-n.clientTop]}function G(){return ao.event.changedTouches[0].identifier}function K(n){return n>0?1:0>n?-1:0}function Q(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function nn(n){return n>1?0:-1>n?Fo:Math.acos(n)}function tn(n){return n>1?Io:-1>n?-Io:Math.asin(n)}function en(n){return((n=Math.exp(n))-1/n)/2}function rn(n){return((n=Math.exp(n))+1/n)/2}function un(n){return((n=Math.exp(2*n))-1)/(n+1)}function on(n){return(n=Math.sin(n/2))*n}function an(){}function ln(n,t,e){return this instanceof ln?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof ln?new ln(n.h,n.s,n.l):_n(""+n,wn,ln):new ln(n,t,e)}function cn(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?u+(o-u)*n/60:180>n?o:240>n?u+(o-u)*(240-n)/60:u}function i(n){return Math.round(255*r(n))}var u,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,u=2*e-o,new mn(i(n+120),i(n),i(n-120))}function fn(n,t,e){return this instanceof fn?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof fn?new fn(n.h,n.c,n.l):n instanceof hn?gn(n.l,n.a,n.b):gn((n=Sn((n=ao.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new fn(n,t,e)}function sn(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new hn(e,Math.cos(n*=Yo)*t,Math.sin(n)*t)}function hn(n,t,e){return this instanceof hn?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof hn?new hn(n.l,n.a,n.b):n instanceof fn?sn(n.h,n.c,n.l):Sn((n=mn(n)).r,n.g,n.b):new hn(n,t,e)}function pn(n,t,e){var r=(n+16)/116,i=r+t/500,u=r-e/200;return i=vn(i)*na,r=vn(r)*ta,u=vn(u)*ea,new mn(yn(3.2404542*i-1.5371385*r-.4985314*u),yn(-.969266*i+1.8760108*r+.041556*u),yn(.0556434*i-.2040259*r+1.0572252*u))}function gn(n,t,e){return n>0?new fn(Math.atan2(e,t)*Zo,Math.sqrt(t*t+e*e),n):new fn(NaN,NaN,n)}function vn(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function dn(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function yn(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function mn(n,t,e){return this instanceof mn?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof mn?new mn(n.r,n.g,n.b):_n(""+n,mn,cn):new mn(n,t,e)}function Mn(n){return new mn(n>>16,n>>8&255,255&n)}function xn(n){return Mn(n)+""}function bn(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function _n(n,t,e){var r,i,u,o=0,a=0,l=0;if(r=/([a-z]+)\((.*)\)/.exec(n=n.toLowerCase()))switch(i=r[2].split(","),r[1]){case"hsl":return e(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return t(Nn(i[0]),Nn(i[1]),Nn(i[2]))}return(u=ua.get(n))?t(u.r,u.g,u.b):(null==n||"#"!==n.charAt(0)||isNaN(u=parseInt(n.slice(1),16))||(4===n.length?(o=(3840&u)>>4,o=o>>4|o,a=240&u,a=a>>4|a,l=15&u,l=l<<4|l):7===n.length&&(o=(16711680&u)>>16,a=(65280&u)>>8,l=255&u)),t(o,a,l))}function wn(n,t,e){var r,i,u=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-u,l=(o+u)/2;return a?(i=.5>l?a/(o+u):a/(2-o-u),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=NaN,i=l>0&&1>l?0:r),new ln(r,i,l)}function Sn(n,t,e){n=kn(n),t=kn(t),e=kn(e);var r=dn((.4124564*n+.3575761*t+.1804375*e)/na),i=dn((.2126729*n+.7151522*t+.072175*e)/ta),u=dn((.0193339*n+.119192*t+.9503041*e)/ea);return hn(116*i-16,500*(r-i),200*(i-u))}function kn(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Nn(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function En(n){return"function"==typeof n?n:function(){return n}}function An(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),Cn(t,e,n,r)}}function Cn(n,t,e,r){function i(){var n,t=l.status;if(!t&&Ln(l)||t>=200&&300>t||304===t){try{n=e.call(u,l)}catch(r){return void o.error.call(u,r)}o.load.call(u,n)}else o.error.call(u,l)}var u={},o=ao.dispatch("beforesend","progress","load","error"),a={},l=new XMLHttpRequest,c=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(n)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(n){var t=ao.event;ao.event=n;try{o.progress.call(u,l)}finally{ao.event=t}},u.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",u)},u.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",u):t},u.responseType=function(n){return arguments.length?(c=n,u):c},u.response=function(n){return e=n,u},["get","post"].forEach(function(n){u[n]=function(){return u.send.apply(u,[n].concat(co(arguments)))}}),u.send=function(e,r,i){if(2===arguments.length&&"function"==typeof r&&(i=r,r=null),l.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),l.setRequestHeader)for(var f in a)l.setRequestHeader(f,a[f]);return null!=t&&l.overrideMimeType&&l.overrideMimeType(t),null!=c&&(l.responseType=c),null!=i&&u.on("error",i).on("load",function(n){i(null,n)}),o.beforesend.call(u,l),l.send(null==r?null:r),u},u.abort=function(){return l.abort(),u},ao.rebind(u,o,"on"),null==r?u:u.get(zn(r))}function zn(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function Ln(n){var t=n.responseType;return t&&"text"!==t?n.response:n.responseText}function qn(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var i=e+t,u={c:n,t:i,n:null};return aa?aa.n=u:oa=u,aa=u,la||(ca=clearTimeout(ca),la=1,fa(Tn)),u}function Tn(){var n=Rn(),t=Dn()-n;t>24?(isFinite(t)&&(clearTimeout(ca),ca=setTimeout(Tn,t)),la=0):(la=1,fa(Tn))}function Rn(){for(var n=Date.now(),t=oa;t;)n>=t.t&&t.c(n-t.t)&&(t.c=null),t=t.n;return n}function Dn(){for(var n,t=oa,e=1/0;t;)t.c?(t.t<e&&(e=t.t),t=(n=t).n):t=n?n.n=t.n:oa=t.n;return aa=n,e}function Pn(n,t){return t-(n?Math.ceil(Math.log(n)/Math.LN10):1)}function Un(n,t){var e=Math.pow(10,3*xo(8-t));return{scale:t>8?function(n){return n/e}:function(n){return n*e},symbol:n}}function jn(n){var t=n.decimal,e=n.thousands,r=n.grouping,i=n.currency,u=r&&e?function(n,t){for(var i=n.length,u=[],o=0,a=r[0],l=0;i>0&&a>0&&(l+a+1>t&&(a=Math.max(1,t-l)),u.push(n.substring(i-=a,i+a)),!((l+=a+1)>t));)a=r[o=(o+1)%r.length];return u.reverse().join(e)}:m;return function(n){var e=ha.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"-",l=e[4]||"",c=e[5],f=+e[6],s=e[7],h=e[8],p=e[9],g=1,v="",d="",y=!1,m=!0;switch(h&&(h=+h.substring(1)),(c||"0"===r&&"="===o)&&(c=r="0",o="="),p){case"n":s=!0,p="g";break;case"%":g=100,d="%",p="f";break;case"p":g=100,d="%",p="r";break;case"b":case"o":case"x":case"X":"#"===l&&(v="0"+p.toLowerCase());case"c":m=!1;case"d":y=!0,h=0;break;case"s":g=-1,p="r"}"$"===l&&(v=i[0],d=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=pa.get(p)||Fn;var M=c&&s;return function(n){var e=d;if(y&&n%1)return"";var i=0>n||0===n&&0>1/n?(n=-n,"-"):"-"===a?"":a;if(0>g){var l=ao.formatPrefix(n,h);n=l.scale(n),e=l.symbol+d}else n*=g;n=p(n,h);var x,b,_=n.lastIndexOf(".");if(0>_){var w=m?n.lastIndexOf("e"):-1;0>w?(x=n,b=""):(x=n.substring(0,w),b=n.substring(w))}else x=n.substring(0,_),b=t+n.substring(_+1);!c&&s&&(x=u(x,1/0));var S=v.length+x.length+b.length+(M?0:i.length),k=f>S?new Array(S=f-S+1).join(r):"";return M&&(x=u(k+x,k.length?f-b.length:1/0)),i+=v,n=x+b,("<"===o?i+n+k:">"===o?k+i+n:"^"===o?k.substring(0,S>>=1)+i+n+k.substring(S):i+(M?n:k+n))+e}}}function Fn(n){return n+""}function Hn(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function On(n,t,e){function r(t){var e=n(t),r=u(e,1);return r-t>t-e?e:r}function i(e){return t(e=n(new va(e-1)),1),e}function u(n,e){return t(n=new va(+n),e),n}function o(n,r,u){var o=i(n),a=[];if(u>1)for(;r>o;)e(o)%u||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{va=Hn;var r=new Hn;return r._=n,o(r,t,e)}finally{va=Date}}n.floor=n,n.round=r,n.ceil=i,n.offset=u,n.range=o;var l=n.utc=In(n);return l.floor=l,l.round=In(r),l.ceil=In(i),l.offset=In(u),l.range=a,n}function In(n){return function(t,e){try{va=Hn;var r=new Hn;return r._=t,n(r,e)._}finally{va=Date}}}function Yn(n){function t(n){function t(t){for(var e,i,u,o=[],a=-1,l=0;++a<r;)37===n.charCodeAt(a)&&(o.push(n.slice(l,a)),null!=(i=ya[e=n.charAt(++a)])&&(e=n.charAt(++a)),(u=A[e])&&(e=u(t,null==i?"e"===e?" ":"0":i)),o.push(e),l=a+1);return o.push(n.slice(l,a)),o.join("")}var r=n.length;return t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=e(r,n,t,0);if(i!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var u=null!=r.Z&&va!==Hn,o=new(u?Hn:va);return"j"in r?o.setFullYear(r.y,0,r.j):"W"in r||"U"in r?("w"in r||(r.w="W"in r?1:0),o.setFullYear(r.y,0,1),o.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(o.getDay()+5)%7:r.w+7*r.U-(o.getDay()+6)%7)):o.setFullYear(r.y,r.m,r.d),o.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L),u?o._:o},t.toString=function(){return n},t}function e(n,t,e,r){for(var i,u,o,a=0,l=t.length,c=e.length;l>a;){if(r>=c)return-1;if(i=t.charCodeAt(a++),37===i){if(o=t.charAt(a++),u=C[o in ya?t.charAt(a++):o],!u||(r=u(n,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){_.lastIndex=0;var r=_.exec(t.slice(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){x.lastIndex=0;var r=x.exec(t.slice(e));return r?(n.w=b.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){N.lastIndex=0;var r=N.exec(t.slice(e));return r?(n.m=E.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.slice(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,A.c.toString(),t,r)}function l(n,t,r){return e(n,A.x.toString(),t,r)}function c(n,t,r){return e(n,A.X.toString(),t,r)}function f(n,t,e){var r=M.get(t.slice(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var s=n.dateTime,h=n.date,p=n.time,g=n.periods,v=n.days,d=n.shortDays,y=n.months,m=n.shortMonths;t.utc=function(n){function e(n){try{va=Hn;var t=new va;return t._=n,r(t)}finally{va=Date}}var r=t(n);return e.parse=function(n){try{va=Hn;var t=r.parse(n);return t&&t._}finally{va=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ct;var M=ao.map(),x=Vn(v),b=Xn(v),_=Vn(d),w=Xn(d),S=Vn(y),k=Xn(y),N=Vn(m),E=Xn(m);g.forEach(function(n,t){M.set(n.toLowerCase(),t)});var A={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return m[n.getMonth()]},B:function(n){return y[n.getMonth()]},c:t(s),d:function(n,t){return Zn(n.getDate(),t,2)},e:function(n,t){return Zn(n.getDate(),t,2)},H:function(n,t){return Zn(n.getHours(),t,2)},I:function(n,t){return Zn(n.getHours()%12||12,t,2)},j:function(n,t){return Zn(1+ga.dayOfYear(n),t,3)},L:function(n,t){return Zn(n.getMilliseconds(),t,3)},m:function(n,t){return Zn(n.getMonth()+1,t,2)},M:function(n,t){return Zn(n.getMinutes(),t,2)},p:function(n){return g[+(n.getHours()>=12)]},S:function(n,t){return Zn(n.getSeconds(),t,2)},U:function(n,t){return Zn(ga.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return Zn(ga.mondayOfYear(n),t,2)},x:t(h),X:t(p),y:function(n,t){return Zn(n.getFullYear()%100,t,2)},Y:function(n,t){return Zn(n.getFullYear()%1e4,t,4)},Z:at,"%":function(){return"%"}},C={a:r,A:i,b:u,B:o,c:a,d:tt,e:tt,H:rt,I:rt,j:et,L:ot,m:nt,M:it,p:f,S:ut,U:Bn,w:$n,W:Wn,x:l,X:c,y:Gn,Y:Jn,Z:Kn,"%":lt};return t}function Zn(n,t,e){var r=0>n?"-":"",i=(r?-n:n)+"",u=i.length;return r+(e>u?new Array(e-u+1).join(t)+i:i)}function Vn(n){return new RegExp("^(?:"+n.map(ao.requote).join("|")+")","i")}function Xn(n){for(var t=new c,e=-1,r=n.length;++e<r;)t.set(n[e].toLowerCase(),e);return t}function $n(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+1));return r?(n.w=+r[0],e+r[0].length):-1}function Bn(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e));return r?(n.U=+r[0],e+r[0].length):-1}function Wn(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e));return r?(n.W=+r[0],e+r[0].length):-1}function Jn(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+4));return r?(n.y=+r[0],e+r[0].length):-1}function Gn(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.y=Qn(+r[0]),e+r[0].length):-1}function Kn(n,t,e){return/^[+-]\d{4}$/.test(t=t.slice(e,e+5))?(n.Z=-t,e+5):-1}function Qn(n){return n+(n>68?1900:2e3)}function nt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function tt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function et(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function rt(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function it(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function ut(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function ot(n,t,e){ma.lastIndex=0;var r=ma.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function at(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=xo(t)/60|0,i=xo(t)%60;return e+Zn(r,"0",2)+Zn(i,"0",2)}function lt(n,t,e){Ma.lastIndex=0;var r=Ma.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function ct(n){for(var t=n.length,e=-1;++e<t;)n[e][0]=this(n[e][0]);return function(t){for(var e=0,r=n[e];!r[1](t);)r=n[++e];return r[0](t)}}function ft(){}function st(n,t,e){var r=e.s=n+t,i=r-n,u=r-i;e.t=n-u+(t-i)}function ht(n,t){n&&wa.hasOwnProperty(n.type)&&wa[n.type](n,t)}function pt(n,t,e){var r,i=-1,u=n.length-e;for(t.lineStart();++i<u;)r=n[i],t.point(r[0],r[1],r[2]);t.lineEnd()}function gt(n,t){var e=-1,r=n.length;for(t.polygonStart();++e<r;)pt(n[e],t,1);t.polygonEnd()}function vt(){function n(n,t){n*=Yo,t=t*Yo/2+Fo/4;var e=n-r,o=e>=0?1:-1,a=o*e,l=Math.cos(t),c=Math.sin(t),f=u*c,s=i*l+f*Math.cos(a),h=f*o*Math.sin(a);ka.add(Math.atan2(h,s)),r=n,i=l,u=c}var t,e,r,i,u;Na.point=function(o,a){Na.point=n,r=(t=o)*Yo,i=Math.cos(a=(e=a)*Yo/2+Fo/4),u=Math.sin(a)},Na.lineEnd=function(){n(t,e)}}function dt(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function yt(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function mt(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function Mt(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function xt(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function bt(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function _t(n){return[Math.atan2(n[1],n[0]),tn(n[2])]}function wt(n,t){return xo(n[0]-t[0])<Uo&&xo(n[1]-t[1])<Uo}function St(n,t){n*=Yo;var e=Math.cos(t*=Yo);kt(e*Math.cos(n),e*Math.sin(n),Math.sin(t))}function kt(n,t,e){++Ea,Ca+=(n-Ca)/Ea,za+=(t-za)/Ea,La+=(e-La)/Ea}function Nt(){function n(n,i){n*=Yo;var u=Math.cos(i*=Yo),o=u*Math.cos(n),a=u*Math.sin(n),l=Math.sin(i),c=Math.atan2(Math.sqrt((c=e*l-r*a)*c+(c=r*o-t*l)*c+(c=t*a-e*o)*c),t*o+e*a+r*l);Aa+=c,qa+=c*(t+(t=o)),Ta+=c*(e+(e=a)),Ra+=c*(r+(r=l)),kt(t,e,r)}var t,e,r;ja.point=function(i,u){i*=Yo;var o=Math.cos(u*=Yo);t=o*Math.cos(i),e=o*Math.sin(i),r=Math.sin(u),ja.point=n,kt(t,e,r)}}function Et(){ja.point=St}function At(){function n(n,t){n*=Yo;var e=Math.cos(t*=Yo),o=e*Math.cos(n),a=e*Math.sin(n),l=Math.sin(t),c=i*l-u*a,f=u*o-r*l,s=r*a-i*o,h=Math.sqrt(c*c+f*f+s*s),p=r*o+i*a+u*l,g=h&&-nn(p)/h,v=Math.atan2(h,p);Da+=g*c,Pa+=g*f,Ua+=g*s,Aa+=v,qa+=v*(r+(r=o)),Ta+=v*(i+(i=a)),Ra+=v*(u+(u=l)),kt(r,i,u)}var t,e,r,i,u;ja.point=function(o,a){t=o,e=a,ja.point=n,o*=Yo;var l=Math.cos(a*=Yo);r=l*Math.cos(o),i=l*Math.sin(o),u=Math.sin(a),kt(r,i,u)},ja.lineEnd=function(){n(t,e),ja.lineEnd=Et,ja.point=St}}function Ct(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function zt(){return!0}function Lt(n,t,e,r,i){var u=[],o=[];if(n.forEach(function(n){if(!((t=n.length-1)<=0)){var t,e=n[0],r=n[t];if(wt(e,r)){i.lineStart();for(var a=0;t>a;++a)i.point((e=n[a])[0],e[1]);return void i.lineEnd()}var l=new Tt(e,n,null,!0),c=new Tt(e,null,l,!1);l.o=c,u.push(l),o.push(c),l=new Tt(r,n,null,!1),c=new Tt(r,null,l,!0),l.o=c,u.push(l),o.push(c)}}),o.sort(t),qt(u),qt(o),u.length){for(var a=0,l=e,c=o.length;c>a;++a)o[a].e=l=!l;for(var f,s,h=u[0];;){for(var p=h,g=!0;p.v;)if((p=p.n)===h)return;f=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(g)for(var a=0,c=f.length;c>a;++a)i.point((s=f[a])[0],s[1]);else r(p.x,p.n.x,1,i);p=p.n}else{if(g){f=p.p.z;for(var a=f.length-1;a>=0;--a)i.point((s=f[a])[0],s[1])}else r(p.x,p.p.x,-1,i);p=p.p}p=p.o,f=p.z,g=!g}while(!p.v);i.lineEnd()}}}function qt(n){if(t=n.length){for(var t,e,r=0,i=n[0];++r<t;)i.n=e=n[r],e.p=i,i=e;i.n=e=n[0],e.p=i}}function Tt(n,t,e,r){this.x=n,this.z=t,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function Rt(n,t,e,r){return function(i,u){function o(t,e){var r=i(t,e);n(t=r[0],e=r[1])&&u.point(t,e)}function a(n,t){var e=i(n,t);d.point(e[0],e[1])}function l(){m.point=a,d.lineStart()}function c(){m.point=o,d.lineEnd()}function f(n,t){v.push([n,t]);var e=i(n,t);x.point(e[0],e[1])}function s(){x.lineStart(),v=[]}function h(){f(v[0][0],v[0][1]),x.lineEnd();var n,t=x.clean(),e=M.buffer(),r=e.length;if(v.pop(),g.push(v),v=null,r)if(1&t){n=e[0];var i,r=n.length-1,o=-1;if(r>0){for(b||(u.polygonStart(),b=!0),u.lineStart();++o<r;)u.point((i=n[o])[0],i[1]);u.lineEnd()}}else r>1&&2&t&&e.push(e.pop().concat(e.shift())),p.push(e.filter(Dt))}var p,g,v,d=t(u),y=i.invert(r[0],r[1]),m={point:o,lineStart:l,lineEnd:c,polygonStart:function(){m.point=f,m.lineStart=s,m.lineEnd=h,p=[],g=[]},polygonEnd:function(){m.point=o,m.lineStart=l,m.lineEnd=c,p=ao.merge(p);var n=Ot(y,g);p.length?(b||(u.polygonStart(),b=!0),Lt(p,Ut,n,e,u)):n&&(b||(u.polygonStart(),b=!0),u.lineStart(),e(null,null,1,u),u.lineEnd()),b&&(u.polygonEnd(),b=!1),p=g=null},sphere:function(){u.polygonStart(),u.lineStart(),e(null,null,1,u),u.lineEnd(),u.polygonEnd()}},M=Pt(),x=t(M),b=!1;return m}}function Dt(n){return n.length>1}function Pt(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:b,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Ut(n,t){return((n=n.x)[0]<0?n[1]-Io-Uo:Io-n[1])-((t=t.x)[0]<0?t[1]-Io-Uo:Io-t[1])}function jt(n){var t,e=NaN,r=NaN,i=NaN;return{lineStart:function(){n.lineStart(),t=1},point:function(u,o){var a=u>0?Fo:-Fo,l=xo(u-e);xo(l-Fo)<Uo?(n.point(e,r=(r+o)/2>0?Io:-Io),n.point(i,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(u,r),t=0):i!==a&&l>=Fo&&(xo(e-i)<Uo&&(e-=i*Uo),xo(u-a)<Uo&&(u-=a*Uo),r=Ft(e,r,u,o),n.point(i,r),n.lineEnd(),n.lineStart(),n.point(a,r),t=0),n.point(e=u,r=o),i=a},lineEnd:function(){n.lineEnd(),e=r=NaN},clean:function(){return 2-t}}}function Ft(n,t,e,r){var i,u,o=Math.sin(n-e);return xo(o)>Uo?Math.atan((Math.sin(t)*(u=Math.cos(r))*Math.sin(e)-Math.sin(r)*(i=Math.cos(t))*Math.sin(n))/(i*u*o)):(t+r)/2}function Ht(n,t,e,r){var i;if(null==n)i=e*Io,r.point(-Fo,i),r.point(0,i),r.point(Fo,i),r.point(Fo,0),r.point(Fo,-i),r.point(0,-i),r.point(-Fo,-i),r.point(-Fo,0),r.point(-Fo,i);else if(xo(n[0]-t[0])>Uo){var u=n[0]<t[0]?Fo:-Fo;i=e*u/2,r.point(-u,i),r.point(0,i),r.point(u,i)}else r.point(t[0],t[1])}function Ot(n,t){var e=n[0],r=n[1],i=[Math.sin(e),-Math.cos(e),0],u=0,o=0;ka.reset();for(var a=0,l=t.length;l>a;++a){var c=t[a],f=c.length;if(f)for(var s=c[0],h=s[0],p=s[1]/2+Fo/4,g=Math.sin(p),v=Math.cos(p),d=1;;){d===f&&(d=0),n=c[d];var y=n[0],m=n[1]/2+Fo/4,M=Math.sin(m),x=Math.cos(m),b=y-h,_=b>=0?1:-1,w=_*b,S=w>Fo,k=g*M;if(ka.add(Math.atan2(k*_*Math.sin(w),v*x+k*Math.cos(w))),u+=S?b+_*Ho:b,S^h>=e^y>=e){var N=mt(dt(s),dt(n));bt(N);var E=mt(i,N);bt(E);var A=(S^b>=0?-1:1)*tn(E[2]);(r>A||r===A&&(N[0]||N[1]))&&(o+=S^b>=0?1:-1)}if(!d++)break;h=y,g=M,v=x,s=n}}return(-Uo>u||Uo>u&&-Uo>ka)^1&o}function It(n){function t(n,t){return Math.cos(n)*Math.cos(t)>u}function e(n){var e,u,l,c,f;return{lineStart:function(){c=l=!1,f=1},point:function(s,h){var p,g=[s,h],v=t(s,h),d=o?v?0:i(s,h):v?i(s+(0>s?Fo:-Fo),h):0;if(!e&&(c=l=v)&&n.lineStart(),v!==l&&(p=r(e,g),(wt(e,p)||wt(g,p))&&(g[0]+=Uo,g[1]+=Uo,v=t(g[0],g[1]))),v!==l)f=0,v?(n.lineStart(),p=r(g,e),n.point(p[0],p[1])):(p=r(e,g),n.point(p[0],p[1]),n.lineEnd()),e=p;else if(a&&e&&o^v){var y;d&u||!(y=r(g,e,!0))||(f=0,o?(n.lineStart(),n.point(y[0][0],y[0][1]),n.point(y[1][0],y[1][1]),n.lineEnd()):(n.point(y[1][0],y[1][1]),n.lineEnd(),n.lineStart(),n.point(y[0][0],y[0][1])))}!v||e&&wt(e,g)||n.point(g[0],g[1]),e=g,l=v,u=d},lineEnd:function(){l&&n.lineEnd(),e=null},clean:function(){return f|(c&&l)<<1}}}function r(n,t,e){var r=dt(n),i=dt(t),o=[1,0,0],a=mt(r,i),l=yt(a,a),c=a[0],f=l-c*c;if(!f)return!e&&n;var s=u*l/f,h=-u*c/f,p=mt(o,a),g=xt(o,s),v=xt(a,h);Mt(g,v);var d=p,y=yt(g,d),m=yt(d,d),M=y*y-m*(yt(g,g)-1);if(!(0>M)){var x=Math.sqrt(M),b=xt(d,(-y-x)/m);if(Mt(b,g),b=_t(b),!e)return b;var _,w=n[0],S=t[0],k=n[1],N=t[1];w>S&&(_=w,w=S,S=_);var E=S-w,A=xo(E-Fo)<Uo,C=A||Uo>E;if(!A&&k>N&&(_=k,k=N,N=_),C?A?k+N>0^b[1]<(xo(b[0]-w)<Uo?k:N):k<=b[1]&&b[1]<=N:E>Fo^(w<=b[0]&&b[0]<=S)){var z=xt(d,(-y+x)/m);return Mt(z,g),[b,_t(z)]}}}function i(t,e){var r=o?n:Fo-n,i=0;return-r>t?i|=1:t>r&&(i|=2),-r>e?i|=4:e>r&&(i|=8),i}var u=Math.cos(n),o=u>0,a=xo(u)>Uo,l=ve(n,6*Yo);return Rt(t,e,l,o?[0,-n]:[-Fo,n-Fo])}function Yt(n,t,e,r){return function(i){var u,o=i.a,a=i.b,l=o.x,c=o.y,f=a.x,s=a.y,h=0,p=1,g=f-l,v=s-c;if(u=n-l,g||!(u>0)){if(u/=g,0>g){if(h>u)return;p>u&&(p=u)}else if(g>0){if(u>p)return;u>h&&(h=u)}if(u=e-l,g||!(0>u)){if(u/=g,0>g){if(u>p)return;u>h&&(h=u)}else if(g>0){if(h>u)return;p>u&&(p=u)}if(u=t-c,v||!(u>0)){if(u/=v,0>v){if(h>u)return;p>u&&(p=u)}else if(v>0){if(u>p)return;u>h&&(h=u)}if(u=r-c,v||!(0>u)){if(u/=v,0>v){if(u>p)return;u>h&&(h=u)}else if(v>0){if(h>u)return;p>u&&(p=u)}return h>0&&(i.a={x:l+h*g,y:c+h*v}),1>p&&(i.b={x:l+p*g,y:c+p*v}),i}}}}}}function Zt(n,t,e,r){function i(r,i){return xo(r[0]-n)<Uo?i>0?0:3:xo(r[0]-e)<Uo?i>0?2:1:xo(r[1]-t)<Uo?i>0?1:0:i>0?3:2}function u(n,t){return o(n.x,t.x)}function o(n,t){var e=i(n,1),r=i(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function l(n){for(var t=0,e=d.length,r=n[1],i=0;e>i;++i)for(var u,o=1,a=d[i],l=a.length,c=a[0];l>o;++o)u=a[o],c[1]<=r?u[1]>r&&Q(c,u,n)>0&&++t:u[1]<=r&&Q(c,u,n)<0&&--t,c=u;return 0!==t}function c(u,a,l,c){var f=0,s=0;if(null==u||(f=i(u,l))!==(s=i(a,l))||o(u,a)<0^l>0){do c.point(0===f||3===f?n:e,f>1?r:t);while((f=(f+l+4)%4)!==s)}else c.point(a[0],a[1])}function f(i,u){return i>=n&&e>=i&&u>=t&&r>=u}function s(n,t){f(n,t)&&a.point(n,t)}function h(){C.point=g,d&&d.push(y=[]),S=!0,w=!1,b=_=NaN}function p(){v&&(g(m,M),x&&w&&E.rejoin(),v.push(E.buffer())),C.point=s,w&&a.lineEnd()}function g(n,t){n=Math.max(-Ha,Math.min(Ha,n)),t=Math.max(-Ha,Math.min(Ha,t));var e=f(n,t);if(d&&y.push([n,t]),S)m=n,M=t,x=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:b,y:_},b:{x:n,y:t}};A(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}b=n,_=t,w=e}var v,d,y,m,M,x,b,_,w,S,k,N=a,E=Pt(),A=Yt(n,t,e,r),C={point:s,lineStart:h,lineEnd:p,polygonStart:function(){a=E,v=[],d=[],k=!0},polygonEnd:function(){a=N,v=ao.merge(v);var t=l([n,r]),e=k&&t,i=v.length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),c(null,null,1,a),a.lineEnd()),i&&Lt(v,u,t,c,a),a.polygonEnd()),v=d=y=null}};return C}}function Vt(n){var t=0,e=Fo/3,r=ae(n),i=r(t,e);return i.parallels=function(n){return arguments.length?r(t=n[0]*Fo/180,e=n[1]*Fo/180):[t/Fo*180,e/Fo*180]},i}function Xt(n,t){function e(n,t){var e=Math.sqrt(u-2*i*Math.sin(t))/i;return[e*Math.sin(n*=i),o-e*Math.cos(n)]}var r=Math.sin(n),i=(r+Math.sin(t))/2,u=1+r*(2*i-r),o=Math.sqrt(u)/i;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/i,tn((u-(n*n+e*e)*i*i)/(2*i))]},e}function $t(){function n(n,t){Ia+=i*n-r*t,r=n,i=t}var t,e,r,i;$a.point=function(u,o){$a.point=n,t=r=u,e=i=o},$a.lineEnd=function(){n(t,e)}}function Bt(n,t){Ya>n&&(Ya=n),n>Va&&(Va=n),Za>t&&(Za=t),t>Xa&&(Xa=t)}function Wt(){function n(n,t){o.push("M",n,",",t,u)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function i(){o.push("Z")}var u=Jt(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return u=Jt(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Jt(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Gt(n,t){Ca+=n,za+=t,++La}function Kt(){function n(n,r){var i=n-t,u=r-e,o=Math.sqrt(i*i+u*u);qa+=o*(t+n)/2,Ta+=o*(e+r)/2,Ra+=o,Gt(t=n,e=r)}var t,e;Wa.point=function(r,i){Wa.point=n,Gt(t=r,e=i)}}function Qt(){Wa.point=Gt}function ne(){function n(n,t){var e=n-r,u=t-i,o=Math.sqrt(e*e+u*u);qa+=o*(r+n)/2,Ta+=o*(i+t)/2,Ra+=o,o=i*n-r*t,Da+=o*(r+n),Pa+=o*(i+t),Ua+=3*o,Gt(r=n,i=t)}var t,e,r,i;Wa.point=function(u,o){Wa.point=n,Gt(t=r=u,e=i=o)},Wa.lineEnd=function(){n(t,e)}}function te(n){function t(t,e){n.moveTo(t+o,e),n.arc(t,e,o,0,Ho)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function i(){a.point=t}function u(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:i,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=i,a.point=t},pointRadius:function(n){return o=n,a},result:b};return a}function ee(n){function t(n){return(a?r:e)(n)}function e(t){return ue(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){M=NaN,S.point=u,t.lineStart()}function u(e,r){var u=dt([e,r]),o=n(e,r);i(M,x,m,b,_,w,M=o[0],x=o[1],m=e,b=u[0],_=u[1],w=u[2],a,t),t.point(M,x)}function o(){S.point=e,t.lineEnd()}function l(){
r(),S.point=c,S.lineEnd=f}function c(n,t){u(s=n,h=t),p=M,g=x,v=b,d=_,y=w,S.point=u}function f(){i(M,x,m,b,_,w,p,g,s,v,d,y,a,t),S.lineEnd=o,o()}var s,h,p,g,v,d,y,m,M,x,b,_,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=l},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function i(t,e,r,a,l,c,f,s,h,p,g,v,d,y){var m=f-t,M=s-e,x=m*m+M*M;if(x>4*u&&d--){var b=a+p,_=l+g,w=c+v,S=Math.sqrt(b*b+_*_+w*w),k=Math.asin(w/=S),N=xo(xo(w)-1)<Uo||xo(r-h)<Uo?(r+h)/2:Math.atan2(_,b),E=n(N,k),A=E[0],C=E[1],z=A-t,L=C-e,q=M*z-m*L;(q*q/x>u||xo((m*z+M*L)/x-.5)>.3||o>a*p+l*g+c*v)&&(i(t,e,r,a,l,c,A,C,N,b/=S,_/=S,w,d,y),y.point(A,C),i(A,C,N,b,_,w,f,s,h,p,g,v,d,y))}}var u=.5,o=Math.cos(30*Yo),a=16;return t.precision=function(n){return arguments.length?(a=(u=n*n)>0&&16,t):Math.sqrt(u)},t}function re(n){var t=ee(function(t,e){return n([t*Zo,e*Zo])});return function(n){return le(t(n))}}function ie(n){this.stream=n}function ue(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function oe(n){return ae(function(){return n})()}function ae(n){function t(n){return n=a(n[0]*Yo,n[1]*Yo),[n[0]*h+l,c-n[1]*h]}function e(n){return n=a.invert((n[0]-l)/h,(c-n[1])/h),n&&[n[0]*Zo,n[1]*Zo]}function r(){a=Ct(o=se(y,M,x),u);var n=u(v,d);return l=p-n[0]*h,c=g+n[1]*h,i()}function i(){return f&&(f.valid=!1,f=null),t}var u,o,a,l,c,f,s=ee(function(n,t){return n=u(n,t),[n[0]*h+l,c-n[1]*h]}),h=150,p=480,g=250,v=0,d=0,y=0,M=0,x=0,b=Fa,_=m,w=null,S=null;return t.stream=function(n){return f&&(f.valid=!1),f=le(b(o,s(_(n)))),f.valid=!0,f},t.clipAngle=function(n){return arguments.length?(b=null==n?(w=n,Fa):It((w=+n)*Yo),i()):w},t.clipExtent=function(n){return arguments.length?(S=n,_=n?Zt(n[0][0],n[0][1],n[1][0],n[1][1]):m,i()):S},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(p=+n[0],g=+n[1],r()):[p,g]},t.center=function(n){return arguments.length?(v=n[0]%360*Yo,d=n[1]%360*Yo,r()):[v*Zo,d*Zo]},t.rotate=function(n){return arguments.length?(y=n[0]%360*Yo,M=n[1]%360*Yo,x=n.length>2?n[2]%360*Yo:0,r()):[y*Zo,M*Zo,x*Zo]},ao.rebind(t,s,"precision"),function(){return u=n.apply(this,arguments),t.invert=u.invert&&e,r()}}function le(n){return ue(n,function(t,e){n.point(t*Yo,e*Yo)})}function ce(n,t){return[n,t]}function fe(n,t){return[n>Fo?n-Ho:-Fo>n?n+Ho:n,t]}function se(n,t,e){return n?t||e?Ct(pe(n),ge(t,e)):pe(n):t||e?ge(t,e):fe}function he(n){return function(t,e){return t+=n,[t>Fo?t-Ho:-Fo>t?t+Ho:t,e]}}function pe(n){var t=he(n);return t.invert=he(-n),t}function ge(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*r+a*i;return[Math.atan2(l*u-f*o,a*r-c*i),tn(f*u+l*o)]}var r=Math.cos(n),i=Math.sin(n),u=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,l=Math.sin(n)*e,c=Math.sin(t),f=c*u-l*o;return[Math.atan2(l*u+c*o,a*r+f*i),tn(f*r-a*i)]},e}function ve(n,t){var e=Math.cos(n),r=Math.sin(n);return function(i,u,o,a){var l=o*t;null!=i?(i=de(e,i),u=de(e,u),(o>0?u>i:i>u)&&(i+=o*Ho)):(i=n+o*Ho,u=n-.5*l);for(var c,f=i;o>0?f>u:u>f;f-=l)a.point((c=_t([e,-r*Math.cos(f),-r*Math.sin(f)]))[0],c[1])}}function de(n,t){var e=dt(t);e[0]-=n,bt(e);var r=nn(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Uo)%(2*Math.PI)}function ye(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function me(n,t,e){var r=ao.range(n,t-Uo,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function Me(n){return n.source}function xe(n){return n.target}function be(n,t,e,r){var i=Math.cos(t),u=Math.sin(t),o=Math.cos(r),a=Math.sin(r),l=i*Math.cos(n),c=i*Math.sin(n),f=o*Math.cos(e),s=o*Math.sin(e),h=2*Math.asin(Math.sqrt(on(r-t)+i*o*on(e-n))),p=1/Math.sin(h),g=h?function(n){var t=Math.sin(n*=h)*p,e=Math.sin(h-n)*p,r=e*l+t*f,i=e*c+t*s,o=e*u+t*a;return[Math.atan2(i,r)*Zo,Math.atan2(o,Math.sqrt(r*r+i*i))*Zo]}:function(){return[n*Zo,t*Zo]};return g.distance=h,g}function _e(){function n(n,i){var u=Math.sin(i*=Yo),o=Math.cos(i),a=xo((n*=Yo)-t),l=Math.cos(a);Ja+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*u-e*o*l)*a),e*u+r*o*l),t=n,e=u,r=o}var t,e,r;Ga.point=function(i,u){t=i*Yo,e=Math.sin(u*=Yo),r=Math.cos(u),Ga.point=n},Ga.lineEnd=function(){Ga.point=Ga.lineEnd=b}}function we(n,t){function e(t,e){var r=Math.cos(t),i=Math.cos(e),u=n(r*i);return[u*i*Math.sin(t),u*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),i=t(r),u=Math.sin(i),o=Math.cos(i);return[Math.atan2(n*u,r*o),Math.asin(r&&e*u/r)]},e}function Se(n,t){function e(n,t){o>0?-Io+Uo>t&&(t=-Io+Uo):t>Io-Uo&&(t=Io-Uo);var e=o/Math.pow(i(t),u);return[e*Math.sin(u*n),o-e*Math.cos(u*n)]}var r=Math.cos(n),i=function(n){return Math.tan(Fo/4+n/2)},u=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(i(t)/i(n)),o=r*Math.pow(i(n),u)/u;return u?(e.invert=function(n,t){var e=o-t,r=K(u)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/u,2*Math.atan(Math.pow(o/r,1/u))-Io]},e):Ne}function ke(n,t){function e(n,t){var e=u-t;return[e*Math.sin(i*n),u-e*Math.cos(i*n)]}var r=Math.cos(n),i=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),u=r/i+n;return xo(i)<Uo?ce:(e.invert=function(n,t){var e=u-t;return[Math.atan2(n,e)/i,u-K(i)*Math.sqrt(n*n+e*e)]},e)}function Ne(n,t){return[n,Math.log(Math.tan(Fo/4+t/2))]}function Ee(n){var t,e=oe(n),r=e.scale,i=e.translate,u=e.clipExtent;return e.scale=function(){var n=r.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.translate=function(){var n=i.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.clipExtent=function(n){var o=u.apply(e,arguments);if(o===e){if(t=null==n){var a=Fo*r(),l=i();u([[l[0]-a,l[1]-a],[l[0]+a,l[1]+a]])}}else t&&(o=null);return o},e.clipExtent(null)}function Ae(n,t){return[Math.log(Math.tan(Fo/4+t/2)),-n]}function Ce(n){return n[0]}function ze(n){return n[1]}function Le(n){for(var t=n.length,e=[0,1],r=2,i=2;t>i;i++){for(;r>1&&Q(n[e[r-2]],n[e[r-1]],n[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function qe(n,t){return n[0]-t[0]||n[1]-t[1]}function Te(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Re(n,t,e,r){var i=n[0],u=e[0],o=t[0]-i,a=r[0]-u,l=n[1],c=e[1],f=t[1]-l,s=r[1]-c,h=(a*(l-c)-s*(i-u))/(s*o-a*f);return[i+h*o,l+h*f]}function De(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Pe(){rr(this),this.edge=this.site=this.circle=null}function Ue(n){var t=cl.pop()||new Pe;return t.site=n,t}function je(n){Be(n),ol.remove(n),cl.push(n),rr(n)}function Fe(n){var t=n.circle,e=t.x,r=t.cy,i={x:e,y:r},u=n.P,o=n.N,a=[n];je(n);for(var l=u;l.circle&&xo(e-l.circle.x)<Uo&&xo(r-l.circle.cy)<Uo;)u=l.P,a.unshift(l),je(l),l=u;a.unshift(l),Be(l);for(var c=o;c.circle&&xo(e-c.circle.x)<Uo&&xo(r-c.circle.cy)<Uo;)o=c.N,a.push(c),je(c),c=o;a.push(c),Be(c);var f,s=a.length;for(f=1;s>f;++f)c=a[f],l=a[f-1],nr(c.edge,l.site,c.site,i);l=a[0],c=a[s-1],c.edge=Ke(l.site,c.site,null,i),$e(l),$e(c)}function He(n){for(var t,e,r,i,u=n.x,o=n.y,a=ol._;a;)if(r=Oe(a,o)-u,r>Uo)a=a.L;else{if(i=u-Ie(a,o),!(i>Uo)){r>-Uo?(t=a.P,e=a):i>-Uo?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var l=Ue(n);if(ol.insert(t,l),t||e){if(t===e)return Be(t),e=Ue(t.site),ol.insert(l,e),l.edge=e.edge=Ke(t.site,l.site),$e(t),void $e(e);if(!e)return void(l.edge=Ke(t.site,l.site));Be(t),Be(e);var c=t.site,f=c.x,s=c.y,h=n.x-f,p=n.y-s,g=e.site,v=g.x-f,d=g.y-s,y=2*(h*d-p*v),m=h*h+p*p,M=v*v+d*d,x={x:(d*m-p*M)/y+f,y:(h*M-v*m)/y+s};nr(e.edge,c,g,x),l.edge=Ke(c,n,null,x),e.edge=Ke(n,g,null,x),$e(t),$e(e)}}function Oe(n,t){var e=n.site,r=e.x,i=e.y,u=i-t;if(!u)return r;var o=n.P;if(!o)return-(1/0);e=o.site;var a=e.x,l=e.y,c=l-t;if(!c)return a;var f=a-r,s=1/u-1/c,h=f/c;return s?(-h+Math.sqrt(h*h-2*s*(f*f/(-2*c)-l+c/2+i-u/2)))/s+r:(r+a)/2}function Ie(n,t){var e=n.N;if(e)return Oe(e,t);var r=n.site;return r.y===t?r.x:1/0}function Ye(n){this.site=n,this.edges=[]}function Ze(n){for(var t,e,r,i,u,o,a,l,c,f,s=n[0][0],h=n[1][0],p=n[0][1],g=n[1][1],v=ul,d=v.length;d--;)if(u=v[d],u&&u.prepare())for(a=u.edges,l=a.length,o=0;l>o;)f=a[o].end(),r=f.x,i=f.y,c=a[++o%l].start(),t=c.x,e=c.y,(xo(r-t)>Uo||xo(i-e)>Uo)&&(a.splice(o,0,new tr(Qe(u.site,f,xo(r-s)<Uo&&g-i>Uo?{x:s,y:xo(t-s)<Uo?e:g}:xo(i-g)<Uo&&h-r>Uo?{x:xo(e-g)<Uo?t:h,y:g}:xo(r-h)<Uo&&i-p>Uo?{x:h,y:xo(t-h)<Uo?e:p}:xo(i-p)<Uo&&r-s>Uo?{x:xo(e-p)<Uo?t:s,y:p}:null),u.site,null)),++l)}function Ve(n,t){return t.angle-n.angle}function Xe(){rr(this),this.x=this.y=this.arc=this.site=this.cy=null}function $e(n){var t=n.P,e=n.N;if(t&&e){var r=t.site,i=n.site,u=e.site;if(r!==u){var o=i.x,a=i.y,l=r.x-o,c=r.y-a,f=u.x-o,s=u.y-a,h=2*(l*s-c*f);if(!(h>=-jo)){var p=l*l+c*c,g=f*f+s*s,v=(s*p-c*g)/h,d=(l*g-f*p)/h,s=d+a,y=fl.pop()||new Xe;y.arc=n,y.site=i,y.x=v+o,y.y=s+Math.sqrt(v*v+d*d),y.cy=s,n.circle=y;for(var m=null,M=ll._;M;)if(y.y<M.y||y.y===M.y&&y.x<=M.x){if(!M.L){m=M.P;break}M=M.L}else{if(!M.R){m=M;break}M=M.R}ll.insert(m,y),m||(al=y)}}}}function Be(n){var t=n.circle;t&&(t.P||(al=t.N),ll.remove(t),fl.push(t),rr(t),n.circle=null)}function We(n){for(var t,e=il,r=Yt(n[0][0],n[0][1],n[1][0],n[1][1]),i=e.length;i--;)t=e[i],(!Je(t,n)||!r(t)||xo(t.a.x-t.b.x)<Uo&&xo(t.a.y-t.b.y)<Uo)&&(t.a=t.b=null,e.splice(i,1))}function Je(n,t){var e=n.b;if(e)return!0;var r,i,u=n.a,o=t[0][0],a=t[1][0],l=t[0][1],c=t[1][1],f=n.l,s=n.r,h=f.x,p=f.y,g=s.x,v=s.y,d=(h+g)/2,y=(p+v)/2;if(v===p){if(o>d||d>=a)return;if(h>g){if(u){if(u.y>=c)return}else u={x:d,y:l};e={x:d,y:c}}else{if(u){if(u.y<l)return}else u={x:d,y:c};e={x:d,y:l}}}else if(r=(h-g)/(v-p),i=y-r*d,-1>r||r>1)if(h>g){if(u){if(u.y>=c)return}else u={x:(l-i)/r,y:l};e={x:(c-i)/r,y:c}}else{if(u){if(u.y<l)return}else u={x:(c-i)/r,y:c};e={x:(l-i)/r,y:l}}else if(v>p){if(u){if(u.x>=a)return}else u={x:o,y:r*o+i};e={x:a,y:r*a+i}}else{if(u){if(u.x<o)return}else u={x:a,y:r*a+i};e={x:o,y:r*o+i}}return n.a=u,n.b=e,!0}function Ge(n,t){this.l=n,this.r=t,this.a=this.b=null}function Ke(n,t,e,r){var i=new Ge(n,t);return il.push(i),e&&nr(i,n,t,e),r&&nr(i,t,n,r),ul[n.i].edges.push(new tr(i,n,t)),ul[t.i].edges.push(new tr(i,t,n)),i}function Qe(n,t,e){var r=new Ge(n,null);return r.a=t,r.b=e,il.push(r),r}function nr(n,t,e,r){n.a||n.b?n.l===e?n.b=r:n.a=r:(n.a=r,n.l=t,n.r=e)}function tr(n,t,e){var r=n.a,i=n.b;this.edge=n,this.site=t,this.angle=e?Math.atan2(e.y-t.y,e.x-t.x):n.l===t?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function er(){this._=null}function rr(n){n.U=n.C=n.L=n.R=n.P=n.N=null}function ir(n,t){var e=t,r=t.R,i=e.U;i?i.L===e?i.L=r:i.R=r:n._=r,r.U=i,e.U=r,e.R=r.L,e.R&&(e.R.U=e),r.L=e}function ur(n,t){var e=t,r=t.L,i=e.U;i?i.L===e?i.L=r:i.R=r:n._=r,r.U=i,e.U=r,e.L=r.R,e.L&&(e.L.U=e),r.R=e}function or(n){for(;n.L;)n=n.L;return n}function ar(n,t){var e,r,i,u=n.sort(lr).pop();for(il=[],ul=new Array(n.length),ol=new er,ll=new er;;)if(i=al,u&&(!i||u.y<i.y||u.y===i.y&&u.x<i.x))u.x===e&&u.y===r||(ul[u.i]=new Ye(u),He(u),e=u.x,r=u.y),u=n.pop();else{if(!i)break;Fe(i.arc)}t&&(We(t),Ze(t));var o={cells:ul,edges:il};return ol=ll=il=ul=null,o}function lr(n,t){return t.y-n.y||t.x-n.x}function cr(n,t,e){return(n.x-e.x)*(t.y-n.y)-(n.x-t.x)*(e.y-n.y)}function fr(n){return n.x}function sr(n){return n.y}function hr(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function pr(n,t,e,r,i,u){if(!n(t,e,r,i,u)){var o=.5*(e+i),a=.5*(r+u),l=t.nodes;l[0]&&pr(n,l[0],e,r,o,a),l[1]&&pr(n,l[1],o,r,i,a),l[2]&&pr(n,l[2],e,a,o,u),l[3]&&pr(n,l[3],o,a,i,u)}}function gr(n,t,e,r,i,u,o){var a,l=1/0;return function c(n,f,s,h,p){if(!(f>u||s>o||r>h||i>p)){if(g=n.point){var g,v=t-n.x,d=e-n.y,y=v*v+d*d;if(l>y){var m=Math.sqrt(l=y);r=t-m,i=e-m,u=t+m,o=e+m,a=g}}for(var M=n.nodes,x=.5*(f+h),b=.5*(s+p),_=t>=x,w=e>=b,S=w<<1|_,k=S+4;k>S;++S)if(n=M[3&S])switch(3&S){case 0:c(n,f,s,x,b);break;case 1:c(n,x,s,h,b);break;case 2:c(n,f,b,x,p);break;case 3:c(n,x,b,h,p)}}}(n,r,i,u,o),a}function vr(n,t){n=ao.rgb(n),t=ao.rgb(t);var e=n.r,r=n.g,i=n.b,u=t.r-e,o=t.g-r,a=t.b-i;return function(n){return"#"+bn(Math.round(e+u*n))+bn(Math.round(r+o*n))+bn(Math.round(i+a*n))}}function dr(n,t){var e,r={},i={};for(e in n)e in t?r[e]=Mr(n[e],t[e]):i[e]=n[e];for(e in t)e in n||(i[e]=t[e]);return function(n){for(e in r)i[e]=r[e](n);return i}}function yr(n,t){return n=+n,t=+t,function(e){return n*(1-e)+t*e}}function mr(n,t){var e,r,i,u=hl.lastIndex=pl.lastIndex=0,o=-1,a=[],l=[];for(n+="",t+="";(e=hl.exec(n))&&(r=pl.exec(t));)(i=r.index)>u&&(i=t.slice(u,i),a[o]?a[o]+=i:a[++o]=i),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,l.push({i:o,x:yr(e,r)})),u=pl.lastIndex;return u<t.length&&(i=t.slice(u),a[o]?a[o]+=i:a[++o]=i),a.length<2?l[0]?(t=l[0].x,function(n){return t(n)+""}):function(){return t}:(t=l.length,function(n){for(var e,r=0;t>r;++r)a[(e=l[r]).i]=e.x(n);return a.join("")})}function Mr(n,t){for(var e,r=ao.interpolators.length;--r>=0&&!(e=ao.interpolators[r](n,t)););return e}function xr(n,t){var e,r=[],i=[],u=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(Mr(n[e],t[e]));for(;u>e;++e)i[e]=n[e];for(;o>e;++e)i[e]=t[e];return function(n){for(e=0;a>e;++e)i[e]=r[e](n);return i}}function br(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function _r(n){return function(t){return 1-n(1-t)}}function wr(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function Sr(n){return n*n}function kr(n){return n*n*n}function Nr(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function Er(n){return function(t){return Math.pow(t,n)}}function Ar(n){return 1-Math.cos(n*Io)}function Cr(n){return Math.pow(2,10*(n-1))}function zr(n){return 1-Math.sqrt(1-n*n)}function Lr(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/Ho*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*Ho/t)}}function qr(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Tr(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Rr(n,t){n=ao.hcl(n),t=ao.hcl(t);var e=n.h,r=n.c,i=n.l,u=t.h-e,o=t.c-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return sn(e+u*n,r+o*n,i+a*n)+""}}function Dr(n,t){n=ao.hsl(n),t=ao.hsl(t);var e=n.h,r=n.s,i=n.l,u=t.h-e,o=t.s-r,a=t.l-i;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(u)?(u=0,e=isNaN(e)?t.h:e):u>180?u-=360:-180>u&&(u+=360),function(n){return cn(e+u*n,r+o*n,i+a*n)+""}}function Pr(n,t){n=ao.lab(n),t=ao.lab(t);var e=n.l,r=n.a,i=n.b,u=t.l-e,o=t.a-r,a=t.b-i;return function(n){return pn(e+u*n,r+o*n,i+a*n)+""}}function Ur(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function jr(n){var t=[n.a,n.b],e=[n.c,n.d],r=Hr(t),i=Fr(t,e),u=Hr(Or(e,t,-i))||0;t[0]*e[1]<e[0]*t[1]&&(t[0]*=-1,t[1]*=-1,r*=-1,i*=-1),this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-e[0],e[1]))*Zo,this.translate=[n.e,n.f],this.scale=[r,u],this.skew=u?Math.atan2(i,u)*Zo:0}function Fr(n,t){return n[0]*t[0]+n[1]*t[1]}function Hr(n){var t=Math.sqrt(Fr(n,n));return t&&(n[0]/=t,n[1]/=t),t}function Or(n,t,e){return n[0]+=e*t[0],n[1]+=e*t[1],n}function Ir(n){return n.length?n.pop()+",":""}function Yr(n,t,e,r){if(n[0]!==t[0]||n[1]!==t[1]){var i=e.push("translate(",null,",",null,")");r.push({i:i-4,x:yr(n[0],t[0])},{i:i-2,x:yr(n[1],t[1])})}else(t[0]||t[1])&&e.push("translate("+t+")")}function Zr(n,t,e,r){n!==t?(n-t>180?t+=360:t-n>180&&(n+=360),r.push({i:e.push(Ir(e)+"rotate(",null,")")-2,x:yr(n,t)})):t&&e.push(Ir(e)+"rotate("+t+")")}function Vr(n,t,e,r){n!==t?r.push({i:e.push(Ir(e)+"skewX(",null,")")-2,x:yr(n,t)}):t&&e.push(Ir(e)+"skewX("+t+")")}function Xr(n,t,e,r){if(n[0]!==t[0]||n[1]!==t[1]){var i=e.push(Ir(e)+"scale(",null,",",null,")");r.push({i:i-4,x:yr(n[0],t[0])},{i:i-2,x:yr(n[1],t[1])})}else 1===t[0]&&1===t[1]||e.push(Ir(e)+"scale("+t+")")}function $r(n,t){var e=[],r=[];return n=ao.transform(n),t=ao.transform(t),Yr(n.translate,t.translate,e,r),Zr(n.rotate,t.rotate,e,r),Vr(n.skew,t.skew,e,r),Xr(n.scale,t.scale,e,r),n=t=null,function(n){for(var t,i=-1,u=r.length;++i<u;)e[(t=r[i]).i]=t.x(n);return e.join("")}}function Br(n,t){return t=(t-=n=+n)||1/t,function(e){return(e-n)/t}}function Wr(n,t){return t=(t-=n=+n)||1/t,function(e){return Math.max(0,Math.min(1,(e-n)/t))}}function Jr(n){for(var t=n.source,e=n.target,r=Kr(t,e),i=[t];t!==r;)t=t.parent,i.push(t);for(var u=i.length;e!==r;)i.splice(u,0,e),e=e.parent;return i}function Gr(n){for(var t=[],e=n.parent;null!=e;)t.push(n),n=e,e=e.parent;return t.push(n),t}function Kr(n,t){if(n===t)return n;for(var e=Gr(n),r=Gr(t),i=e.pop(),u=r.pop(),o=null;i===u;)o=i,i=e.pop(),u=r.pop();return o}function Qr(n){n.fixed|=2}function ni(n){n.fixed&=-7}function ti(n){n.fixed|=4,n.px=n.x,n.py=n.y}function ei(n){n.fixed&=-5}function ri(n,t,e){var r=0,i=0;if(n.charge=0,!n.leaf)for(var u,o=n.nodes,a=o.length,l=-1;++l<a;)u=o[l],null!=u&&(ri(u,t,e),n.charge+=u.charge,r+=u.charge*u.cx,i+=u.charge*u.cy);if(n.point){n.leaf||(n.point.x+=Math.random()-.5,n.point.y+=Math.random()-.5);var c=t*e[n.point.index];n.charge+=n.pointCharge=c,r+=c*n.point.x,i+=c*n.point.y}n.cx=r/n.charge,n.cy=i/n.charge}function ii(n,t){return ao.rebind(n,t,"sort","children","value"),n.nodes=n,n.links=fi,n}function ui(n,t){for(var e=[n];null!=(n=e.pop());)if(t(n),(i=n.children)&&(r=i.length))for(var r,i;--r>=0;)e.push(i[r])}function oi(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(u=n.children)&&(i=u.length))for(var i,u,o=-1;++o<i;)e.push(u[o]);for(;null!=(n=r.pop());)t(n)}function ai(n){return n.children}function li(n){return n.value}function ci(n,t){return t.value-n.value}function fi(n){return ao.merge(n.map(function(n){return(n.children||[]).map(function(t){return{source:n,target:t}})}))}function si(n){return n.x}function hi(n){return n.y}function pi(n,t,e){n.y0=t,n.y=e}function gi(n){return ao.range(n.length)}function vi(n){for(var t=-1,e=n[0].length,r=[];++t<e;)r[t]=0;return r}function di(n){for(var t,e=1,r=0,i=n[0][1],u=n.length;u>e;++e)(t=n[e][1])>i&&(r=e,i=t);return r}function yi(n){return n.reduce(mi,0)}function mi(n,t){return n+t[1]}function Mi(n,t){return xi(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function xi(n,t){for(var e=-1,r=+n[0],i=(n[1]-r)/t,u=[];++e<=t;)u[e]=i*e+r;return u}function bi(n){return[ao.min(n),ao.max(n)]}function _i(n,t){return n.value-t.value}function wi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function Si(n,t){n._pack_next=t,t._pack_prev=n}function ki(n,t){var e=t.x-n.x,r=t.y-n.y,i=n.r+t.r;return.999*i*i>e*e+r*r}function Ni(n){function t(n){f=Math.min(n.x-n.r,f),s=Math.max(n.x+n.r,s),h=Math.min(n.y-n.r,h),p=Math.max(n.y+n.r,p)}if((e=n.children)&&(c=e.length)){var e,r,i,u,o,a,l,c,f=1/0,s=-(1/0),h=1/0,p=-(1/0);if(e.forEach(Ei),r=e[0],r.x=-r.r,r.y=0,t(r),c>1&&(i=e[1],i.x=i.r,i.y=0,t(i),c>2))for(u=e[2],zi(r,i,u),t(u),wi(r,u),r._pack_prev=u,wi(u,i),i=r._pack_next,o=3;c>o;o++){zi(r,i,u=e[o]);var g=0,v=1,d=1;for(a=i._pack_next;a!==i;a=a._pack_next,v++)if(ki(a,u)){g=1;break}if(1==g)for(l=r._pack_prev;l!==a._pack_prev&&!ki(l,u);l=l._pack_prev,d++);g?(d>v||v==d&&i.r<r.r?Si(r,i=a):Si(r=l,i),o--):(wi(r,u),i=u,t(u))}var y=(f+s)/2,m=(h+p)/2,M=0;for(o=0;c>o;o++)u=e[o],u.x-=y,u.y-=m,M=Math.max(M,u.r+Math.sqrt(u.x*u.x+u.y*u.y));n.r=M,e.forEach(Ai)}}function Ei(n){n._pack_next=n._pack_prev=n}function Ai(n){delete n._pack_next,delete n._pack_prev}function Ci(n,t,e,r){var i=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,i)for(var u=-1,o=i.length;++u<o;)Ci(i[u],t,e,r)}function zi(n,t,e){var r=n.r+e.r,i=t.x-n.x,u=t.y-n.y;if(r&&(i||u)){var o=t.r+e.r,a=i*i+u*u;o*=o,r*=r;var l=.5+(r-o)/(2*a),c=Math.sqrt(Math.max(0,2*o*(r+a)-(r-=a)*r-o*o))/(2*a);e.x=n.x+l*i+c*u,e.y=n.y+l*u-c*i}else e.x=n.x+r,e.y=n.y}function Li(n,t){return n.parent==t.parent?1:2}function qi(n){var t=n.children;return t.length?t[0]:n.t}function Ti(n){var t,e=n.children;return(t=e.length)?e[t-1]:n.t}function Ri(n,t,e){var r=e/(t.i-n.i);t.c-=r,t.s+=e,n.c+=r,t.z+=e,t.m+=e}function Di(n){for(var t,e=0,r=0,i=n.children,u=i.length;--u>=0;)t=i[u],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function Pi(n,t,e){return n.a.parent===t.parent?n.a:e}function Ui(n){return 1+ao.max(n,function(n){return n.y})}function ji(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Fi(n){var t=n.children;return t&&t.length?Fi(t[0]):n}function Hi(n){var t,e=n.children;return e&&(t=e.length)?Hi(e[t-1]):n}function Oi(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function Ii(n,t){var e=n.x+t[3],r=n.y+t[0],i=n.dx-t[1]-t[3],u=n.dy-t[0]-t[2];return 0>i&&(e+=i/2,i=0),0>u&&(r+=u/2,u=0),{x:e,y:r,dx:i,dy:u}}function Yi(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Zi(n){return n.rangeExtent?n.rangeExtent():Yi(n.range())}function Vi(n,t,e,r){var i=e(n[0],n[1]),u=r(t[0],t[1]);return function(n){return u(i(n))}}function Xi(n,t){var e,r=0,i=n.length-1,u=n[r],o=n[i];return u>o&&(e=r,r=i,i=e,e=u,u=o,o=e),n[r]=t.floor(u),n[i]=t.ceil(o),n}function $i(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:Sl}function Bi(n,t,e,r){var i=[],u=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]<n[0]&&(n=n.slice().reverse(),t=t.slice().reverse());++o<=a;)i.push(e(n[o-1],n[o])),u.push(r(t[o-1],t[o]));return function(t){var e=ao.bisect(n,t,1,a)-1;return u[e](i[e](t))}}function Wi(n,t,e,r){function i(){var i=Math.min(n.length,t.length)>2?Bi:Vi,l=r?Wr:Br;return o=i(n,t,l,e),a=i(t,n,l,Mr),u}function u(n){return o(n)}var o,a;return u.invert=function(n){return a(n)},u.domain=function(t){return arguments.length?(n=t.map(Number),i()):n},u.range=function(n){return arguments.length?(t=n,i()):t},u.rangeRound=function(n){return u.range(n).interpolate(Ur)},u.clamp=function(n){return arguments.length?(r=n,i()):r},u.interpolate=function(n){return arguments.length?(e=n,i()):e},u.ticks=function(t){return Qi(n,t)},u.tickFormat=function(t,e){return nu(n,t,e)},u.nice=function(t){return Gi(n,t),i()},u.copy=function(){return Wi(n,t,e,r)},i()}function Ji(n,t){return ao.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Gi(n,t){return Xi(n,$i(Ki(n,t)[2])),Xi(n,$i(Ki(n,t)[2])),n}function Ki(n,t){null==t&&(t=10);var e=Yi(n),r=e[1]-e[0],i=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),u=t/r*i;return.15>=u?i*=10:.35>=u?i*=5:.75>=u&&(i*=2),e[0]=Math.ceil(e[0]/i)*i,e[1]=Math.floor(e[1]/i)*i+.5*i,e[2]=i,e}function Qi(n,t){return ao.range.apply(ao,Ki(n,t))}function nu(n,t,e){var r=Ki(n,t);if(e){var i=ha.exec(e);if(i.shift(),"s"===i[8]){var u=ao.formatPrefix(Math.max(xo(r[0]),xo(r[1])));return i[7]||(i[7]="."+tu(u.scale(r[2]))),i[8]="f",e=ao.format(i.join("")),function(n){return e(u.scale(n))+u.symbol}}i[7]||(i[7]="."+eu(i[8],r)),e=i.join("")}else e=",."+tu(r[2])+"f";return ao.format(e)}function tu(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function eu(n,t){var e=tu(t[2]);return n in kl?Math.abs(e-tu(Math.max(xo(t[0]),xo(t[1]))))+ +("e"!==n):e-2*("%"===n)}function ru(n,t,e,r){function i(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function u(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(i(t))}return o.invert=function(t){return u(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(i)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(i)),o):t},o.nice=function(){var t=Xi(r.map(i),e?Math:El);return n.domain(t),r=t.map(u),o},o.ticks=function(){var n=Yi(r),o=[],a=n[0],l=n[1],c=Math.floor(i(a)),f=Math.ceil(i(l)),s=t%1?2:t;if(isFinite(f-c)){if(e){for(;f>c;c++)for(var h=1;s>h;h++)o.push(u(c)*h);o.push(u(c))}else for(o.push(u(c));c++<f;)for(var h=s-1;h>0;h--)o.push(u(c)*h);for(c=0;o[c]<a;c++);for(f=o.length;o[f-1]>l;f--);o=o.slice(c,f)}return o},o.tickFormat=function(n,e){if(!arguments.length)return Nl;arguments.length<2?e=Nl:"function"!=typeof e&&(e=ao.format(e));var r=Math.max(1,t*n/o.ticks().length);return function(n){var o=n/u(Math.round(i(n)));return t-.5>o*t&&(o*=t),r>=o?e(n):""}},o.copy=function(){return ru(n.copy(),t,e,r)},Ji(o,n)}function iu(n,t,e){function r(t){return n(i(t))}var i=uu(t),u=uu(1/t);return r.invert=function(t){return u(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(i)),r):e},r.ticks=function(n){return Qi(e,n)},r.tickFormat=function(n,t){return nu(e,n,t)},r.nice=function(n){return r.domain(Gi(e,n))},r.exponent=function(o){return arguments.length?(i=uu(t=o),u=uu(1/t),n.domain(e.map(i)),r):t},r.copy=function(){return iu(n.copy(),t,e)},Ji(r,n)}function uu(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function ou(n,t){function e(e){return u[((i.get(e)||("range"===t.t?i.set(e,n.push(e)):NaN))-1)%u.length]}function r(t,e){return ao.range(n.length).map(function(n){return t+e*n})}var i,u,o;return e.domain=function(r){if(!arguments.length)return n;n=[],i=new c;for(var u,o=-1,a=r.length;++o<a;)i.has(u=r[o])||i.set(u,n.push(u));return e[t.t].apply(e,t.a)},e.range=function(n){return arguments.length?(u=n,o=0,t={t:"range",a:arguments},e):u},e.rangePoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],c=i[1],f=n.length<2?(l=(l+c)/2,0):(c-l)/(n.length-1+a);return u=r(l+f*a/2,f),o=0,t={t:"rangePoints",a:arguments},e},e.rangeRoundPoints=function(i,a){arguments.length<2&&(a=0);var l=i[0],c=i[1],f=n.length<2?(l=c=Math.round((l+c)/2),0):(c-l)/(n.length-1+a)|0;return u=r(l+Math.round(f*a/2+(c-l-(n.length-1+a)*f)/2),f),o=0,t={t:"rangeRoundPoints",a:arguments},e},e.rangeBands=function(i,a,l){arguments.length<2&&(a=0),arguments.length<3&&(l=a);var c=i[1]<i[0],f=i[c-0],s=i[1-c],h=(s-f)/(n.length-a+2*l);return u=r(f+h*l,h),c&&u.reverse(),o=h*(1-a),t={t:"rangeBands",a:arguments},e},e.rangeRoundBands=function(i,a,l){arguments.length<2&&(a=0),arguments.length<3&&(l=a);var c=i[1]<i[0],f=i[c-0],s=i[1-c],h=Math.floor((s-f)/(n.length-a+2*l));return u=r(f+Math.round((s-f-(n.length-a)*h)/2),h),c&&u.reverse(),o=Math.round(h*(1-a)),t={t:"rangeRoundBands",a:arguments},e},e.rangeBand=function(){return o},e.rangeExtent=function(){return Yi(t.a[0])},e.copy=function(){return ou(n,t)},e.domain(n)}function au(n,t){function u(){var e=0,r=t.length;for(a=[];++e<r;)a[e-1]=ao.quantile(n,e/r);return o}function o(n){return isNaN(n=+n)?void 0:t[ao.bisect(a,n)]}var a;return o.domain=function(t){return arguments.length?(n=t.map(r).filter(i).sort(e),u()):n},o.range=function(n){return arguments.length?(t=n,u()):t},o.quantiles=function(){return a},o.invertExtent=function(e){return e=t.indexOf(e),0>e?[NaN,NaN]:[e>0?a[e-1]:n[0],e<a.length?a[e]:n[n.length-1]]},o.copy=function(){return au(n,t)},u()}function lu(n,t,e){function r(t){return e[Math.max(0,Math.min(o,Math.floor(u*(t-n))))]}function i(){return u=e.length/(t-n),o=e.length-1,r}var u,o;return r.domain=function(e){return arguments.length?(n=+e[0],t=+e[e.length-1],i()):[n,t]},r.range=function(n){return arguments.length?(e=n,i()):e},r.invertExtent=function(t){return t=e.indexOf(t),t=0>t?NaN:t/u+n,[t,t+1/u]},r.copy=function(){return lu(n,t,e)},i()}function cu(n,t){function e(e){return e>=e?t[ao.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return cu(n,t)},e}function fu(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Qi(n,t)},t.tickFormat=function(t,e){return nu(n,t,e)},t.copy=function(){return fu(n)},t}function su(){return 0}function hu(n){return n.innerRadius}function pu(n){return n.outerRadius}function gu(n){return n.startAngle}function vu(n){return n.endAngle}function du(n){return n&&n.padAngle}function yu(n,t,e,r){return(n-e)*t-(t-r)*n>0?0:1}function mu(n,t,e,r,i){var u=n[0]-t[0],o=n[1]-t[1],a=(i?r:-r)/Math.sqrt(u*u+o*o),l=a*o,c=-a*u,f=n[0]+l,s=n[1]+c,h=t[0]+l,p=t[1]+c,g=(f+h)/2,v=(s+p)/2,d=h-f,y=p-s,m=d*d+y*y,M=e-r,x=f*p-h*s,b=(0>y?-1:1)*Math.sqrt(Math.max(0,M*M*m-x*x)),_=(x*y-d*b)/m,w=(-x*d-y*b)/m,S=(x*y+d*b)/m,k=(-x*d+y*b)/m,N=_-g,E=w-v,A=S-g,C=k-v;return N*N+E*E>A*A+C*C&&(_=S,w=k),[[_-l,w-c],[_*e/M,w*e/M]]}function Mu(n){function t(t){function o(){c.push("M",u(n(f),a))}for(var l,c=[],f=[],s=-1,h=t.length,p=En(e),g=En(r);++s<h;)i.call(this,l=t[s],s)?f.push([+p.call(this,l,s),+g.call(this,l,s)]):f.length&&(o(),f=[]);return f.length&&o(),c.length?c.join(""):null}var e=Ce,r=ze,i=zt,u=xu,o=u.key,a=.7;return t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t.defined=function(n){return arguments.length?(i=n,t):i},t.interpolate=function(n){return arguments.length?(o="function"==typeof n?u=n:(u=Tl.get(n)||xu).key,t):o},t.tension=function(n){return arguments.length?(a=n,t):a},t}function xu(n){return n.length>1?n.join("L"):n+"Z"}function bu(n){return n.join("L")+"Z"}function _u(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t<e;)i.push("H",(r[0]+(r=n[t])[0])/2,"V",r[1]);return e>1&&i.push("H",r[0]),i.join("")}function wu(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t<e;)i.push("V",(r=n[t])[1],"H",r[0]);return i.join("")}function Su(n){for(var t=0,e=n.length,r=n[0],i=[r[0],",",r[1]];++t<e;)i.push("H",(r=n[t])[0],"V",r[1]);return i.join("")}function ku(n,t){return n.length<4?xu(n):n[1]+Au(n.slice(1,-1),Cu(n,t))}function Nu(n,t){return n.length<3?bu(n):n[0]+Au((n.push(n[0]),n),Cu([n[n.length-2]].concat(n,[n[1]]),t))}function Eu(n,t){return n.length<3?xu(n):n[0]+Au(n,Cu(n,t))}function Au(n,t){if(t.length<1||n.length!=t.length&&n.length!=t.length+2)return xu(n);var e=n.length!=t.length,r="",i=n[0],u=n[1],o=t[0],a=o,l=1;if(e&&(r+="Q"+(u[0]-2*o[0]/3)+","+(u[1]-2*o[1]/3)+","+u[0]+","+u[1],i=n[1],l=2),t.length>1){a=t[1],u=n[l],l++,r+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(u[0]-a[0])+","+(u[1]-a[1])+","+u[0]+","+u[1];for(var c=2;c<t.length;c++,l++)u=n[l],a=t[c],r+="S"+(u[0]-a[0])+","+(u[1]-a[1])+","+u[0]+","+u[1]}if(e){var f=n[l];r+="Q"+(u[0]+2*a[0]/3)+","+(u[1]+2*a[1]/3)+","+f[0]+","+f[1]}return r}function Cu(n,t){for(var e,r=[],i=(1-t)/2,u=n[0],o=n[1],a=1,l=n.length;++a<l;)e=u,u=o,o=n[a],r.push([i*(o[0]-e[0]),i*(o[1]-e[1])]);return r}function zu(n){if(n.length<3)return xu(n);var t=1,e=n.length,r=n[0],i=r[0],u=r[1],o=[i,i,i,(r=n[1])[0]],a=[u,u,u,r[1]],l=[i,",",u,"L",Ru(Pl,o),",",Ru(Pl,a)];for(n.push(n[e-1]);++t<=e;)r=n[t],o.shift(),o.push(r[0]),a.shift(),a.push(r[1]),Du(l,o,a);return n.pop(),l.push("L",r),l.join("")}function Lu(n){if(n.length<4)return xu(n);for(var t,e=[],r=-1,i=n.length,u=[0],o=[0];++r<3;)t=n[r],u.push(t[0]),o.push(t[1]);for(e.push(Ru(Pl,u)+","+Ru(Pl,o)),--r;++r<i;)t=n[r],u.shift(),u.push(t[0]),o.shift(),o.push(t[1]),Du(e,u,o);return e.join("")}function qu(n){for(var t,e,r=-1,i=n.length,u=i+4,o=[],a=[];++r<4;)e=n[r%i],o.push(e[0]),a.push(e[1]);for(t=[Ru(Pl,o),",",Ru(Pl,a)],--r;++r<u;)e=n[r%i],o.shift(),o.push(e[0]),a.shift(),a.push(e[1]),Du(t,o,a);return t.join("")}function Tu(n,t){var e=n.length-1;if(e)for(var r,i,u=n[0][0],o=n[0][1],a=n[e][0]-u,l=n[e][1]-o,c=-1;++c<=e;)r=n[c],i=c/e,r[0]=t*r[0]+(1-t)*(u+i*a),r[1]=t*r[1]+(1-t)*(o+i*l);return zu(n)}function Ru(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]+n[3]*t[3]}function Du(n,t,e){n.push("C",Ru(Rl,t),",",Ru(Rl,e),",",Ru(Dl,t),",",Ru(Dl,e),",",Ru(Pl,t),",",Ru(Pl,e))}function Pu(n,t){return(t[1]-n[1])/(t[0]-n[0])}function Uu(n){for(var t=0,e=n.length-1,r=[],i=n[0],u=n[1],o=r[0]=Pu(i,u);++t<e;)r[t]=(o+(o=Pu(i=u,u=n[t+1])))/2;return r[t]=o,r}function ju(n){for(var t,e,r,i,u=[],o=Uu(n),a=-1,l=n.length-1;++a<l;)t=Pu(n[a],n[a+1]),xo(t)<Uo?o[a]=o[a+1]=0:(e=o[a]/t,r=o[a+1]/t,i=e*e+r*r,i>9&&(i=3*t/Math.sqrt(i),o[a]=i*e,o[a+1]=i*r));for(a=-1;++a<=l;)i=(n[Math.min(l,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),u.push([i||0,o[a]*i||0]);return u}function Fu(n){return n.length<3?xu(n):n[0]+Au(n,ju(n))}function Hu(n){for(var t,e,r,i=-1,u=n.length;++i<u;)t=n[i],e=t[0],r=t[1]-Io,t[0]=e*Math.cos(r),t[1]=e*Math.sin(r);return n}function Ou(n){function t(t){function l(){v.push("M",a(n(y),s),f,c(n(d.reverse()),s),"Z")}for(var h,p,g,v=[],d=[],y=[],m=-1,M=t.length,x=En(e),b=En(i),_=e===r?function(){
return p}:En(r),w=i===u?function(){return g}:En(u);++m<M;)o.call(this,h=t[m],m)?(d.push([p=+x.call(this,h,m),g=+b.call(this,h,m)]),y.push([+_.call(this,h,m),+w.call(this,h,m)])):d.length&&(l(),d=[],y=[]);return d.length&&l(),v.length?v.join(""):null}var e=Ce,r=Ce,i=0,u=ze,o=zt,a=xu,l=a.key,c=a,f="L",s=.7;return t.x=function(n){return arguments.length?(e=r=n,t):r},t.x0=function(n){return arguments.length?(e=n,t):e},t.x1=function(n){return arguments.length?(r=n,t):r},t.y=function(n){return arguments.length?(i=u=n,t):u},t.y0=function(n){return arguments.length?(i=n,t):i},t.y1=function(n){return arguments.length?(u=n,t):u},t.defined=function(n){return arguments.length?(o=n,t):o},t.interpolate=function(n){return arguments.length?(l="function"==typeof n?a=n:(a=Tl.get(n)||xu).key,c=a.reverse||a,f=a.closed?"M":"L",t):l},t.tension=function(n){return arguments.length?(s=n,t):s},t}function Iu(n){return n.radius}function Yu(n){return[n.x,n.y]}function Zu(n){return function(){var t=n.apply(this,arguments),e=t[0],r=t[1]-Io;return[e*Math.cos(r),e*Math.sin(r)]}}function Vu(){return 64}function Xu(){return"circle"}function $u(n){var t=Math.sqrt(n/Fo);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function Bu(n){return function(){var t,e,r;(t=this[n])&&(r=t[e=t.active])&&(r.timer.c=null,r.timer.t=NaN,--t.count?delete t[e]:delete this[n],t.active+=.5,r.event&&r.event.interrupt.call(this,this.__data__,r.index))}}function Wu(n,t,e){return ko(n,Yl),n.namespace=t,n.id=e,n}function Ju(n,t,e,r){var i=n.id,u=n.namespace;return Y(n,"function"==typeof e?function(n,o,a){n[u][i].tween.set(t,r(e.call(n,n.__data__,o,a)))}:(e=r(e),function(n){n[u][i].tween.set(t,e)}))}function Gu(n){return null==n&&(n=""),function(){this.textContent=n}}function Ku(n){return null==n?"__transition__":"__transition_"+n+"__"}function Qu(n,t,e,r,i){function u(n){var t=v.delay;return f.t=t+l,n>=t?o(n-t):void(f.c=o)}function o(e){var i=g.active,u=g[i];u&&(u.timer.c=null,u.timer.t=NaN,--g.count,delete g[i],u.event&&u.event.interrupt.call(n,n.__data__,u.index));for(var o in g)if(r>+o){var c=g[o];c.timer.c=null,c.timer.t=NaN,--g.count,delete g[o]}f.c=a,qn(function(){return f.c&&a(e||1)&&(f.c=null,f.t=NaN),1},0,l),g.active=r,v.event&&v.event.start.call(n,n.__data__,t),p=[],v.tween.forEach(function(e,r){(r=r.call(n,n.__data__,t))&&p.push(r)}),h=v.ease,s=v.duration}function a(i){for(var u=i/s,o=h(u),a=p.length;a>0;)p[--a].call(n,o);return u>=1?(v.event&&v.event.end.call(n,n.__data__,t),--g.count?delete g[r]:delete n[e],1):void 0}var l,f,s,h,p,g=n[e]||(n[e]={active:0,count:0}),v=g[r];v||(l=i.time,f=qn(u,0,l),v=g[r]={tween:new c,time:l,timer:f,delay:i.delay,duration:i.duration,ease:i.ease,index:t},i=null,++g.count)}function no(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate("+(isFinite(r)?r:e(n))+",0)"})}function to(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate(0,"+(isFinite(r)?r:e(n))+")"})}function eo(n){return n.toISOString()}function ro(n,t,e){function r(t){return n(t)}function i(n,e){var r=n[1]-n[0],i=r/e,u=ao.bisect(Kl,i);return u==Kl.length?[t.year,Ki(n.map(function(n){return n/31536e6}),e)[2]]:u?t[i/Kl[u-1]<Kl[u]/i?u-1:u]:[tc,Ki(n,e)[2]]}return r.invert=function(t){return io(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain(t),r):n.domain().map(io)},r.nice=function(n,t){function e(e){return!isNaN(e)&&!n.range(e,io(+e+1),t).length}var u=r.domain(),o=Yi(u),a=null==n?i(o,10):"number"==typeof n&&i(o,n);return a&&(n=a[0],t=a[1]),r.domain(Xi(u,t>1?{floor:function(t){for(;e(t=n.floor(t));)t=io(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=io(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Yi(r.domain()),u=null==n?i(e,10):"number"==typeof n?i(e,n):!n.range&&[{range:n},t];return u&&(n=u[0],t=u[1]),n.range(e[0],io(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return ro(n.copy(),t,e)},Ji(r,n)}function io(n){return new Date(n)}function uo(n){return JSON.parse(n.responseText)}function oo(n){var t=fo.createRange();return t.selectNode(fo.body),t.createContextualFragment(n.responseText)}var ao={version:"3.5.17"},lo=[].slice,co=function(n){return lo.call(n)},fo=this.document;if(fo)try{co(fo.documentElement.childNodes)[0].nodeType}catch(so){co=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}if(Date.now||(Date.now=function(){return+new Date}),fo)try{fo.createElement("DIV").style.setProperty("opacity",0,"")}catch(ho){var po=this.Element.prototype,go=po.setAttribute,vo=po.setAttributeNS,yo=this.CSSStyleDeclaration.prototype,mo=yo.setProperty;po.setAttribute=function(n,t){go.call(this,n,t+"")},po.setAttributeNS=function(n,t,e){vo.call(this,n,t,e+"")},yo.setProperty=function(n,t,e){mo.call(this,n,t+"",e)}}ao.ascending=e,ao.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:NaN},ao.min=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i<u;)if(null!=(r=n[i])&&r>=r){e=r;break}for(;++i<u;)null!=(r=n[i])&&e>r&&(e=r)}else{for(;++i<u;)if(null!=(r=t.call(n,n[i],i))&&r>=r){e=r;break}for(;++i<u;)null!=(r=t.call(n,n[i],i))&&e>r&&(e=r)}return e},ao.max=function(n,t){var e,r,i=-1,u=n.length;if(1===arguments.length){for(;++i<u;)if(null!=(r=n[i])&&r>=r){e=r;break}for(;++i<u;)null!=(r=n[i])&&r>e&&(e=r)}else{for(;++i<u;)if(null!=(r=t.call(n,n[i],i))&&r>=r){e=r;break}for(;++i<u;)null!=(r=t.call(n,n[i],i))&&r>e&&(e=r)}return e},ao.extent=function(n,t){var e,r,i,u=-1,o=n.length;if(1===arguments.length){for(;++u<o;)if(null!=(r=n[u])&&r>=r){e=i=r;break}for(;++u<o;)null!=(r=n[u])&&(e>r&&(e=r),r>i&&(i=r))}else{for(;++u<o;)if(null!=(r=t.call(n,n[u],u))&&r>=r){e=i=r;break}for(;++u<o;)null!=(r=t.call(n,n[u],u))&&(e>r&&(e=r),r>i&&(i=r))}return[e,i]},ao.sum=function(n,t){var e,r=0,u=n.length,o=-1;if(1===arguments.length)for(;++o<u;)i(e=+n[o])&&(r+=e);else for(;++o<u;)i(e=+t.call(n,n[o],o))&&(r+=e);return r},ao.mean=function(n,t){var e,u=0,o=n.length,a=-1,l=o;if(1===arguments.length)for(;++a<o;)i(e=r(n[a]))?u+=e:--l;else for(;++a<o;)i(e=r(t.call(n,n[a],a)))?u+=e:--l;return l?u/l:void 0},ao.quantile=function(n,t){var e=(n.length-1)*t+1,r=Math.floor(e),i=+n[r-1],u=e-r;return u?i+u*(n[r]-i):i},ao.median=function(n,t){var u,o=[],a=n.length,l=-1;if(1===arguments.length)for(;++l<a;)i(u=r(n[l]))&&o.push(u);else for(;++l<a;)i(u=r(t.call(n,n[l],l)))&&o.push(u);return o.length?ao.quantile(o.sort(e),.5):void 0},ao.variance=function(n,t){var e,u,o=n.length,a=0,l=0,c=-1,f=0;if(1===arguments.length)for(;++c<o;)i(e=r(n[c]))&&(u=e-a,a+=u/++f,l+=u*(e-a));else for(;++c<o;)i(e=r(t.call(n,n[c],c)))&&(u=e-a,a+=u/++f,l+=u*(e-a));return f>1?l/(f-1):void 0},ao.deviation=function(){var n=ao.variance.apply(this,arguments);return n?Math.sqrt(n):n};var Mo=u(e);ao.bisectLeft=Mo.left,ao.bisect=ao.bisectRight=Mo.right,ao.bisector=function(n){return u(1===n.length?function(t,r){return e(n(t),r)}:n)},ao.shuffle=function(n,t,e){(u=arguments.length)<3&&(e=n.length,2>u&&(t=0));for(var r,i,u=e-t;u;)i=Math.random()*u--|0,r=n[u+t],n[u+t]=n[i+t],n[i+t]=r;return n},ao.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},ao.pairs=function(n){for(var t,e=0,r=n.length-1,i=n[0],u=new Array(0>r?0:r);r>e;)u[e]=[t=i,i=n[++e]];return u},ao.transpose=function(n){if(!(i=n.length))return[];for(var t=-1,e=ao.min(n,o),r=new Array(e);++t<e;)for(var i,u=-1,a=r[t]=new Array(i);++u<i;)a[u]=n[u][t];return r},ao.zip=function(){return ao.transpose(arguments)},ao.keys=function(n){var t=[];for(var e in n)t.push(e);return t},ao.values=function(n){var t=[];for(var e in n)t.push(n[e]);return t},ao.entries=function(n){var t=[];for(var e in n)t.push({key:e,value:n[e]});return t},ao.merge=function(n){for(var t,e,r,i=n.length,u=-1,o=0;++u<i;)o+=n[u].length;for(e=new Array(o);--i>=0;)for(r=n[i],t=r.length;--t>=0;)e[--o]=r[t];return e};var xo=Math.abs;ao.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),(t-n)/e===1/0)throw new Error("infinite range");var r,i=[],u=a(xo(e)),o=-1;if(n*=u,t*=u,e*=u,0>e)for(;(r=n+e*++o)>t;)i.push(r/u);else for(;(r=n+e*++o)<t;)i.push(r/u);return i},ao.map=function(n,t){var e=new c;if(n instanceof c)n.forEach(function(n,t){e.set(n,t)});else if(Array.isArray(n)){var r,i=-1,u=n.length;if(1===arguments.length)for(;++i<u;)e.set(i,n[i]);else for(;++i<u;)e.set(t.call(n,r=n[i],i),r)}else for(var o in n)e.set(o,n[o]);return e};var bo="__proto__",_o="\x00";l(c,{has:h,get:function(n){return this._[f(n)]},set:function(n,t){return this._[f(n)]=t},remove:p,keys:g,values:function(){var n=[];for(var t in this._)n.push(this._[t]);return n},entries:function(){var n=[];for(var t in this._)n.push({key:s(t),value:this._[t]});return n},size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,s(t),this._[t])}}),ao.nest=function(){function n(t,o,a){if(a>=u.length)return r?r.call(i,o):e?o.sort(e):o;for(var l,f,s,h,p=-1,g=o.length,v=u[a++],d=new c;++p<g;)(h=d.get(l=v(f=o[p])))?h.push(f):d.set(l,[f]);return t?(f=t(),s=function(e,r){f.set(e,n(t,r,a))}):(f={},s=function(e,r){f[e]=n(t,r,a)}),d.forEach(s),f}function t(n,e){if(e>=u.length)return n;var r=[],i=o[e++];return n.forEach(function(n,i){r.push({key:n,values:t(i,e)})}),i?r.sort(function(n,t){return i(n.key,t.key)}):r}var e,r,i={},u=[],o=[];return i.map=function(t,e){return n(e,t,0)},i.entries=function(e){return t(n(ao.map,e,0),0)},i.key=function(n){return u.push(n),i},i.sortKeys=function(n){return o[u.length-1]=n,i},i.sortValues=function(n){return e=n,i},i.rollup=function(n){return r=n,i},i},ao.set=function(n){var t=new y;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},l(y,{has:h,add:function(n){return this._[f(n+="")]=!0,n},remove:p,values:g,size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,s(t))}}),ao.behavior={},ao.rebind=function(n,t){for(var e,r=1,i=arguments.length;++r<i;)n[e=arguments[r]]=M(n,t,t[e]);return n};var wo=["webkit","ms","moz","Moz","o","O"];ao.dispatch=function(){for(var n=new _,t=-1,e=arguments.length;++t<e;)n[arguments[t]]=w(n);return n},_.prototype.on=function(n,t){var e=n.indexOf("."),r="";if(e>=0&&(r=n.slice(e+1),n=n.slice(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},ao.event=null,ao.requote=function(n){return n.replace(So,"\\$&")};var So=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ko={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},No=function(n,t){return t.querySelector(n)},Eo=function(n,t){return t.querySelectorAll(n)},Ao=function(n,t){var e=n.matches||n[x(n,"matchesSelector")];return(Ao=function(n,t){return e.call(n,t)})(n,t)};"function"==typeof Sizzle&&(No=function(n,t){return Sizzle(n,t)[0]||null},Eo=Sizzle,Ao=Sizzle.matchesSelector),ao.selection=function(){return ao.select(fo.documentElement)};var Co=ao.selection.prototype=[];Co.select=function(n){var t,e,r,i,u=[];n=A(n);for(var o=-1,a=this.length;++o<a;){u.push(t=[]),t.parentNode=(r=this[o]).parentNode;for(var l=-1,c=r.length;++l<c;)(i=r[l])?(t.push(e=n.call(i,i.__data__,l,o)),e&&"__data__"in i&&(e.__data__=i.__data__)):t.push(null)}return E(u)},Co.selectAll=function(n){var t,e,r=[];n=C(n);for(var i=-1,u=this.length;++i<u;)for(var o=this[i],a=-1,l=o.length;++a<l;)(e=o[a])&&(r.push(t=co(n.call(e,e.__data__,a,i))),t.parentNode=e);return E(r)};var zo="http://www.w3.org/1999/xhtml",Lo={svg:"http://www.w3.org/2000/svg",xhtml:zo,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};ao.ns={prefix:Lo,qualify:function(n){var t=n.indexOf(":"),e=n;return t>=0&&"xmlns"!==(e=n.slice(0,t))&&(n=n.slice(t+1)),Lo.hasOwnProperty(e)?{space:Lo[e],local:n}:n}},Co.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=ao.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(z(t,n[t]));return this}return this.each(z(n,t))},Co.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=T(n)).length,i=-1;if(t=e.classList){for(;++i<r;)if(!t.contains(n[i]))return!1}else for(t=e.getAttribute("class");++i<r;)if(!q(n[i]).test(t))return!1;return!0}for(t in n)this.each(R(t,n[t]));return this}return this.each(R(n,t))},Co.style=function(n,e,r){var i=arguments.length;if(3>i){if("string"!=typeof n){2>i&&(e="");for(r in n)this.each(P(r,n[r],e));return this}if(2>i){var u=this.node();return t(u).getComputedStyle(u,null).getPropertyValue(n)}r=""}return this.each(P(n,e,r))},Co.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(U(t,n[t]));return this}return this.each(U(n,t))},Co.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},Co.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},Co.append=function(n){return n=j(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},Co.insert=function(n,t){return n=j(n),t=A(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},Co.remove=function(){return this.each(F)},Co.data=function(n,t){function e(n,e){var r,i,u,o=n.length,s=e.length,h=Math.min(o,s),p=new Array(s),g=new Array(s),v=new Array(o);if(t){var d,y=new c,m=new Array(o);for(r=-1;++r<o;)(i=n[r])&&(y.has(d=t.call(i,i.__data__,r))?v[r]=i:y.set(d,i),m[r]=d);for(r=-1;++r<s;)(i=y.get(d=t.call(e,u=e[r],r)))?i!==!0&&(p[r]=i,i.__data__=u):g[r]=H(u),y.set(d,!0);for(r=-1;++r<o;)r in m&&y.get(m[r])!==!0&&(v[r]=n[r])}else{for(r=-1;++r<h;)i=n[r],u=e[r],i?(i.__data__=u,p[r]=i):g[r]=H(u);for(;s>r;++r)g[r]=H(e[r]);for(;o>r;++r)v[r]=n[r]}g.update=p,g.parentNode=p.parentNode=v.parentNode=n.parentNode,a.push(g),l.push(p),f.push(v)}var r,i,u=-1,o=this.length;if(!arguments.length){for(n=new Array(o=(r=this[0]).length);++u<o;)(i=r[u])&&(n[u]=i.__data__);return n}var a=Z([]),l=E([]),f=E([]);if("function"==typeof n)for(;++u<o;)e(r=this[u],n.call(r,r.parentNode.__data__,u));else for(;++u<o;)e(r=this[u],n);return l.enter=function(){return a},l.exit=function(){return f},l},Co.datum=function(n){return arguments.length?this.property("__data__",n):this.property("__data__")},Co.filter=function(n){var t,e,r,i=[];"function"!=typeof n&&(n=O(n));for(var u=0,o=this.length;o>u;u++){i.push(t=[]),t.parentNode=(e=this[u]).parentNode;for(var a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return E(i)},Co.order=function(){for(var n=-1,t=this.length;++n<t;)for(var e,r=this[n],i=r.length-1,u=r[i];--i>=0;)(e=r[i])&&(u&&u!==e.nextSibling&&u.parentNode.insertBefore(e,u),u=e);return this},Co.sort=function(n){n=I.apply(this,arguments);for(var t=-1,e=this.length;++t<e;)this[t].sort(n);return this.order()},Co.each=function(n){return Y(this,function(t,e,r){n.call(t,t.__data__,e,r)})},Co.call=function(n){var t=co(arguments);return n.apply(t[0]=this,t),this},Co.empty=function(){return!this.node()},Co.node=function(){for(var n=0,t=this.length;t>n;n++)for(var e=this[n],r=0,i=e.length;i>r;r++){var u=e[r];if(u)return u}return null},Co.size=function(){var n=0;return Y(this,function(){++n}),n};var qo=[];ao.selection.enter=Z,ao.selection.enter.prototype=qo,qo.append=Co.append,qo.empty=Co.empty,qo.node=Co.node,qo.call=Co.call,qo.size=Co.size,qo.select=function(n){for(var t,e,r,i,u,o=[],a=-1,l=this.length;++a<l;){r=(i=this[a]).update,o.push(t=[]),t.parentNode=i.parentNode;for(var c=-1,f=i.length;++c<f;)(u=i[c])?(t.push(r[c]=e=n.call(i.parentNode,u.__data__,c,a)),e.__data__=u.__data__):t.push(null)}return E(o)},qo.insert=function(n,t){return arguments.length<2&&(t=V(this)),Co.insert.call(this,n,t)},ao.select=function(t){var e;return"string"==typeof t?(e=[No(t,fo)],e.parentNode=fo.documentElement):(e=[t],e.parentNode=n(t)),E([e])},ao.selectAll=function(n){var t;return"string"==typeof n?(t=co(Eo(n,fo)),t.parentNode=fo.documentElement):(t=co(n),t.parentNode=null),E([t])},Co.on=function(n,t,e){var r=arguments.length;if(3>r){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(X(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(X(n,t,e))};var To=ao.map({mouseenter:"mouseover",mouseleave:"mouseout"});fo&&To.forEach(function(n){"on"+n in fo&&To.remove(n)});var Ro,Do=0;ao.mouse=function(n){return J(n,k())};var Po=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;ao.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=k().changedTouches),t)for(var r,i=0,u=t.length;u>i;++i)if((r=t[i]).identifier===e)return J(n,r)},ao.behavior.drag=function(){function n(){this.on("mousedown.drag",u).on("touchstart.drag",o)}function e(n,t,e,u,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-M[0],e=r[1]-M[1],g|=n|e,M=r,p({type:"drag",x:r[0]+c[0],y:r[1]+c[1],dx:n,dy:e}))}function l(){t(h,v)&&(y.on(u+d,null).on(o+d,null),m(g),p({type:"dragend"}))}var c,f=this,s=ao.event.target.correspondingElement||ao.event.target,h=f.parentNode,p=r.of(f,arguments),g=0,v=n(),d=".drag"+(null==v?"":"-"+v),y=ao.select(e(s)).on(u+d,a).on(o+d,l),m=W(s),M=t(h,v);i?(c=i.apply(f,arguments),c=[c.x-M[0],c.y-M[1]]):c=[0,0],p({type:"dragstart"})}}var r=N(n,"drag","dragstart","dragend"),i=null,u=e(b,ao.mouse,t,"mousemove","mouseup"),o=e(G,ao.touch,m,"touchmove","touchend");return n.origin=function(t){return arguments.length?(i=t,n):i},ao.rebind(n,r,"on")},ao.touches=function(n,t){return arguments.length<2&&(t=k().touches),t?co(t).map(function(t){var e=J(n,t);return e.identifier=t.identifier,e}):[]};var Uo=1e-6,jo=Uo*Uo,Fo=Math.PI,Ho=2*Fo,Oo=Ho-Uo,Io=Fo/2,Yo=Fo/180,Zo=180/Fo,Vo=Math.SQRT2,Xo=2,$o=4;ao.interpolateZoom=function(n,t){var e,r,i=n[0],u=n[1],o=n[2],a=t[0],l=t[1],c=t[2],f=a-i,s=l-u,h=f*f+s*s;if(jo>h)r=Math.log(c/o)/Vo,e=function(n){return[i+n*f,u+n*s,o*Math.exp(Vo*n*r)]};else{var p=Math.sqrt(h),g=(c*c-o*o+$o*h)/(2*o*Xo*p),v=(c*c-o*o-$o*h)/(2*c*Xo*p),d=Math.log(Math.sqrt(g*g+1)-g),y=Math.log(Math.sqrt(v*v+1)-v);r=(y-d)/Vo,e=function(n){var t=n*r,e=rn(d),a=o/(Xo*p)*(e*un(Vo*t+d)-en(d));return[i+a*f,u+a*s,o*e/rn(Vo*t+d)]}}return e.duration=1e3*r,e},ao.behavior.zoom=function(){function n(n){n.on(L,s).on(Wo+".zoom",p).on("dblclick.zoom",g).on(R,h)}function e(n){return[(n[0]-k.x)/k.k,(n[1]-k.y)/k.k]}function r(n){return[n[0]*k.k+k.x,n[1]*k.k+k.y]}function i(n){k.k=Math.max(A[0],Math.min(A[1],n))}function u(n,t){t=r(t),k.x+=n[0]-t[0],k.y+=n[1]-t[1]}function o(t,e,r,o){t.__chart__={x:k.x,y:k.y,k:k.k},i(Math.pow(2,o)),u(d=e,r),t=ao.select(t),C>0&&(t=t.transition().duration(C)),t.call(n.event)}function a(){b&&b.domain(x.range().map(function(n){return(n-k.x)/k.k}).map(x.invert)),w&&w.domain(_.range().map(function(n){return(n-k.y)/k.k}).map(_.invert))}function l(n){z++||n({type:"zoomstart"})}function c(n){a(),n({type:"zoom",scale:k.k,translate:[k.x,k.y]})}function f(n){--z||(n({type:"zoomend"}),d=null)}function s(){function n(){a=1,u(ao.mouse(i),h),c(o)}function r(){s.on(q,null).on(T,null),p(a),f(o)}var i=this,o=D.of(i,arguments),a=0,s=ao.select(t(i)).on(q,n).on(T,r),h=e(ao.mouse(i)),p=W(i);Il.call(i),l(o)}function h(){function n(){var n=ao.touches(g);return p=k.k,n.forEach(function(n){n.identifier in d&&(d[n.identifier]=e(n))}),n}function t(){var t=ao.event.target;ao.select(t).on(x,r).on(b,a),_.push(t);for(var e=ao.event.changedTouches,i=0,u=e.length;u>i;++i)d[e[i].identifier]=null;var l=n(),c=Date.now();if(1===l.length){if(500>c-M){var f=l[0];o(g,f,d[f.identifier],Math.floor(Math.log(k.k)/Math.LN2)+1),S()}M=c}else if(l.length>1){var f=l[0],s=l[1],h=f[0]-s[0],p=f[1]-s[1];y=h*h+p*p}}function r(){var n,t,e,r,o=ao.touches(g);Il.call(g);for(var a=0,l=o.length;l>a;++a,r=null)if(e=o[a],r=d[e.identifier]){if(t)break;n=e,t=r}if(r){var f=(f=e[0]-n[0])*f+(f=e[1]-n[1])*f,s=y&&Math.sqrt(f/y);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+r[0])/2,(t[1]+r[1])/2],i(s*p)}M=null,u(n,t),c(v)}function a(){if(ao.event.touches.length){for(var t=ao.event.changedTouches,e=0,r=t.length;r>e;++e)delete d[t[e].identifier];for(var i in d)return void n()}ao.selectAll(_).on(m,null),w.on(L,s).on(R,h),N(),f(v)}var p,g=this,v=D.of(g,arguments),d={},y=0,m=".zoom-"+ao.event.changedTouches[0].identifier,x="touchmove"+m,b="touchend"+m,_=[],w=ao.select(g),N=W(g);t(),l(v),w.on(L,null).on(R,t)}function p(){var n=D.of(this,arguments);m?clearTimeout(m):(Il.call(this),v=e(d=y||ao.mouse(this)),l(n)),m=setTimeout(function(){m=null,f(n)},50),S(),i(Math.pow(2,.002*Bo())*k.k),u(d,v),c(n)}function g(){var n=ao.mouse(this),t=Math.log(k.k)/Math.LN2;o(this,n,e(n),ao.event.shiftKey?Math.ceil(t)-1:Math.floor(t)+1)}var v,d,y,m,M,x,b,_,w,k={x:0,y:0,k:1},E=[960,500],A=Jo,C=250,z=0,L="mousedown.zoom",q="mousemove.zoom",T="mouseup.zoom",R="touchstart.zoom",D=N(n,"zoomstart","zoom","zoomend");return Wo||(Wo="onwheel"in fo?(Bo=function(){return-ao.event.deltaY*(ao.event.deltaMode?120:1)},"wheel"):"onmousewheel"in fo?(Bo=function(){return ao.event.wheelDelta},"mousewheel"):(Bo=function(){return-ao.event.detail},"MozMousePixelScroll")),n.event=function(n){n.each(function(){var n=D.of(this,arguments),t=k;Hl?ao.select(this).transition().each("start.zoom",function(){k=this.__chart__||{x:0,y:0,k:1},l(n)}).tween("zoom:zoom",function(){var e=E[0],r=E[1],i=d?d[0]:e/2,u=d?d[1]:r/2,o=ao.interpolateZoom([(i-k.x)/k.k,(u-k.y)/k.k,e/k.k],[(i-t.x)/t.k,(u-t.y)/t.k,e/t.k]);return function(t){var r=o(t),a=e/r[2];this.__chart__=k={x:i-r[0]*a,y:u-r[1]*a,k:a},c(n)}}).each("interrupt.zoom",function(){f(n)}).each("end.zoom",function(){f(n)}):(this.__chart__=k,l(n),c(n),f(n))})},n.translate=function(t){return arguments.length?(k={x:+t[0],y:+t[1],k:k.k},a(),n):[k.x,k.y]},n.scale=function(t){return arguments.length?(k={x:k.x,y:k.y,k:null},i(+t),a(),n):k.k},n.scaleExtent=function(t){return arguments.length?(A=null==t?Jo:[+t[0],+t[1]],n):A},n.center=function(t){return arguments.length?(y=t&&[+t[0],+t[1]],n):y},n.size=function(t){return arguments.length?(E=t&&[+t[0],+t[1]],n):E},n.duration=function(t){return arguments.length?(C=+t,n):C},n.x=function(t){return arguments.length?(b=t,x=t.copy(),k={x:0,y:0,k:1},n):b},n.y=function(t){return arguments.length?(w=t,_=t.copy(),k={x:0,y:0,k:1},n):w},ao.rebind(n,D,"on")};var Bo,Wo,Jo=[0,1/0];ao.color=an,an.prototype.toString=function(){return this.rgb()+""},ao.hsl=ln;var Go=ln.prototype=new an;Go.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,this.l/n)},Go.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new ln(this.h,this.s,n*this.l)},Go.rgb=function(){return cn(this.h,this.s,this.l)},ao.hcl=fn;var Ko=fn.prototype=new an;Ko.brighter=function(n){return new fn(this.h,this.c,Math.min(100,this.l+Qo*(arguments.length?n:1)))},Ko.darker=function(n){return new fn(this.h,this.c,Math.max(0,this.l-Qo*(arguments.length?n:1)))},Ko.rgb=function(){return sn(this.h,this.c,this.l).rgb()},ao.lab=hn;var Qo=18,na=.95047,ta=1,ea=1.08883,ra=hn.prototype=new an;ra.brighter=function(n){return new hn(Math.min(100,this.l+Qo*(arguments.length?n:1)),this.a,this.b)},ra.darker=function(n){return new hn(Math.max(0,this.l-Qo*(arguments.length?n:1)),this.a,this.b)},ra.rgb=function(){return pn(this.l,this.a,this.b)},ao.rgb=mn;var ia=mn.prototype=new an;ia.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,i=30;return t||e||r?(t&&i>t&&(t=i),e&&i>e&&(e=i),r&&i>r&&(r=i),new mn(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new mn(i,i,i)},ia.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new mn(n*this.r,n*this.g,n*this.b)},ia.hsl=function(){return wn(this.r,this.g,this.b)},ia.toString=function(){return"#"+bn(this.r)+bn(this.g)+bn(this.b)};var ua=ao.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ua.forEach(function(n,t){ua.set(n,Mn(t))}),ao.functor=En,ao.xhr=An(m),ao.dsv=function(n,t){function e(n,e,u){arguments.length<3&&(u=e,e=null);var o=Cn(n,t,null==e?r:i(e),u);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:i(n)):e},o}function r(n){return e.parse(n.responseText)}function i(n){return function(t){return e.parse(t.responseText,n)}}function u(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),l=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var i=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(i(n),e)}:i})},e.parseRows=function(n,t){function e(){if(f>=c)return o;if(i)return i=!1,u;var t=f;if(34===n.charCodeAt(t)){for(var e=t;e++<c;)if(34===n.charCodeAt(e)){if(34!==n.charCodeAt(e+1))break;++e}f=e+2;var r=n.charCodeAt(e+1);return 13===r?(i=!0,10===n.charCodeAt(e+2)&&++f):10===r&&(i=!0),n.slice(t+1,e).replace(/""/g,'"')}for(;c>f;){var r=n.charCodeAt(f++),a=1;if(10===r)i=!0;else if(13===r)i=!0,10===n.charCodeAt(f)&&(++f,++a);else if(r!==l)continue;return n.slice(t,f-a)}return n.slice(t)}for(var r,i,u={},o={},a=[],c=n.length,f=0,s=0;(r=e())!==o;){for(var h=[];r!==u&&r!==o;)h.push(r),r=e();t&&null==(h=t(h,s++))||a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new y,i=[];return t.forEach(function(n){for(var t in n)r.has(t)||i.push(r.add(t))}),[i.map(o).join(n)].concat(t.map(function(t){return i.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(u).join("\n")},e},ao.csv=ao.dsv(",","text/csv"),ao.tsv=ao.dsv("	","text/tab-separated-values");var oa,aa,la,ca,fa=this[x(this,"requestAnimationFrame")]||function(n){setTimeout(n,17)};ao.timer=function(){qn.apply(this,arguments)},ao.timer.flush=function(){Rn(),Dn()},ao.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var sa=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Un);ao.formatPrefix=function(n,t){var e=0;return(n=+n)&&(0>n&&(n*=-1),t&&(n=ao.round(n,Pn(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),sa[8+e/3]};var ha=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,pa=ao.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=ao.round(n,Pn(n,t))).toFixed(Math.max(0,Math.min(20,Pn(n*(1+1e-15),t))))}}),ga=ao.time={},va=Date;Hn.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){da.setUTCDate.apply(this._,arguments)},setDay:function(){da.setUTCDay.apply(this._,arguments)},setFullYear:function(){da.setUTCFullYear.apply(this._,arguments)},setHours:function(){da.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){da.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){da.setUTCMinutes.apply(this._,arguments)},setMonth:function(){da.setUTCMonth.apply(this._,arguments)},setSeconds:function(){da.setUTCSeconds.apply(this._,arguments)},setTime:function(){da.setTime.apply(this._,arguments)}};var da=Date.prototype;ga.year=On(function(n){return n=ga.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),ga.years=ga.year.range,ga.years.utc=ga.year.utc.range,ga.day=On(function(n){var t=new va(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),ga.days=ga.day.range,ga.days.utc=ga.day.utc.range,ga.dayOfYear=function(n){var t=ga.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=ga[n]=On(function(n){return(n=ga.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});ga[n+"s"]=e.range,ga[n+"s"].utc=e.utc.range,ga[n+"OfYear"]=function(n){var e=ga.year(n).getDay();return Math.floor((ga.dayOfYear(n)+(e+t)%7)/7)}}),ga.week=ga.sunday,ga.weeks=ga.sunday.range,ga.weeks.utc=ga.sunday.utc.range,ga.weekOfYear=ga.sundayOfYear;var ya={"-":"",_:" ",0:"0"},ma=/^\s*\d+/,Ma=/^%/;ao.locale=function(n){return{numberFormat:jn(n),timeFormat:Yn(n)}};var xa=ao.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ao.format=xa.numberFormat,ao.geo={},ft.prototype={s:0,t:0,add:function(n){st(n,this.t,ba),st(ba.s,this.s,this),this.s?this.t+=ba.t:this.s=ba.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ba=new ft;ao.geo.stream=function(n,t){n&&_a.hasOwnProperty(n.type)?_a[n.type](n,t):ht(n,t)};var _a={Feature:function(n,t){ht(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,i=e.length;++r<i;)ht(e[r].geometry,t)}},wa={Sphere:function(n,t){t.sphere()},Point:function(n,t){n=n.coordinates,t.point(n[0],n[1],n[2])},MultiPoint:function(n,t){for(var e=n.coordinates,r=-1,i=e.length;++r<i;)n=e[r],t.point(n[0],n[1],n[2])},LineString:function(n,t){pt(n.coordinates,t,0)},MultiLineString:function(n,t){for(var e=n.coordinates,r=-1,i=e.length;++r<i;)pt(e[r],t,0)},Polygon:function(n,t){gt(n.coordinates,t)},MultiPolygon:function(n,t){for(var e=n.coordinates,r=-1,i=e.length;++r<i;)gt(e[r],t)},GeometryCollection:function(n,t){for(var e=n.geometries,r=-1,i=e.length;++r<i;)ht(e[r],t)}};ao.geo.area=function(n){return Sa=0,ao.geo.stream(n,Na),Sa};var Sa,ka=new ft,Na={sphere:function(){Sa+=4*Fo},point:b,lineStart:b,lineEnd:b,polygonStart:function(){ka.reset(),Na.lineStart=vt},polygonEnd:function(){var n=2*ka;Sa+=0>n?4*Fo+n:n,Na.lineStart=Na.lineEnd=Na.point=b}};ao.geo.bounds=function(){function n(n,t){M.push(x=[f=n,h=n]),s>t&&(s=t),t>p&&(p=t)}function t(t,e){var r=dt([t*Yo,e*Yo]);if(y){var i=mt(y,r),u=[i[1],-i[0],0],o=mt(u,i);bt(o),o=_t(o);var l=t-g,c=l>0?1:-1,v=o[0]*Zo*c,d=xo(l)>180;if(d^(v>c*g&&c*t>v)){var m=o[1]*Zo;m>p&&(p=m)}else if(v=(v+360)%360-180,d^(v>c*g&&c*t>v)){var m=-o[1]*Zo;s>m&&(s=m)}else s>e&&(s=e),e>p&&(p=e);d?g>t?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t):h>=f?(f>t&&(f=t),t>h&&(h=t)):t>g?a(f,t)>a(f,h)&&(h=t):a(t,h)>a(f,h)&&(f=t)}else n(t,e);y=r,g=t}function e(){b.point=t}function r(){x[0]=f,x[1]=h,b.point=n,y=null}function i(n,e){if(y){var r=n-g;m+=xo(r)>180?r+(r>0?360:-360):r}else v=n,d=e;Na.point(n,e),t(n,e)}function u(){Na.lineStart()}function o(){i(v,d),Na.lineEnd(),xo(m)>Uo&&(f=-(h=180)),x[0]=f,x[1]=h,y=null}function a(n,t){return(t-=n)<0?t+360:t}function l(n,t){return n[0]-t[0]}function c(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:n<t[0]||t[1]<n}var f,s,h,p,g,v,d,y,m,M,x,b={point:n,lineStart:e,lineEnd:r,polygonStart:function(){b.point=i,b.lineStart=u,b.lineEnd=o,m=0,Na.polygonStart()},polygonEnd:function(){Na.polygonEnd(),b.point=n,b.lineStart=e,b.lineEnd=r,0>ka?(f=-(h=180),s=-(p=90)):m>Uo?p=90:-Uo>m&&(s=-90),x[0]=f,x[1]=h}};return function(n){p=h=-(f=s=1/0),M=[],ao.geo.stream(n,b);var t=M.length;if(t){M.sort(l);for(var e,r=1,i=M[0],u=[i];t>r;++r)e=M[r],c(e[0],i)||c(e[1],i)?(a(i[0],e[1])>a(i[0],i[1])&&(i[1]=e[1]),a(e[0],i[1])>a(i[0],i[1])&&(i[0]=e[0])):u.push(i=e);for(var o,e,g=-(1/0),t=u.length-1,r=0,i=u[t];t>=r;i=e,++r)e=u[r],(o=a(i[1],e[0]))>g&&(g=o,f=e[0],h=i[1])}return M=x=null,f===1/0||s===1/0?[[NaN,NaN],[NaN,NaN]]:[[f,s],[h,p]]}}(),ao.geo.centroid=function(n){Ea=Aa=Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,ja);var t=Da,e=Pa,r=Ua,i=t*t+e*e+r*r;return jo>i&&(t=qa,e=Ta,r=Ra,Uo>Aa&&(t=Ca,e=za,r=La),i=t*t+e*e+r*r,jo>i)?[NaN,NaN]:[Math.atan2(e,t)*Zo,tn(r/Math.sqrt(i))*Zo]};var Ea,Aa,Ca,za,La,qa,Ta,Ra,Da,Pa,Ua,ja={sphere:b,point:St,lineStart:Nt,lineEnd:Et,polygonStart:function(){ja.lineStart=At},polygonEnd:function(){ja.lineStart=Nt}},Fa=Rt(zt,jt,Ht,[-Fo,-Fo/2]),Ha=1e9;ao.geo.clipExtent=function(){var n,t,e,r,i,u,o={stream:function(n){return i&&(i.valid=!1),i=u(n),i.valid=!0,i},extent:function(a){return arguments.length?(u=Zt(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),i&&(i.valid=!1,i=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(ao.geo.conicEqualArea=function(){return Vt(Xt)}).raw=Xt,ao.geo.albers=function(){return ao.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},ao.geo.albersUsa=function(){function n(n){var u=n[0],o=n[1];return t=null,e(u,o),t||(r(u,o),t)||i(u,o),t}var t,e,r,i,u=ao.geo.albers(),o=ao.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ao.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=u.scale(),e=u.translate(),r=(n[0]-e[0])/t,i=(n[1]-e[1])/t;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?o:i>=.166&&.234>i&&r>=-.214&&-.115>r?a:u).invert(n)},n.stream=function(n){var t=u.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,i){t.point(n,i),e.point(n,i),r.point(n,i)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(u.precision(t),o.precision(t),a.precision(t),n):u.precision()},n.scale=function(t){return arguments.length?(u.scale(t),o.scale(.35*t),a.scale(t),n.translate(u.translate())):u.scale()},n.translate=function(t){if(!arguments.length)return u.translate();var c=u.scale(),f=+t[0],s=+t[1];return e=u.translate(t).clipExtent([[f-.455*c,s-.238*c],[f+.455*c,s+.238*c]]).stream(l).point,r=o.translate([f-.307*c,s+.201*c]).clipExtent([[f-.425*c+Uo,s+.12*c+Uo],[f-.214*c-Uo,s+.234*c-Uo]]).stream(l).point,i=a.translate([f-.205*c,s+.212*c]).clipExtent([[f-.214*c+Uo,s+.166*c+Uo],[f-.115*c-Uo,s+.234*c-Uo]]).stream(l).point,n},n.scale(1070)};var Oa,Ia,Ya,Za,Va,Xa,$a={point:b,lineStart:b,lineEnd:b,polygonStart:function(){Ia=0,$a.lineStart=$t},polygonEnd:function(){$a.lineStart=$a.lineEnd=$a.point=b,Oa+=xo(Ia/2)}},Ba={point:Bt,lineStart:b,lineEnd:b,polygonStart:b,polygonEnd:b},Wa={point:Gt,lineStart:Kt,lineEnd:Qt,polygonStart:function(){Wa.lineStart=ne},polygonEnd:function(){Wa.point=Gt,Wa.lineStart=Kt,Wa.lineEnd=Qt}};ao.geo.path=function(){function n(n){return n&&("function"==typeof a&&u.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=i(u)),ao.geo.stream(n,o)),u.result()}function t(){return o=null,n}var e,r,i,u,o,a=4.5;return n.area=function(n){return Oa=0,ao.geo.stream(n,i($a)),Oa},n.centroid=function(n){return Ca=za=La=qa=Ta=Ra=Da=Pa=Ua=0,ao.geo.stream(n,i(Wa)),Ua?[Da/Ua,Pa/Ua]:Ra?[qa/Ra,Ta/Ra]:La?[Ca/La,za/La]:[NaN,NaN]},n.bounds=function(n){return Va=Xa=-(Ya=Za=1/0),ao.geo.stream(n,i(Ba)),[[Ya,Za],[Va,Xa]]},n.projection=function(n){return arguments.length?(i=(e=n)?n.stream||re(n):m,t()):e},n.context=function(n){return arguments.length?(u=null==(r=n)?new Wt:new te(n),"function"!=typeof a&&u.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(u.pointRadius(+t),+t),n):a},n.projection(ao.geo.albersUsa()).context(null)},ao.geo.transform=function(n){return{stream:function(t){var e=new ie(t);for(var r in n)e[r]=n[r];return e}}},ie.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},ao.geo.projection=oe,ao.geo.projectionMutator=ae,(ao.geo.equirectangular=function(){return oe(ce)}).raw=ce.invert=ce,ao.geo.rotation=function(n){function t(t){return t=n(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t}return n=se(n[0]%360*Yo,n[1]*Yo,n.length>2?n[2]*Yo:0),t.invert=function(t){return t=n.invert(t[0]*Yo,t[1]*Yo),t[0]*=Zo,t[1]*=Zo,t},t},fe.invert=ce,ao.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=se(-n[0]*Yo,-n[1]*Yo,0).invert,i=[];return e(null,null,1,{point:function(n,e){i.push(n=t(n,e)),n[0]*=Zo,n[1]*=Zo}}),{type:"Polygon",coordinates:[i]}}var t,e,r=[0,0],i=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=ve((t=+r)*Yo,i*Yo),n):t},n.precision=function(r){return arguments.length?(e=ve(t*Yo,(i=+r)*Yo),n):i},n.angle(90)},ao.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Yo,i=n[1]*Yo,u=t[1]*Yo,o=Math.sin(r),a=Math.cos(r),l=Math.sin(i),c=Math.cos(i),f=Math.sin(u),s=Math.cos(u);return Math.atan2(Math.sqrt((e=s*o)*e+(e=c*f-l*s*a)*e),l*f+c*s*a)},ao.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return ao.range(Math.ceil(u/d)*d,i,d).map(h).concat(ao.range(Math.ceil(c/y)*y,l,y).map(p)).concat(ao.range(Math.ceil(r/g)*g,e,g).filter(function(n){return xo(n%d)>Uo}).map(f)).concat(ao.range(Math.ceil(a/v)*v,o,v).filter(function(n){return xo(n%y)>Uo}).map(s))}var e,r,i,u,o,a,l,c,f,s,h,p,g=10,v=g,d=90,y=360,m=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(u).concat(p(l).slice(1),h(i).reverse().slice(1),p(c).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(u=+t[0][0],i=+t[1][0],c=+t[0][1],l=+t[1][1],u>i&&(t=u,u=i,i=t),c>l&&(t=c,c=l,l=t),n.precision(m)):[[u,c],[i,l]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(m)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],y=+t[1],n):[d,y]},n.minorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],n):[g,v]},n.precision=function(t){return arguments.length?(m=+t,f=ye(a,o,90),s=me(r,e,m),h=ye(c,l,90),p=me(u,i,m),n):m},n.majorExtent([[-180,-90+Uo],[180,90-Uo]]).minorExtent([[-180,-80-Uo],[180,80+Uo]])},ao.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||i.apply(this,arguments)]}}var t,e,r=Me,i=xe;return n.distance=function(){return ao.geo.distance(t||r.apply(this,arguments),e||i.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(i=t,e="function"==typeof t?null:t,n):i},n.precision=function(){return arguments.length?n:0},n},ao.geo.interpolate=function(n,t){return be(n[0]*Yo,n[1]*Yo,t[0]*Yo,t[1]*Yo)},ao.geo.length=function(n){return Ja=0,ao.geo.stream(n,Ga),Ja};var Ja,Ga={sphere:b,point:b,lineStart:_e,lineEnd:b,polygonStart:b,polygonEnd:b},Ka=we(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(ao.geo.azimuthalEqualArea=function(){return oe(Ka)}).raw=Ka;var Qa=we(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},m);(ao.geo.azimuthalEquidistant=function(){return oe(Qa)}).raw=Qa,(ao.geo.conicConformal=function(){return Vt(Se)}).raw=Se,(ao.geo.conicEquidistant=function(){return Vt(ke)}).raw=ke;var nl=we(function(n){return 1/n},Math.atan);(ao.geo.gnomonic=function(){return oe(nl)}).raw=nl,Ne.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Io]},(ao.geo.mercator=function(){return Ee(Ne)}).raw=Ne;var tl=we(function(){return 1},Math.asin);(ao.geo.orthographic=function(){return oe(tl)}).raw=tl;var el=we(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(ao.geo.stereographic=function(){return oe(el)}).raw=el,Ae.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Io]},(ao.geo.transverseMercator=function(){var n=Ee(Ae),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=Ae,ao.geom={},ao.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,i=En(e),u=En(r),o=n.length,a=[],l=[];for(t=0;o>t;t++)a.push([+i.call(this,n[t],t),+u.call(this,n[t],t),t]);for(a.sort(qe),t=0;o>t;t++)l.push([a[t][0],-a[t][1]]);var c=Le(a),f=Le(l),s=f[0]===c[0],h=f[f.length-1]===c[c.length-1],p=[];for(t=c.length-1;t>=0;--t)p.push(n[a[c[t]][2]]);for(t=+s;t<f.length-h;++t)p.push(n[a[f[t]][2]]);return p}var e=Ce,r=ze;return arguments.length?t(n):(t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t)},ao.geom.polygon=function(n){return ko(n,rl),n};var rl=ao.geom.polygon.prototype=[];rl.area=function(){for(var n,t=-1,e=this.length,r=this[e-1],i=0;++t<e;)n=r,r=this[t],i+=n[1]*r[0]-n[0]*r[1];return.5*i},rl.centroid=function(n){var t,e,r=-1,i=this.length,u=0,o=0,a=this[i-1];for(arguments.length||(n=-1/(6*this.area()));++r<i;)t=a,a=this[r],e=t[0]*a[1]-a[0]*t[1],u+=(t[0]+a[0])*e,o+=(t[1]+a[1])*e;return[u*n,o*n]},rl.clip=function(n){for(var t,e,r,i,u,o,a=De(n),l=-1,c=this.length-De(this),f=this[c-1];++l<c;){for(t=n.slice(),n.length=0,i=this[l],u=t[(r=t.length-a)-1],e=-1;++e<r;)o=t[e],Te(o,f,i)?(Te(u,f,i)||n.push(Re(u,o,f,i)),n.push(o)):Te(u,f,i)&&n.push(Re(u,o,f,i)),u=o;a&&n.push(n[0]),f=i}return n};var il,ul,ol,al,ll,cl=[],fl=[];Ye.prototype.prepare=function(){for(var n,t=this.edges,e=t.length;e--;)n=t[e].edge,n.b&&n.a||t.splice(e,1);return t.sort(Ve),t.length},tr.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},er.prototype={insert:function(n,t){var e,r,i;if(n){if(t.P=n,t.N=n.N,n.N&&(n.N.P=t),n.N=t,n.R){for(n=n.R;n.L;)n=n.L;n.L=t}else n.R=t;e=n}else this._?(n=or(this._),t.P=null,t.N=n,n.P=n.L=t,e=n):(t.P=t.N=null,this._=t,e=null);for(t.L=t.R=null,t.U=e,t.C=!0,n=t;e&&e.C;)r=e.U,e===r.L?(i=r.R,i&&i.C?(e.C=i.C=!1,r.C=!0,n=r):(n===e.R&&(ir(this,e),n=e,e=n.U),e.C=!1,r.C=!0,ur(this,r))):(i=r.L,i&&i.C?(e.C=i.C=!1,r.C=!0,n=r):(n===e.L&&(ur(this,e),n=e,e=n.U),e.C=!1,r.C=!0,ir(this,r))),e=n.U;this._.C=!1},remove:function(n){n.N&&(n.N.P=n.P),n.P&&(n.P.N=n.N),n.N=n.P=null;var t,e,r,i=n.U,u=n.L,o=n.R;if(e=u?o?or(o):u:o,i?i.L===n?i.L=e:i.R=e:this._=e,u&&o?(r=e.C,e.C=n.C,e.L=u,u.U=e,e!==o?(i=e.U,e.U=n.U,n=e.R,i.L=n,e.R=o,o.U=e):(e.U=i,i=e,n=e.R)):(r=n.C,n=e),n&&(n.U=i),!r){if(n&&n.C)return void(n.C=!1);do{if(n===this._)break;if(n===i.L){if(t=i.R,t.C&&(t.C=!1,i.C=!0,ir(this,i),t=i.R),t.L&&t.L.C||t.R&&t.R.C){t.R&&t.R.C||(t.L.C=!1,t.C=!0,ur(this,t),t=i.R),t.C=i.C,i.C=t.R.C=!1,ir(this,i),n=this._;break}}else if(t=i.L,t.C&&(t.C=!1,i.C=!0,ur(this,i),t=i.L),t.L&&t.L.C||t.R&&t.R.C){t.L&&t.L.C||(t.R.C=!1,t.C=!0,ir(this,t),t=i.L),t.C=i.C,i.C=t.L.C=!1,ur(this,i),n=this._;break}t.C=!0,n=i,i=i.U}while(!n.C);n&&(n.C=!1)}}},ao.geom.voronoi=function(n){function t(n){var t=new Array(n.length),r=a[0][0],i=a[0][1],u=a[1][0],o=a[1][1];return ar(e(n),a).cells.forEach(function(e,a){var l=e.edges,c=e.site,f=t[a]=l.length?l.map(function(n){var t=n.start();return[t.x,t.y]}):c.x>=r&&c.x<=u&&c.y>=i&&c.y<=o?[[r,o],[u,o],[u,i],[r,i]]:[];f.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(u(n,t)/Uo)*Uo,y:Math.round(o(n,t)/Uo)*Uo,i:t}})}var r=Ce,i=ze,u=r,o=i,a=sl;return n?t(n):(t.links=function(n){return ar(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return ar(e(n)).cells.forEach(function(e,r){for(var i,u,o=e.site,a=e.edges.sort(Ve),l=-1,c=a.length,f=a[c-1].edge,s=f.l===o?f.r:f.l;++l<c;)i=f,u=s,f=a[l].edge,s=f.l===o?f.r:f.l,r<u.i&&r<s.i&&cr(o,u,s)<0&&t.push([n[r],n[u.i],n[s.i]])}),t},t.x=function(n){return arguments.length?(u=En(r=n),t):r},t.y=function(n){return arguments.length?(o=En(i=n),t):i},t.clipExtent=function(n){return arguments.length?(a=null==n?sl:n,t):a===sl?null:a},t.size=function(n){return arguments.length?t.clipExtent(n&&[[0,0],n]):a===sl?null:a&&a[1]},t)};var sl=[[-1e6,-1e6],[1e6,1e6]];ao.geom.delaunay=function(n){return ao.geom.voronoi().triangles(n)},ao.geom.quadtree=function(n,t,e,r,i){function u(n){function u(n,t,e,r,i,u,o,a){if(!isNaN(e)&&!isNaN(r))if(n.leaf){var l=n.x,f=n.y;if(null!=l)if(xo(l-e)+xo(f-r)<.01)c(n,t,e,r,i,u,o,a);else{var s=n.point;n.x=n.y=n.point=null,c(n,s,l,f,i,u,o,a),c(n,t,e,r,i,u,o,a)}else n.x=e,n.y=r,n.point=t}else c(n,t,e,r,i,u,o,a)}function c(n,t,e,r,i,o,a,l){var c=.5*(i+a),f=.5*(o+l),s=e>=c,h=r>=f,p=h<<1|s;n.leaf=!1,n=n.nodes[p]||(n.nodes[p]=hr()),s?i=c:a=c,h?o=f:l=f,u(n,t,e,r,i,o,a,l)}var f,s,h,p,g,v,d,y,m,M=En(a),x=En(l);if(null!=t)v=t,d=e,y=r,m=i;else if(y=m=-(v=d=1/0),s=[],h=[],g=n.length,o)for(p=0;g>p;++p)f=n[p],f.x<v&&(v=f.x),f.y<d&&(d=f.y),f.x>y&&(y=f.x),f.y>m&&(m=f.y),s.push(f.x),h.push(f.y);else for(p=0;g>p;++p){var b=+M(f=n[p],p),_=+x(f,p);v>b&&(v=b),d>_&&(d=_),b>y&&(y=b),_>m&&(m=_),s.push(b),h.push(_)}var w=y-v,S=m-d;w>S?m=d+w:y=v+S;var k=hr();if(k.add=function(n){u(k,n,+M(n,++p),+x(n,p),v,d,y,m)},k.visit=function(n){pr(n,k,v,d,y,m)},k.find=function(n){return gr(k,n[0],n[1],v,d,y,m)},p=-1,null==t){for(;++p<g;)u(k,n[p],s[p],h[p],v,d,y,m);--p}else n.forEach(k.add);return s=h=n=f=null,k}var o,a=Ce,l=ze;return(o=arguments.length)?(a=fr,l=sr,3===o&&(i=e,r=t,e=t=0),u(n)):(u.x=function(n){return arguments.length?(a=n,u):a},u.y=function(n){return arguments.length?(l=n,u):l},u.extent=function(n){return arguments.length?(null==n?t=e=r=i=null:(t=+n[0][0],e=+n[0][1],r=+n[1][0],i=+n[1][1]),u):null==t?null:[[t,e],[r,i]]},u.size=function(n){return arguments.length?(null==n?t=e=r=i=null:(t=e=0,r=+n[0],i=+n[1]),u):null==t?null:[r-t,i-e]},u)},ao.interpolateRgb=vr,ao.interpolateObject=dr,ao.interpolateNumber=yr,ao.interpolateString=mr;var hl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,pl=new RegExp(hl.source,"g");ao.interpolate=Mr,ao.interpolators=[function(n,t){var e=typeof t;return("string"===e?ua.has(t.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(t)?vr:mr:t instanceof an?vr:Array.isArray(t)?xr:"object"===e&&isNaN(t)?dr:yr)(n,t)}],ao.interpolateArray=xr;var gl=function(){return m},vl=ao.map({linear:gl,poly:Er,quad:function(){return Sr},cubic:function(){return kr},sin:function(){return Ar},exp:function(){return Cr},circle:function(){return zr},elastic:Lr,back:qr,bounce:function(){return Tr}}),dl=ao.map({"in":m,out:_r,"in-out":wr,"out-in":function(n){return wr(_r(n))}});ao.ease=function(n){var t=n.indexOf("-"),e=t>=0?n.slice(0,t):n,r=t>=0?n.slice(t+1):"in";return e=vl.get(e)||gl,r=dl.get(r)||m,br(r(e.apply(null,lo.call(arguments,1))))},ao.interpolateHcl=Rr,ao.interpolateHsl=Dr,ao.interpolateLab=Pr,ao.interpolateRound=Ur,ao.transform=function(n){var t=fo.createElementNS(ao.ns.prefix.svg,"g");return(ao.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new jr(e?e.matrix:yl)})(n)},jr.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var yl={a:1,b:0,c:0,d:1,e:0,f:0};ao.interpolateTransform=$r,ao.layout={},ao.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++e<r;)t.push(Jr(n[e]));return t}},ao.layout.chord=function(){function n(){var n,c,s,h,p,g={},v=[],d=ao.range(u),y=[];for(e=[],r=[],n=0,h=-1;++h<u;){for(c=0,p=-1;++p<u;)c+=i[h][p];v.push(c),y.push(ao.range(u)),n+=c}for(o&&d.sort(function(n,t){return o(v[n],v[t])}),a&&y.forEach(function(n,t){n.sort(function(n,e){return a(i[t][n],i[t][e])})}),n=(Ho-f*u)/n,c=0,h=-1;++h<u;){for(s=c,p=-1;++p<u;){var m=d[h],M=y[m][p],x=i[m][M],b=c,_=c+=x*n;g[m+"-"+M]={index:m,subindex:M,startAngle:b,endAngle:_,value:x}}r[m]={index:m,startAngle:s,endAngle:c,value:v[m]},c+=f}for(h=-1;++h<u;)for(p=h-1;++p<u;){var w=g[h+"-"+p],S=g[p+"-"+h];(w.value||S.value)&&e.push(w.value<S.value?{source:S,target:w}:{source:w,target:S})}l&&t()}function t(){e.sort(function(n,t){return l((n.source.value+n.target.value)/2,(t.source.value+t.target.value)/2)})}var e,r,i,u,o,a,l,c={},f=0;return c.matrix=function(n){return arguments.length?(u=(i=n)&&i.length,e=r=null,c):i},c.padding=function(n){return arguments.length?(f=n,e=r=null,c):f},c.sortGroups=function(n){return arguments.length?(o=n,e=r=null,c):o},c.sortSubgroups=function(n){return arguments.length?(a=n,e=null,c):a},c.sortChords=function(n){return arguments.length?(l=n,e&&t(),c):l},c.chords=function(){return e||n(),e},c.groups=function(){return r||n(),r},c},ao.layout.force=function(){function n(n){return function(t,e,r,i){if(t.point!==n){var u=t.cx-n.x,o=t.cy-n.y,a=i-e,l=u*u+o*o;if(l>a*a/y){if(v>l){var c=t.charge/l;n.px-=u*c,n.py-=o*c}return!0}if(t.point&&l&&v>l){var c=t.pointCharge/l;n.px-=u*c,n.py-=o*c}}return!t.charge}}function t(n){n.px=ao.event.x,n.py=ao.event.y,l.resume()}var e,r,i,u,o,a,l={},c=ao.dispatch("start","tick","end"),f=[1,1],s=.9,h=ml,p=Ml,g=-30,v=xl,d=.1,y=.64,M=[],x=[];return l.tick=function(){if((i*=.99)<.005)return e=null,c.end({type:"end",alpha:i=0}),!0;var t,r,l,h,p,v,y,m,b,_=M.length,w=x.length;for(r=0;w>r;++r)l=x[r],h=l.source,p=l.target,m=p.x-h.x,b=p.y-h.y,(v=m*m+b*b)&&(v=i*o[r]*((v=Math.sqrt(v))-u[r])/v,m*=v,b*=v,p.x-=m*(y=h.weight+p.weight?h.weight/(h.weight+p.weight):.5),p.y-=b*y,h.x+=m*(y=1-y),h.y+=b*y);if((y=i*d)&&(m=f[0]/2,b=f[1]/2,r=-1,y))for(;++r<_;)l=M[r],l.x+=(m-l.x)*y,l.y+=(b-l.y)*y;if(g)for(ri(t=ao.geom.quadtree(M),i,a),r=-1;++r<_;)(l=M[r]).fixed||t.visit(n(l));for(r=-1;++r<_;)l=M[r],l.fixed?(l.x=l.px,l.y=l.py):(l.x-=(l.px-(l.px=l.x))*s,l.y-=(l.py-(l.py=l.y))*s);c.tick({type:"tick",alpha:i})},l.nodes=function(n){return arguments.length?(M=n,l):M},l.links=function(n){return arguments.length?(x=n,l):x},l.size=function(n){return arguments.length?(f=n,l):f},l.linkDistance=function(n){return arguments.length?(h="function"==typeof n?n:+n,l):h},l.distance=l.linkDistance,l.linkStrength=function(n){return arguments.length?(p="function"==typeof n?n:+n,l):p},l.friction=function(n){return arguments.length?(s=+n,l):s},l.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,l):g},l.chargeDistance=function(n){return arguments.length?(v=n*n,l):Math.sqrt(v)},l.gravity=function(n){return arguments.length?(d=+n,l):d},l.theta=function(n){return arguments.length?(y=n*n,l):Math.sqrt(y)},l.alpha=function(n){return arguments.length?(n=+n,i?n>0?i=n:(e.c=null,e.t=NaN,e=null,c.end({type:"end",alpha:i=0})):n>0&&(c.start({type:"start",alpha:i=n}),e=qn(l.tick)),l):i},l.start=function(){function n(n,r){if(!e){for(e=new Array(i),l=0;i>l;++l)e[l]=[];for(l=0;c>l;++l){var u=x[l];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var o,a=e[t],l=-1,f=a.length;++l<f;)if(!isNaN(o=a[l][n]))return o;return Math.random()*r}var t,e,r,i=M.length,c=x.length,s=f[0],v=f[1];for(t=0;i>t;++t)(r=M[t]).index=t,r.weight=0;for(t=0;c>t;++t)r=x[t],"number"==typeof r.source&&(r.source=M[r.source]),"number"==typeof r.target&&(r.target=M[r.target]),++r.source.weight,++r.target.weight;for(t=0;i>t;++t)r=M[t],isNaN(r.x)&&(r.x=n("x",s)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof h)for(t=0;c>t;++t)u[t]=+h.call(this,x[t],t);else for(t=0;c>t;++t)u[t]=h;if(o=[],"function"==typeof p)for(t=0;c>t;++t)o[t]=+p.call(this,x[t],t);else for(t=0;c>t;++t)o[t]=p;if(a=[],"function"==typeof g)for(t=0;i>t;++t)a[t]=+g.call(this,M[t],t);else for(t=0;i>t;++t)a[t]=g;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return r||(r=ao.behavior.drag().origin(m).on("dragstart.force",Qr).on("drag.force",t).on("dragend.force",ni)),arguments.length?void this.on("mouseover.force",ti).on("mouseout.force",ei).call(r):r},ao.rebind(l,c,"on")};var ml=20,Ml=1,xl=1/0;ao.layout.hierarchy=function(){function n(i){var u,o=[i],a=[];for(i.depth=0;null!=(u=o.pop());)if(a.push(u),(c=e.call(n,u,u.depth))&&(l=c.length)){for(var l,c,f;--l>=0;)o.push(f=c[l]),f.parent=u,f.depth=u.depth+1;r&&(u.value=0),u.children=c}else r&&(u.value=+r.call(n,u,u.depth)||0),delete u.children;return oi(i,function(n){var e,i;t&&(e=n.children)&&e.sort(t),r&&(i=n.parent)&&(i.value+=n.value)}),a}var t=ci,e=ai,r=li;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(ui(t,function(n){n.children&&(n.value=0)}),oi(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},ao.layout.partition=function(){function n(t,e,r,i){var u=t.children;if(t.x=e,t.y=t.depth*i,t.dx=r,t.dy=i,u&&(o=u.length)){var o,a,l,c=-1;for(r=t.value?r/t.value:0;++c<o;)n(a=u[c],e,l=a.value*r,i),e+=l}}function t(n){var e=n.children,r=0;if(e&&(i=e.length))for(var i,u=-1;++u<i;)r=Math.max(r,t(e[u]));return 1+r}function e(e,u){var o=r.call(this,e,u);return n(o[0],0,i[0],i[1]/t(o[0])),o}var r=ao.layout.hierarchy(),i=[1,1];return e.size=function(n){return arguments.length?(i=n,e):i},ii(e,r)},ao.layout.pie=function(){function n(o){var a,l=o.length,c=o.map(function(e,r){return+t.call(n,e,r)}),f=+("function"==typeof r?r.apply(this,arguments):r),s=("function"==typeof i?i.apply(this,arguments):i)-f,h=Math.min(Math.abs(s)/l,+("function"==typeof u?u.apply(this,arguments):u)),p=h*(0>s?-1:1),g=ao.sum(c),v=g?(s-l*p)/g:0,d=ao.range(l),y=[];return null!=e&&d.sort(e===bl?function(n,t){return c[t]-c[n]}:function(n,t){return e(o[n],o[t])}),d.forEach(function(n){y[n]={data:o[n],value:a=c[n],startAngle:f,endAngle:f+=a*v+p,padAngle:h}}),y}var t=Number,e=bl,r=0,i=Ho,u=0;return n.value=function(e){return arguments.length?(t=e,n):t},n.sort=function(t){return arguments.length?(e=t,n):e},n.startAngle=function(t){return arguments.length?(r=t,n):r},n.endAngle=function(t){return arguments.length?(i=t,n):i},n.padAngle=function(t){return arguments.length?(u=t,n):u},n};var bl={};ao.layout.stack=function(){function n(a,l){if(!(h=a.length))return a;var c=a.map(function(e,r){return t.call(n,e,r)}),f=c.map(function(t){return t.map(function(t,e){return[u.call(n,t,e),o.call(n,t,e)]})}),s=e.call(n,f,l);c=ao.permute(c,s),f=ao.permute(f,s);var h,p,g,v,d=r.call(n,f,l),y=c[0].length;for(g=0;y>g;++g)for(i.call(n,c[0][g],v=d[g],f[0][g][1]),p=1;h>p;++p)i.call(n,c[p][g],v+=f[p-1][g][1],f[p][g][1]);return a}var t=m,e=gi,r=vi,i=pi,u=si,o=hi;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:_l.get(t)||gi,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:wl.get(t)||vi,n):r},n.x=function(t){return arguments.length?(u=t,n):u},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(i=t,n):i},n};var _l=ao.map({"inside-out":function(n){var t,e,r=n.length,i=n.map(di),u=n.map(yi),o=ao.range(r).sort(function(n,t){return i[n]-i[t]}),a=0,l=0,c=[],f=[];for(t=0;r>t;++t)e=o[t],l>a?(a+=u[e],c.push(e)):(l+=u[e],f.push(e));return f.reverse().concat(c)},reverse:function(n){return ao.range(n.length).reverse()},"default":gi}),wl=ao.map({silhouette:function(n){var t,e,r,i=n.length,u=n[0].length,o=[],a=0,l=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;u>e;++e)l[e]=(a-o[e])/2;return l},wiggle:function(n){var t,e,r,i,u,o,a,l,c,f=n.length,s=n[0],h=s.length,p=[];for(p[0]=l=c=0,e=1;h>e;++e){for(t=0,i=0;f>t;++t)i+=n[t][e][1];for(t=0,u=0,a=s[e][0]-s[e-1][0];f>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;u+=o*n[t][e][1]}p[e]=l-=i?u/i*a:0,c>l&&(c=l)}for(e=0;h>e;++e)p[e]-=c;return p},expand:function(n){var t,e,r,i=n.length,u=n[0].length,o=1/i,a=[];for(e=0;u>e;++e){for(t=0,r=0;i>t;t++)r+=n[t][e][1];if(r)for(t=0;i>t;t++)n[t][e][1]/=r;else for(t=0;i>t;t++)n[t][e][1]=o}for(e=0;u>e;++e)a[e]=0;return a},zero:vi});ao.layout.histogram=function(){function n(n,u){for(var o,a,l=[],c=n.map(e,this),f=r.call(this,c,u),s=i.call(this,f,c,u),u=-1,h=c.length,p=s.length-1,g=t?1:1/h;++u<p;)o=l[u]=[],o.dx=s[u+1]-(o.x=s[u]),o.y=0;if(p>0)for(u=-1;++u<h;)a=c[u],a>=f[0]&&a<=f[1]&&(o=l[ao.bisect(s,a,1,p)-1],o.y+=g,o.push(n[u]));return l}var t=!0,e=Number,r=bi,i=Mi;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=En(t),n):r},n.bins=function(t){return arguments.length?(i="number"==typeof t?function(n){return xi(n,t)}:En(t),n):i},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},ao.layout.pack=function(){function n(n,u){var o=e.call(this,n,u),a=o[0],l=i[0],c=i[1],f=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,oi(a,function(n){n.r=+f(n.value)}),oi(a,Ni),r){var s=r*(t?1:Math.max(2*a.r/l,2*a.r/c))/2;oi(a,function(n){n.r+=s}),oi(a,Ni),oi(a,function(n){n.r-=s})}return Ci(a,l/2,c/2,t?1:1/Math.max(2*a.r/l,2*a.r/c)),o}var t,e=ao.layout.hierarchy().sort(_i),r=0,i=[1,1];return n.size=function(t){return arguments.length?(i=t,n):i},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},ii(n,e)},ao.layout.tree=function(){function n(n,i){var f=o.call(this,n,i),s=f[0],h=t(s);if(oi(h,e),h.parent.m=-h.z,ui(h,r),c)ui(s,u);else{var p=s,g=s,v=s;ui(s,function(n){n.x<p.x&&(p=n),n.x>g.x&&(g=n),n.depth>v.depth&&(v=n)});var d=a(p,g)/2-p.x,y=l[0]/(g.x+a(g,p)/2+d),m=l[1]/(v.depth||1);ui(s,function(n){n.x=(n.x+d)*y,n.y=n.depth*m})}return f}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var i,u=t.children,o=0,a=u.length;a>o;++o)r.push((u[o]=i={_:u[o],parent:t,children:(i=u[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){Di(n);var u=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-u):n.z=u}else r&&(n.z=r.z+a(n._,r._));n.parent.A=i(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function i(n,t,e){if(t){for(var r,i=n,u=n,o=t,l=i.parent.children[0],c=i.m,f=u.m,s=o.m,h=l.m;o=Ti(o),i=qi(i),o&&i;)l=qi(l),u=Ti(u),u.a=n,r=o.z+s-i.z-c+a(o._,i._),r>0&&(Ri(Pi(o,n,e),n,r),c+=r,f+=r),s+=o.m,c+=i.m,h+=l.m,f+=u.m;o&&!Ti(u)&&(u.t=o,u.m+=s-f),i&&!qi(l)&&(l.t=i,l.m+=c-h,e=n)}return e}function u(n){n.x*=l[0],n.y=n.depth*l[1]}var o=ao.layout.hierarchy().sort(null).value(null),a=Li,l=[1,1],c=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(c=null==(l=t)?u:null,n):c?null:l},n.nodeSize=function(t){return arguments.length?(c=null==(l=t)?null:u,n):c?l:null},ii(n,o)},ao.layout.cluster=function(){function n(n,u){var o,a=t.call(this,n,u),l=a[0],c=0;oi(l,function(n){var t=n.children;t&&t.length?(n.x=ji(t),n.y=Ui(t)):(n.x=o?c+=e(n,o):0,n.y=0,o=n)});var f=Fi(l),s=Hi(l),h=f.x-e(f,s)/2,p=s.x+e(s,f)/2;return oi(l,i?function(n){n.x=(n.x-l.x)*r[0],n.y=(l.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(p-h)*r[0],n.y=(1-(l.y?n.y/l.y:1))*r[1]}),a}var t=ao.layout.hierarchy().sort(null).value(null),e=Li,r=[1,1],i=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(i=null==(r=t),n):i?null:r},n.nodeSize=function(t){return arguments.length?(i=null!=(r=t),n):i?r:null},ii(n,t)},ao.layout.treemap=function(){function n(n,t){for(var e,r,i=-1,u=n.length;++i<u;)r=(e=n[i]).value*(0>t?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var u=e.children;if(u&&u.length){var o,a,l,c=s(e),f=[],h=u.slice(),g=1/0,v="slice"===p?c.dx:"dice"===p?c.dy:"slice-dice"===p?1&e.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(n(h,c.dx*c.dy/e.value),f.area=0;(l=h.length)>0;)f.push(o=h[l-1]),f.area+=o.area,"squarify"!==p||(a=r(f,v))<=g?(h.pop(),g=a):(f.area-=f.pop().area,i(f,v,c,!1),v=Math.min(c.dx,c.dy),f.length=f.area=0,g=1/0);f.length&&(i(f,v,c,!0),f.length=f.area=0),u.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var u,o=s(t),a=r.slice(),l=[];for(n(a,o.dx*o.dy/t.value),l.area=0;u=a.pop();)l.push(u),l.area+=u.area,null!=u.z&&(i(l,u.z?o.dx:o.dy,o,!a.length),l.length=l.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,i=0,u=1/0,o=-1,a=n.length;++o<a;)(e=n[o].area)&&(u>e&&(u=e),e>i&&(i=e));return r*=r,t*=t,r?Math.max(t*i*g/r,r/(t*u*g)):1/0}function i(n,t,e,r){var i,u=-1,o=n.length,a=e.x,c=e.y,f=t?l(n.area/t):0;
if(t==e.dx){for((r||f>e.dy)&&(f=e.dy);++u<o;)i=n[u],i.x=a,i.y=c,i.dy=f,a+=i.dx=Math.min(e.x+e.dx-a,f?l(i.area/f):0);i.z=!0,i.dx+=e.x+e.dx-a,e.y+=f,e.dy-=f}else{for((r||f>e.dx)&&(f=e.dx);++u<o;)i=n[u],i.x=a,i.y=c,i.dx=f,c+=i.dy=Math.min(e.y+e.dy-c,f?l(i.area/f):0);i.z=!1,i.dy+=e.y+e.dy-c,e.x+=f,e.dx-=f}}function u(r){var i=o||a(r),u=i[0];return u.x=u.y=0,u.value?(u.dx=c[0],u.dy=c[1]):u.dx=u.dy=0,o&&a.revalue(u),n([u],u.dx*u.dy/u.value),(o?e:t)(u),h&&(o=i),i}var o,a=ao.layout.hierarchy(),l=Math.round,c=[1,1],f=null,s=Oi,h=!1,p="squarify",g=.5*(1+Math.sqrt(5));return u.size=function(n){return arguments.length?(c=n,u):c},u.padding=function(n){function t(t){var e=n.call(u,t,t.depth);return null==e?Oi(t):Ii(t,"number"==typeof e?[e,e,e,e]:e)}function e(t){return Ii(t,n)}if(!arguments.length)return f;var r;return s=null==(f=n)?Oi:"function"==(r=typeof n)?t:"number"===r?(n=[n,n,n,n],e):e,u},u.round=function(n){return arguments.length?(l=n?Math.round:Number,u):l!=Number},u.sticky=function(n){return arguments.length?(h=n,o=null,u):h},u.ratio=function(n){return arguments.length?(g=n,u):g},u.mode=function(n){return arguments.length?(p=n+"",u):p},ii(u,a)},ao.random={normal:function(n,t){var e=arguments.length;return 2>e&&(t=1),1>e&&(n=0),function(){var e,r,i;do e=2*Math.random()-1,r=2*Math.random()-1,i=e*e+r*r;while(!i||i>1);return n+t*e*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var n=ao.random.normal.apply(ao,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=ao.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},ao.scale={};var Sl={floor:m,ceil:m};ao.scale.linear=function(){return Wi([0,1],[0,1],Mr,!1)};var kl={s:1,g:1,p:1,r:1,e:1};ao.scale.log=function(){return ru(ao.scale.linear().domain([0,1]),10,!0,[1,10])};var Nl=ao.format(".0e"),El={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};ao.scale.pow=function(){return iu(ao.scale.linear(),1,[0,1])},ao.scale.sqrt=function(){return ao.scale.pow().exponent(.5)},ao.scale.ordinal=function(){return ou([],{t:"range",a:[[]]})},ao.scale.category10=function(){return ao.scale.ordinal().range(Al)},ao.scale.category20=function(){return ao.scale.ordinal().range(Cl)},ao.scale.category20b=function(){return ao.scale.ordinal().range(zl)},ao.scale.category20c=function(){return ao.scale.ordinal().range(Ll)};var Al=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xn),Cl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xn),zl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xn),Ll=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xn);ao.scale.quantile=function(){return au([],[])},ao.scale.quantize=function(){return lu(0,1,[0,1])},ao.scale.threshold=function(){return cu([.5],[0,1])},ao.scale.identity=function(){return fu([0,1])},ao.svg={},ao.svg.arc=function(){function n(){var n=Math.max(0,+e.apply(this,arguments)),c=Math.max(0,+r.apply(this,arguments)),f=o.apply(this,arguments)-Io,s=a.apply(this,arguments)-Io,h=Math.abs(s-f),p=f>s?0:1;if(n>c&&(g=c,c=n,n=g),h>=Oo)return t(c,p)+(n?t(n,1-p):"")+"Z";var g,v,d,y,m,M,x,b,_,w,S,k,N=0,E=0,A=[];if((y=(+l.apply(this,arguments)||0)/2)&&(d=u===ql?Math.sqrt(n*n+c*c):+u.apply(this,arguments),p||(E*=-1),c&&(E=tn(d/c*Math.sin(y))),n&&(N=tn(d/n*Math.sin(y)))),c){m=c*Math.cos(f+E),M=c*Math.sin(f+E),x=c*Math.cos(s-E),b=c*Math.sin(s-E);var C=Math.abs(s-f-2*E)<=Fo?0:1;if(E&&yu(m,M,x,b)===p^C){var z=(f+s)/2;m=c*Math.cos(z),M=c*Math.sin(z),x=b=null}}else m=M=0;if(n){_=n*Math.cos(s-N),w=n*Math.sin(s-N),S=n*Math.cos(f+N),k=n*Math.sin(f+N);var L=Math.abs(f-s+2*N)<=Fo?0:1;if(N&&yu(_,w,S,k)===1-p^L){var q=(f+s)/2;_=n*Math.cos(q),w=n*Math.sin(q),S=k=null}}else _=w=0;if(h>Uo&&(g=Math.min(Math.abs(c-n)/2,+i.apply(this,arguments)))>.001){v=c>n^p?0:1;var T=g,R=g;if(Fo>h){var D=null==S?[_,w]:null==x?[m,M]:Re([m,M],[S,k],[x,b],[_,w]),P=m-D[0],U=M-D[1],j=x-D[0],F=b-D[1],H=1/Math.sin(Math.acos((P*j+U*F)/(Math.sqrt(P*P+U*U)*Math.sqrt(j*j+F*F)))/2),O=Math.sqrt(D[0]*D[0]+D[1]*D[1]);R=Math.min(g,(n-O)/(H-1)),T=Math.min(g,(c-O)/(H+1))}if(null!=x){var I=mu(null==S?[_,w]:[S,k],[m,M],c,T,p),Y=mu([x,b],[_,w],c,T,p);g===T?A.push("M",I[0],"A",T,",",T," 0 0,",v," ",I[1],"A",c,",",c," 0 ",1-p^yu(I[1][0],I[1][1],Y[1][0],Y[1][1]),",",p," ",Y[1],"A",T,",",T," 0 0,",v," ",Y[0]):A.push("M",I[0],"A",T,",",T," 0 1,",v," ",Y[0])}else A.push("M",m,",",M);if(null!=S){var Z=mu([m,M],[S,k],n,-R,p),V=mu([_,w],null==x?[m,M]:[x,b],n,-R,p);g===R?A.push("L",V[0],"A",R,",",R," 0 0,",v," ",V[1],"A",n,",",n," 0 ",p^yu(V[1][0],V[1][1],Z[1][0],Z[1][1]),",",1-p," ",Z[1],"A",R,",",R," 0 0,",v," ",Z[0]):A.push("L",V[0],"A",R,",",R," 0 0,",v," ",Z[0])}else A.push("L",_,",",w)}else A.push("M",m,",",M),null!=x&&A.push("A",c,",",c," 0 ",C,",",p," ",x,",",b),A.push("L",_,",",w),null!=S&&A.push("A",n,",",n," 0 ",L,",",1-p," ",S,",",k);return A.push("Z"),A.join("")}function t(n,t){return"M0,"+n+"A"+n+","+n+" 0 1,"+t+" 0,"+-n+"A"+n+","+n+" 0 1,"+t+" 0,"+n}var e=hu,r=pu,i=su,u=ql,o=gu,a=vu,l=du;return n.innerRadius=function(t){return arguments.length?(e=En(t),n):e},n.outerRadius=function(t){return arguments.length?(r=En(t),n):r},n.cornerRadius=function(t){return arguments.length?(i=En(t),n):i},n.padRadius=function(t){return arguments.length?(u=t==ql?ql:En(t),n):u},n.startAngle=function(t){return arguments.length?(o=En(t),n):o},n.endAngle=function(t){return arguments.length?(a=En(t),n):a},n.padAngle=function(t){return arguments.length?(l=En(t),n):l},n.centroid=function(){var n=(+e.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+o.apply(this,arguments)+ +a.apply(this,arguments))/2-Io;return[Math.cos(t)*n,Math.sin(t)*n]},n};var ql="auto";ao.svg.line=function(){return Mu(m)};var Tl=ao.map({linear:xu,"linear-closed":bu,step:_u,"step-before":wu,"step-after":Su,basis:zu,"basis-open":Lu,"basis-closed":qu,bundle:Tu,cardinal:Eu,"cardinal-open":ku,"cardinal-closed":Nu,monotone:Fu});Tl.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Rl=[0,2/3,1/3,0],Dl=[0,1/3,2/3,0],Pl=[0,1/6,2/3,1/6];ao.svg.line.radial=function(){var n=Mu(Hu);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},wu.reverse=Su,Su.reverse=wu,ao.svg.area=function(){return Ou(m)},ao.svg.area.radial=function(){var n=Ou(Hu);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},ao.svg.chord=function(){function n(n,a){var l=t(this,u,n,a),c=t(this,o,n,a);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(e(l,c)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,c.r,c.p0)+r(c.r,c.p1,c.a1-c.a0)+i(c.r,c.p1,l.r,l.p0))+"Z"}function t(n,t,e,r){var i=t.call(n,e,r),u=a.call(n,i,r),o=l.call(n,i,r)-Io,f=c.call(n,i,r)-Io;return{r:u,a0:o,a1:f,p0:[u*Math.cos(o),u*Math.sin(o)],p1:[u*Math.cos(f),u*Math.sin(f)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>Fo)+",1 "+t}function i(n,t,e,r){return"Q 0,0 "+r}var u=Me,o=xe,a=Iu,l=gu,c=vu;return n.radius=function(t){return arguments.length?(a=En(t),n):a},n.source=function(t){return arguments.length?(u=En(t),n):u},n.target=function(t){return arguments.length?(o=En(t),n):o},n.startAngle=function(t){return arguments.length?(l=En(t),n):l},n.endAngle=function(t){return arguments.length?(c=En(t),n):c},n},ao.svg.diagonal=function(){function n(n,i){var u=t.call(this,n,i),o=e.call(this,n,i),a=(u.y+o.y)/2,l=[u,{x:u.x,y:a},{x:o.x,y:a},o];return l=l.map(r),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var t=Me,e=xe,r=Yu;return n.source=function(e){return arguments.length?(t=En(e),n):t},n.target=function(t){return arguments.length?(e=En(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},ao.svg.diagonal.radial=function(){var n=ao.svg.diagonal(),t=Yu,e=n.projection;return n.projection=function(n){return arguments.length?e(Zu(t=n)):t},n},ao.svg.symbol=function(){function n(n,r){return(Ul.get(t.call(this,n,r))||$u)(e.call(this,n,r))}var t=Xu,e=Vu;return n.type=function(e){return arguments.length?(t=En(e),n):t},n.size=function(t){return arguments.length?(e=En(t),n):e},n};var Ul=ao.map({circle:$u,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Fl)),e=t*Fl;return"M0,"+-t+"L"+e+",0 0,"+t+" "+-e+",0Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/jl),e=t*jl/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});ao.svg.symbolTypes=Ul.keys();var jl=Math.sqrt(3),Fl=Math.tan(30*Yo);Co.transition=function(n){for(var t,e,r=Hl||++Zl,i=Ku(n),u=[],o=Ol||{time:Date.now(),ease:Nr,delay:0,duration:250},a=-1,l=this.length;++a<l;){u.push(t=[]);for(var c=this[a],f=-1,s=c.length;++f<s;)(e=c[f])&&Qu(e,f,i,r,o),t.push(e)}return Wu(u,i,r)},Co.interrupt=function(n){return this.each(null==n?Il:Bu(Ku(n)))};var Hl,Ol,Il=Bu(Ku()),Yl=[],Zl=0;Yl.call=Co.call,Yl.empty=Co.empty,Yl.node=Co.node,Yl.size=Co.size,ao.transition=function(n,t){return n&&n.transition?Hl?n.transition(t):n:ao.selection().transition(n)},ao.transition.prototype=Yl,Yl.select=function(n){var t,e,r,i=this.id,u=this.namespace,o=[];n=A(n);for(var a=-1,l=this.length;++a<l;){o.push(t=[]);for(var c=this[a],f=-1,s=c.length;++f<s;)(r=c[f])&&(e=n.call(r,r.__data__,f,a))?("__data__"in r&&(e.__data__=r.__data__),Qu(e,f,u,i,r[u][i]),t.push(e)):t.push(null)}return Wu(o,u,i)},Yl.selectAll=function(n){var t,e,r,i,u,o=this.id,a=this.namespace,l=[];n=C(n);for(var c=-1,f=this.length;++c<f;)for(var s=this[c],h=-1,p=s.length;++h<p;)if(r=s[h]){u=r[a][o],e=n.call(r,r.__data__,h,c),l.push(t=[]);for(var g=-1,v=e.length;++g<v;)(i=e[g])&&Qu(i,g,a,o,u),t.push(i)}return Wu(l,a,o)},Yl.filter=function(n){var t,e,r,i=[];"function"!=typeof n&&(n=O(n));for(var u=0,o=this.length;o>u;u++){i.push(t=[]);for(var e=this[u],a=0,l=e.length;l>a;a++)(r=e[a])&&n.call(r,r.__data__,a,u)&&t.push(r)}return Wu(i,this.namespace,this.id)},Yl.tween=function(n,t){var e=this.id,r=this.namespace;return arguments.length<2?this.node()[r][e].tween.get(n):Y(this,null==t?function(t){t[r][e].tween.remove(n)}:function(i){i[r][e].tween.set(n,t)})},Yl.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function i(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function u(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?$r:Mr,a=ao.ns.qualify(n);return Ju(this,"attr."+n,t,a.local?u:i)},Yl.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(i));return r&&function(n){this.setAttribute(i,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(i.space,i.local));return r&&function(n){this.setAttributeNS(i.space,i.local,r(n))}}var i=ao.ns.qualify(n);return this.tween("attr."+n,i.local?r:e)},Yl.style=function(n,e,r){function i(){this.style.removeProperty(n)}function u(e){return null==e?i:(e+="",function(){var i,u=t(this).getComputedStyle(this,null).getPropertyValue(n);return u!==e&&(i=Mr(u,e),function(t){this.style.setProperty(n,i(t),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof n){2>o&&(e="");for(r in n)this.style(r,n[r],e);return this}r=""}return Ju(this,"style."+n,e,u)},Yl.styleTween=function(n,e,r){function i(i,u){var o=e.call(this,i,u,t(this).getComputedStyle(this,null).getPropertyValue(n));return o&&function(t){this.style.setProperty(n,o(t),r)}}return arguments.length<3&&(r=""),this.tween("style."+n,i)},Yl.text=function(n){return Ju(this,"text",n,Gu)},Yl.remove=function(){var n=this.namespace;return this.each("end.transition",function(){var t;this[n].count<2&&(t=this.parentNode)&&t.removeChild(this)})},Yl.ease=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].ease:("function"!=typeof n&&(n=ao.ease.apply(ao,arguments)),Y(this,function(r){r[e][t].ease=n}))},Yl.delay=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].delay:Y(this,"function"==typeof n?function(r,i,u){r[e][t].delay=+n.call(r,r.__data__,i,u)}:(n=+n,function(r){r[e][t].delay=n}))},Yl.duration=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].duration:Y(this,"function"==typeof n?function(r,i,u){r[e][t].duration=Math.max(1,n.call(r,r.__data__,i,u))}:(n=Math.max(1,n),function(r){r[e][t].duration=n}))},Yl.each=function(n,t){var e=this.id,r=this.namespace;if(arguments.length<2){var i=Ol,u=Hl;try{Hl=e,Y(this,function(t,i,u){Ol=t[r][e],n.call(t,t.__data__,i,u)})}finally{Ol=i,Hl=u}}else Y(this,function(i){var u=i[r][e];(u.event||(u.event=ao.dispatch("start","end","interrupt"))).on(n,t)});return this},Yl.transition=function(){for(var n,t,e,r,i=this.id,u=++Zl,o=this.namespace,a=[],l=0,c=this.length;c>l;l++){a.push(n=[]);for(var t=this[l],f=0,s=t.length;s>f;f++)(e=t[f])&&(r=e[o][i],Qu(e,f,o,u,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})),n.push(e)}return Wu(a,o,u)},ao.svg.axis=function(){function n(n){n.each(function(){var n,c=ao.select(this),f=this.__chart__||e,s=this.__chart__=e.copy(),h=null==l?s.ticks?s.ticks.apply(s,a):s.domain():l,p=null==t?s.tickFormat?s.tickFormat.apply(s,a):m:t,g=c.selectAll(".tick").data(h,s),v=g.enter().insert("g",".domain").attr("class","tick").style("opacity",Uo),d=ao.transition(g.exit()).style("opacity",Uo).remove(),y=ao.transition(g.order()).style("opacity",1),M=Math.max(i,0)+o,x=Zi(s),b=c.selectAll(".domain").data([0]),_=(b.enter().append("path").attr("class","domain"),ao.transition(b));v.append("line"),v.append("text");var w,S,k,N,E=v.select("line"),A=y.select("line"),C=g.select("text").text(p),z=v.select("text"),L=y.select("text"),q="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r?(n=no,w="x",k="y",S="x2",N="y2",C.attr("dy",0>q?"0em":".71em").style("text-anchor","middle"),_.attr("d","M"+x[0]+","+q*u+"V0H"+x[1]+"V"+q*u)):(n=to,w="y",k="x",S="y2",N="x2",C.attr("dy",".32em").style("text-anchor",0>q?"end":"start"),_.attr("d","M"+q*u+","+x[0]+"H0V"+x[1]+"H"+q*u)),E.attr(N,q*i),z.attr(k,q*M),A.attr(S,0).attr(N,q*i),L.attr(w,0).attr(k,q*M),s.rangeBand){var T=s,R=T.rangeBand()/2;f=s=function(n){return T(n)+R}}else f.rangeBand?f=s:d.call(n,s,f);v.call(n,f,s),y.call(n,s,s)})}var t,e=ao.scale.linear(),r=Vl,i=6,u=6,o=3,a=[10],l=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Xl?t+"":Vl,n):r},n.ticks=function(){return arguments.length?(a=co(arguments),n):a},n.tickValues=function(t){return arguments.length?(l=t,n):l},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(i=+t,u=+arguments[e-1],n):i},n.innerTickSize=function(t){return arguments.length?(i=+t,n):i},n.outerTickSize=function(t){return arguments.length?(u=+t,n):u},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var Vl="bottom",Xl={top:1,right:1,bottom:1,left:1};ao.svg.brush=function(){function n(t){t.each(function(){var t=ao.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=t.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),t.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=t.selectAll(".resize").data(v,m);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return $l[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,s=ao.transition(t),h=ao.transition(o);c&&(l=Zi(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(s)),f&&(l=Zi(f),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(s)),e(s)})}function e(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+s[+/e$/.test(n)]+","+h[+/^s/.test(n)]+")"})}function r(n){n.select(".extent").attr("x",s[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1]-s[0])}function i(n){n.select(".extent").attr("y",h[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function u(){function u(){32==ao.event.keyCode&&(C||(M=null,L[0]-=s[1],L[1]-=h[1],C=2),S())}function v(){32==ao.event.keyCode&&2==C&&(L[0]+=s[1],L[1]+=h[1],C=0,S())}function d(){var n=ao.mouse(b),t=!1;x&&(n[0]+=x[0],n[1]+=x[1]),C||(ao.event.altKey?(M||(M=[(s[0]+s[1])/2,(h[0]+h[1])/2]),L[0]=s[+(n[0]<M[0])],L[1]=h[+(n[1]<M[1])]):M=null),E&&y(n,c,0)&&(r(k),t=!0),A&&y(n,f,1)&&(i(k),t=!0),t&&(e(k),w({type:"brush",mode:C?"move":"resize"}))}function y(n,t,e){var r,i,u=Zi(t),l=u[0],c=u[1],f=L[e],v=e?h:s,d=v[1]-v[0];return C&&(l-=f,c-=d+f),r=(e?g:p)?Math.max(l,Math.min(c,n[e])):n[e],C?i=(r+=f)+d:(M&&(f=Math.max(l,Math.min(c,2*M[e]-r))),r>f?(i=r,r=f):i=f),v[0]!=r||v[1]!=i?(e?a=null:o=null,v[0]=r,v[1]=i,!0):void 0}function m(){d(),k.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),ao.select("body").style("cursor",null),q.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),z(),w({type:"brushend"})}var M,x,b=this,_=ao.select(ao.event.target),w=l.of(b,arguments),k=ao.select(b),N=_.datum(),E=!/^(n|s)$/.test(N)&&c,A=!/^(e|w)$/.test(N)&&f,C=_.classed("extent"),z=W(b),L=ao.mouse(b),q=ao.select(t(b)).on("keydown.brush",u).on("keyup.brush",v);if(ao.event.changedTouches?q.on("touchmove.brush",d).on("touchend.brush",m):q.on("mousemove.brush",d).on("mouseup.brush",m),k.interrupt().selectAll("*").interrupt(),C)L[0]=s[0]-L[0],L[1]=h[0]-L[1];else if(N){var T=+/w$/.test(N),R=+/^n/.test(N);x=[s[1-T]-L[0],h[1-R]-L[1]],L[0]=s[T],L[1]=h[R]}else ao.event.altKey&&(M=L.slice());k.style("pointer-events","none").selectAll(".resize").style("display",null),ao.select("body").style("cursor",_.style("cursor")),w({type:"brushstart"}),d()}var o,a,l=N(n,"brushstart","brush","brushend"),c=null,f=null,s=[0,0],h=[0,0],p=!0,g=!0,v=Bl[0];return n.event=function(n){n.each(function(){var n=l.of(this,arguments),t={x:s,y:h,i:o,j:a},e=this.__chart__||t;this.__chart__=t,Hl?ao.select(this).transition().each("start.brush",function(){o=e.i,a=e.j,s=e.x,h=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=xr(s,t.x),r=xr(h,t.y);return o=a=null,function(i){s=t.x=e(i),h=t.y=r(i),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i,a=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,v=Bl[!c<<1|!f],n):c},n.y=function(t){return arguments.length?(f=t,v=Bl[!c<<1|!f],n):f},n.clamp=function(t){return arguments.length?(c&&f?(p=!!t[0],g=!!t[1]):c?p=!!t:f&&(g=!!t),n):c&&f?[p,g]:c?p:f?g:null},n.extent=function(t){var e,r,i,u,l;return arguments.length?(c&&(e=t[0],r=t[1],f&&(e=e[0],r=r[0]),o=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(l=e,e=r,r=l),e==s[0]&&r==s[1]||(s=[e,r])),f&&(i=t[0],u=t[1],c&&(i=i[1],u=u[1]),a=[i,u],f.invert&&(i=f(i),u=f(u)),i>u&&(l=i,i=u,u=l),i==h[0]&&u==h[1]||(h=[i,u])),n):(c&&(o?(e=o[0],r=o[1]):(e=s[0],r=s[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(l=e,e=r,r=l))),f&&(a?(i=a[0],u=a[1]):(i=h[0],u=h[1],f.invert&&(i=f.invert(i),u=f.invert(u)),i>u&&(l=i,i=u,u=l))),c&&f?[[e,i],[r,u]]:c?[e,r]:f&&[i,u])},n.clear=function(){return n.empty()||(s=[0,0],h=[0,0],o=a=null),n},n.empty=function(){return!!c&&s[0]==s[1]||!!f&&h[0]==h[1]},ao.rebind(n,l,"on")};var $l={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Bl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Wl=ga.format=xa.timeFormat,Jl=Wl.utc,Gl=Jl("%Y-%m-%dT%H:%M:%S.%LZ");Wl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?eo:Gl,eo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},eo.toString=Gl.toString,ga.second=On(function(n){return new va(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),ga.seconds=ga.second.range,ga.seconds.utc=ga.second.utc.range,ga.minute=On(function(n){return new va(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),ga.minutes=ga.minute.range,ga.minutes.utc=ga.minute.utc.range,ga.hour=On(function(n){var t=n.getTimezoneOffset()/60;return new va(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),ga.hours=ga.hour.range,ga.hours.utc=ga.hour.utc.range,ga.month=On(function(n){return n=ga.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),ga.months=ga.month.range,ga.months.utc=ga.month.utc.range;var Kl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ql=[[ga.second,1],[ga.second,5],[ga.second,15],[ga.second,30],[ga.minute,1],[ga.minute,5],[ga.minute,15],[ga.minute,30],[ga.hour,1],[ga.hour,3],[ga.hour,6],[ga.hour,12],[ga.day,1],[ga.day,2],[ga.week,1],[ga.month,1],[ga.month,3],[ga.year,1]],nc=Wl.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",zt]]),tc={range:function(n,t,e){return ao.range(Math.ceil(n/e)*e,+t,e).map(io)},floor:m,ceil:m};Ql.year=ga.year,ga.scale=function(){return ro(ao.scale.linear(),Ql,nc)};var ec=Ql.map(function(n){return[n[0].utc,n[1]]}),rc=Jl.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",zt]]);ec.year=ga.year.utc,ga.scale.utc=function(){return ro(ao.scale.linear(),ec,rc)},ao.text=An(function(n){return n.responseText}),ao.json=function(n,t){return Cn(n,"application/json",uo,t)},ao.html=function(n,t){return Cn(n,"text/html",oo,t)},ao.xml=An(function(n){return n.responseXML}),"function"==typeof define&&define.amd?(this.d3=ao,define(ao)):"object"==typeof module&&module.exports?module.exports=ao:this.d3=ao}();/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}k.fn=k.prototype={jquery:f,constructor:k,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=k.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return k.each(this,e)},map:function(n){return this.pushStack(k.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},k.extend=k.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(k.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||k.isPlainObject(n)?n:{},i=!1,a[t]=k.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},k.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t){b(e,{nonce:t&&t.nonce})},each:function(e,t){var n,r=0;if(d(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(p,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(d(Object(e))?k.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(d(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g.apply([],a)},guid:1,support:y}),"function"==typeof Symbol&&(k.fn[Symbol.iterator]=t[Symbol.iterator]),k.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var h=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,k="sizzle"+1*new Date,m=n.document,S=0,r=0,p=ue(),x=ue(),N=ue(),A=ue(),D=function(e,t){return e===t&&(l=!0),0},j={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",$=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",F=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="<a id='"+k+"'></a><select id='"+k+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!==C&&T(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!==C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&j.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(D),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(F," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,v){var y="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===v?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=y!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(y){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===S&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[S,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===S&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[k]||(a[k]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[S,d]),a===e))break;return(d-=v)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[k]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace(B,"$1"));return s[k]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:ve(function(){return[0]}),last:ve(function(e,t){return[t-1]}),eq:ve(function(e,t,n){return[n<0?n+t:n]}),even:ve(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ve(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ve(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ve(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[S,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[k]||(e[k]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===S&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Ce(d,h,g,v,y,e){return v&&!v[k]&&(v=Ce(v)),y&&!y[k]&&(y=Ce(y,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?y||(e?d:l||v)?[]:t:f;if(g&&g(f,p,n,r),v){i=Te(p,u),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(y||d){if(y){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);y(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=y?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),y?y(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[k]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(B,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace(B," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,v,y,m,x,r,i=[],o=[],a=N[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[k]?i.push(a):o.push(a);(a=N(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=S+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t===C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument===C||(T(o),n=!E);while(s=v[a++])if(s(o,t||C,n)){r.push(o);break}i&&(S=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&se.uniqueSort(r)}return i&&(S=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ye(t.parentNode)||t),n},d.sortStable=k.split("").sort(D).join("")===k,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);k.find=h,k.expr=h.selectors,k.expr[":"]=k.expr.pseudos,k.uniqueSort=k.unique=h.uniqueSort,k.text=h.getText,k.isXMLDoc=h.isXML,k.contains=h.contains,k.escapeSelector=h.escape;var T=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&k(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},N=k.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var D=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1<i.call(n,e)!==r}):k.filter(n,e,r)}k.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?k.find.matchesSelector(r,e)?[r]:[]:k.find.matches(e,k.grep(t,function(e){return 1===e.nodeType}))},k.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(k(e).filter(function(){for(t=0;t<r;t++)if(k.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)k.find(e,i[t],n);return 1<r?k.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&N.test(e)?k(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(k.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&k(e);if(!N.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&k.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?k.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(k(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(k.uniqueSort(k.merge(this.get(),k(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),k.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return T(e,"parentNode")},parentsUntil:function(e,t,n){return T(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return T(e,"nextSibling")},prevAll:function(e){return T(e,"previousSibling")},nextUntil:function(e,t,n){return T(e,"nextSibling",n)},prevUntil:function(e,t,n){return T(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return"undefined"!=typeof e.contentDocument?e.contentDocument:(A(e,"template")&&(e=e.content||e),k.merge([],e.childNodes))}},function(r,i){k.fn[r]=function(e,t){var n=k.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=k.filter(t,n)),1<this.length&&(O[r]||k.uniqueSort(n),H.test(r)&&n.reverse()),this.pushStack(n)}});var R=/[^\x20\t\r\n\f]+/g;function M(e){return e}function I(e){throw e}function W(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}k.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},k.each(e.match(R)||[],function(e,t){n[t]=!0}),n):k.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){k.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return k.each(arguments,function(e,t){var n;while(-1<(n=k.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<k.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},k.extend({Deferred:function(e){var o=[["notify","progress",k.Callbacks("memory"),k.Callbacks("memory"),2],["resolve","done",k.Callbacks("once memory"),k.Callbacks("once memory"),0,"resolved"],["reject","fail",k.Callbacks("once memory"),k.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return k.Deferred(function(r){k.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,M,s),l(u,o,I,s)):(u++,t.call(e,l(u,o,M,s),l(u,o,I,s),l(u,o,M,o.notifyWith))):(a!==M&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){k.Deferred.exceptionHook&&k.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==I&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(k.Deferred.getStackHook&&(t.stackTrace=k.Deferred.getStackHook()),C.setTimeout(t))}}return k.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:M,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:M)),o[2][3].add(l(0,e,m(n)?n:I))}).promise()},promise:function(e){return null!=e?k.extend(e,a):a}},s={};return k.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=k.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(W(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)W(i[t],a(t),o.reject);return o.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;k.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&$.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},k.readyException=function(e){C.setTimeout(function(){throw e})};var F=k.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),C.removeEventListener("load",B),k.ready()}k.fn.ready=function(e){return F.then(e)["catch"](function(e){k.readyException(e)}),this},k.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--k.readyWait:k.isReady)||(k.isReady=!0)!==e&&0<--k.readyWait||F.resolveWith(E,[k])}}),k.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(k.ready):(E.addEventListener("DOMContentLoaded",B),C.addEventListener("load",B));var _=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)_(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(k(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},z=/^-ms-/,U=/-([a-z])/g;function X(e,t){return t.toUpperCase()}function V(e){return e.replace(z,"ms-").replace(U,X)}var G=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Y(){this.expando=k.expando+Y.uid++}Y.uid=1,Y.prototype={cache:function(e){var t=e[this.expando];return t||(t={},G(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[V(t)]=n;else for(r in t)i[V(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][V(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(V):(t=V(t))in r?[t]:t.match(R)||[]).length;while(n--)delete r[t[n]]}(void 0===t||k.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!k.isEmptyObject(t)}};var Q=new Y,J=new Y,K=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Z=/[A-Z]/g;function ee(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(Z,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:K.test(i)?JSON.parse(i):i)}catch(e){}J.set(e,t,n)}else n=void 0;return n}k.extend({hasData:function(e){return J.hasData(e)||Q.hasData(e)},data:function(e,t,n){return J.access(e,t,n)},removeData:function(e,t){J.remove(e,t)},_data:function(e,t,n){return Q.access(e,t,n)},_removeData:function(e,t){Q.remove(e,t)}}),k.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=J.get(o),1===o.nodeType&&!Q.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=V(r.slice(5)),ee(o,r,i[r]));Q.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){J.set(this,n)}):_(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=J.get(o,n))?t:void 0!==(t=ee(o,n))?t:void 0;this.each(function(){J.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){J.remove(this,e)})}}),k.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Q.get(e,t),n&&(!r||Array.isArray(n)?r=Q.access(e,t,k.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=k.queue(e,t),r=n.length,i=n.shift(),o=k._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){k.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Q.get(e,n)||Q.access(e,n,{empty:k.Callbacks("once memory").add(function(){Q.remove(e,[t+"queue",n])})})}}),k.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?k.queue(this[0],t):void 0===n?this:this.each(function(){var e=k.queue(this,t,n);k._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&k.dequeue(this,t)})},dequeue:function(e){return this.each(function(){k.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=k.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=Q.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var te=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ne=new RegExp("^(?:([+-])=|)("+te+")([a-z%]*)$","i"),re=["Top","Right","Bottom","Left"],ie=E.documentElement,oe=function(e){return k.contains(e.ownerDocument,e)},ae={composed:!0};ie.getRootNode&&(oe=function(e){return k.contains(e.ownerDocument,e)||e.getRootNode(ae)===e.ownerDocument});var se=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&oe(e)&&"none"===k.css(e,"display")},ue=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];for(o in i=n.apply(e,r||[]),t)e.style[o]=a[o];return i};function le(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return k.css(e,t,"")},u=s(),l=n&&n[3]||(k.cssNumber[t]?"":"px"),c=e.nodeType&&(k.cssNumber[t]||"px"!==l&&+u)&&ne.exec(k.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)k.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,k.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ce={};function fe(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Q.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&se(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ce[s])||(o=a.body.appendChild(a.createElement(s)),u=k.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ce[s]=u)))):"none"!==n&&(l[c]="none",Q.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}k.fn.extend({show:function(){return fe(this,!0)},hide:function(){return fe(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){se(this)?k(this).show():k(this).hide()})}});var pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n<r;n++)Q.set(e[n],"globalEval",!t||Q.get(t[n],"globalEval"))}ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;var me,xe,be=/<|&#?\w+;/;function we(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===w(o))k.merge(p,o.nodeType?[o]:o);else if(be.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+k.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;k.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<k.inArray(o,r))i&&i.push(o);else if(l=oe(o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}me=E.createDocumentFragment().appendChild(E.createElement("div")),(xe=E.createElement("input")).setAttribute("type","radio"),xe.setAttribute("checked","checked"),xe.setAttribute("name","t"),me.appendChild(xe),y.checkClone=me.cloneNode(!0).cloneNode(!0).lastChild.checked,me.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t<arguments.length;t++)u[t]=arguments[t];if(s.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,s)){a=k.event.handlers.call(this,s,l),t=0;while((i=a[t++])&&!s.isPropagationStopped()){s.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!s.isImmediatePropagationStopped())s.rnamespace&&!1!==o.namespace&&!s.rnamespace.test(o.namespace)||(s.handleObj=o,s.data=o.data,void 0!==(r=((k.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,u))&&!1===(s.result=r)&&(s.preventDefault(),s.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,s),s.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<k(i,this).index(l):k.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(k.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[k.expando]?e:new k.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click",ke),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Q.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},k.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},k.Event=function(e,t){if(!(this instanceof k.Event))return new k.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?ke:Se,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&k.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[k.expando]=!0},k.Event.prototype={constructor:k.Event,isDefaultPrevented:Se,isPropagationStopped:Se,isImmediatePropagationStopped:Se,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=ke,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=ke,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=ke,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},k.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&Te.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&Ce.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},k.event.addProp),k.each({focus:"focusin",blur:"focusout"},function(e,t){k.event.special[e]={setup:function(){return De(this,e,Ne),!1},trigger:function(){return De(this,e),!0},delegateType:t}}),k.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){k.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||k.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),k.fn.extend({on:function(e,t,n,r){return Ae(this,e,t,n,r)},one:function(e,t,n,r){return Ae(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,k(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Se),this.each(function(){k.event.remove(this,e,n,t)})}});var je=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/<script|<style|<link/i,Le=/checked\s*(?:[^=]|=\s*.checked.)/i,He=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n<r;n++)k.event.add(t,i,l[i][n]);J.hasData(e)&&(s=J.access(e),u=k.extend({},s),J.set(t,u))}}function Ie(n,r,i,o){r=g.apply([],r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!y.checkClone&&Le.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),Ie(t,r,i,o)});if(f&&(t=(e=we(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=k.map(ve(e,"script"),Pe)).length;c<f;c++)u=e,c!==p&&(u=k.clone(u,!0,!0),s&&k.merge(a,ve(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,k.map(a,Re),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Q.access(u,"globalEval")&&k.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?k._evalUrl&&!u.noModule&&k._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")}):b(u.textContent.replace(He,""),u,l))}return n}function We(e,t,n){for(var r,i=t?k.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||k.cleanData(ve(r)),r.parentNode&&(n&&oe(r)&&ye(ve(r,"script")),r.parentNode.removeChild(r));return e}k.extend({htmlPrefilter:function(e){return e.replace(je,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ve(e),a=a||ve(c),r=0,i=o.length;r<i;r++)Me(o[r],a[r]);else Me(e,c);return 0<(a=ve(c,"script")).length&&ye(a,!f&&ve(e,"script")),c},cleanData:function(e){for(var t,n,r,i=k.event.special,o=0;void 0!==(n=e[o]);o++)if(G(n)){if(t=n[Q.expando]){if(t.events)for(r in t.events)i[r]?k.event.remove(n,r):k.removeEvent(n,r,t.handle);n[Q.expando]=void 0}n[J.expando]&&(n[J.expando]=void 0)}}}),k.fn.extend({detach:function(e){return We(this,e,!0)},remove:function(e){return We(this,e)},text:function(e){return _(this,function(e){return void 0===e?k.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Ie(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Oe(this,e).appendChild(e)})},prepend:function(){return Ie(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Oe(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Ie(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Ie(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(k.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return k.clone(this,e,t)})},html:function(e){return _(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!qe.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=k.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(k.cleanData(ve(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return Ie(this,arguments,function(e){var t=this.parentNode;k.inArray(this,n)<0&&(k.cleanData(ve(this)),t&&t.replaceChild(e,this))},n)}}),k.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){k.fn[e]=function(e){for(var t,n=[],r=k(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),k(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var $e=new RegExp("^("+te+")(?!px)[a-z%]+$","i"),Fe=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},Be=new RegExp(re.join("|"),"i");function _e(e,t,n){var r,i,o,a,s=e.style;return(n=n||Fe(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||oe(e)||(a=k.style(e,t)),!y.pixelBoxStyles()&&$e.test(a)&&Be.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function ze(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(u){s.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",u.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",ie.appendChild(s).appendChild(u);var e=C.getComputedStyle(u);n="1%"!==e.top,a=12===t(e.marginLeft),u.style.right="60%",o=36===t(e.right),r=36===t(e.width),u.style.position="absolute",i=12===t(u.offsetWidth/3),ie.removeChild(s),u=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s=E.createElement("div"),u=E.createElement("div");u.style&&(u.style.backgroundClip="content-box",u.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===u.style.backgroundClip,k.extend(y,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),a},scrollboxSize:function(){return e(),i}}))}();var Ue=["Webkit","Moz","ms"],Xe=E.createElement("div").style,Ve={};function Ge(e){var t=k.cssProps[e]||Ve[e];return t||(e in Xe?e:Ve[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=Ue.length;while(n--)if((e=Ue[n]+t)in Xe)return e}(e)||e)}var Ye=/^(none|table(?!-c[ea]).+)/,Qe=/^--/,Je={position:"absolute",visibility:"hidden",display:"block"},Ke={letterSpacing:"0",fontWeight:"400"};function Ze(e,t,n){var r=ne.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function et(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=k.css(e,n+re[a],!0,i)),r?("content"===n&&(u-=k.css(e,"padding"+re[a],!0,i)),"margin"!==n&&(u-=k.css(e,"border"+re[a]+"Width",!0,i))):(u+=k.css(e,"padding"+re[a],!0,i),"padding"!==n?u+=k.css(e,"border"+re[a]+"Width",!0,i):s+=k.css(e,"border"+re[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function tt(e,t,n){var r=Fe(e),i=(!y.boxSizingReliable()||n)&&"border-box"===k.css(e,"boxSizing",!1,r),o=i,a=_e(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if($e.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||"auto"===a||!parseFloat(a)&&"inline"===k.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===k.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+et(e,t,n||(i?"border":"content"),o,r,a)+"px"}function nt(e,t,n,r,i){return new nt.prototype.init(e,t,n,r,i)}k.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=_e(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=V(t),u=Qe.test(t),l=e.style;if(u||(t=Ge(s)),a=k.cssHooks[t]||k.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=ne.exec(n))&&i[1]&&(n=le(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(k.cssNumber[s]?"":"px")),y.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=V(t);return Qe.test(t)||(t=Ge(s)),(a=k.cssHooks[t]||k.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=_e(e,t,r)),"normal"===i&&t in Ke&&(i=Ke[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),k.each(["height","width"],function(e,u){k.cssHooks[u]={get:function(e,t,n){if(t)return!Ye.test(k.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?tt(e,u,n):ue(e,Je,function(){return tt(e,u,n)})},set:function(e,t,n){var r,i=Fe(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===k.css(e,"boxSizing",!1,i),s=n?et(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-et(e,u,"border",!1,i)-.5)),s&&(r=ne.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=k.css(e,u)),Ze(0,t,s)}}}),k.cssHooks.marginLeft=ze(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(_e(e,"marginLeft"))||e.getBoundingClientRect().left-ue(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),k.each({margin:"",padding:"",border:"Width"},function(i,o){k.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+re[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(k.cssHooks[i+o].set=Ze)}),k.fn.extend({css:function(e,t){return _(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Fe(e),i=t.length;a<i;a++)o[t[a]]=k.css(e,t[a],!1,r);return o}return void 0!==n?k.style(e,t,n):k.css(e,t)},e,t,1<arguments.length)}}),((k.Tween=nt).prototype={constructor:nt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||k.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(k.cssNumber[n]?"":"px")},cur:function(){var e=nt.propHooks[this.prop];return e&&e.get?e.get(this):nt.propHooks._default.get(this)},run:function(e){var t,n=nt.propHooks[this.prop];return this.options.duration?this.pos=t=k.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):nt.propHooks._default.set(this),this}}).init.prototype=nt.prototype,(nt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=k.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){k.fx.step[e.prop]?k.fx.step[e.prop](e):1!==e.elem.nodeType||!k.cssHooks[e.prop]&&null==e.elem.style[Ge(e.prop)]?e.elem[e.prop]=e.now:k.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=nt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},k.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},k.fx=nt.prototype.init,k.fx.step={};var rt,it,ot,at,st=/^(?:toggle|show|hide)$/,ut=/queueHooks$/;function lt(){it&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(lt):C.setTimeout(lt,k.fx.interval),k.fx.tick())}function ct(){return C.setTimeout(function(){rt=void 0}),rt=Date.now()}function ft(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=re[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function pt(e,t,n){for(var r,i=(dt.tweeners[t]||[]).concat(dt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function dt(o,e,t){var n,a,r=0,i=dt.prefilters.length,s=k.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=rt||ct(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:k.extend({},e),opts:k.extend(!0,{specialEasing:{},easing:k.easing._default},t),originalProperties:e,originalOptions:t,startTime:rt||ct(),duration:t.duration,tweens:[],createTween:function(e,t){var n=k.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=V(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=k.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=dt.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(k._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return k.map(c,pt,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),k.fx.timer(k.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}k.Animation=k.extend(dt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return le(n.elem,e,ne.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(R);for(var n,r=0,i=e.length;r<i;r++)n=e[r],dt.tweeners[n]=dt.tweeners[n]||[],dt.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&se(e),v=Q.get(e,"fxshow");for(r in n.queue||(null==(a=k._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,k.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],st.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||k.style(e,r)}if((u=!k.isEmptyObject(t))||!k.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=Q.get(e,"display")),"none"===(c=k.css(e,"display"))&&(l?c=l:(fe([e],!0),l=e.style.display||l,c=k.css(e,"display"),fe([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===k.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(v?"hidden"in v&&(g=v.hidden):v=Q.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&fe([e],!0),p.done(function(){for(r in g||fe([e]),Q.remove(e,"fxshow"),d)k.style(e,r,d[r])})),u=pt(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?dt.prefilters.unshift(e):dt.prefilters.push(e)}}),k.speed=function(e,t,n){var r=e&&"object"==typeof e?k.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return k.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in k.fx.speeds?r.duration=k.fx.speeds[r.duration]:r.duration=k.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&k.dequeue(this,r.queue)},r},k.fn.extend({fadeTo:function(e,t,n,r){return this.filter(se).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=k.isEmptyObject(t),o=k.speed(e,n,r),a=function(){var e=dt(this,k.extend({},t),o);(i||Q.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&!1!==i&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=k.timers,r=Q.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&ut.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||k.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Q.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=k.timers,o=n?n.length:0;for(t.finish=!0,k.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),k.each(["toggle","show","hide"],function(e,r){var i=k.fn[r];k.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(ft(r,!0),e,t,n)}}),k.each({slideDown:ft("show"),slideUp:ft("hide"),slideToggle:ft("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){k.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),k.timers=[],k.fx.tick=function(){var e,t=0,n=k.timers;for(rt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||k.fx.stop(),rt=void 0},k.fx.timer=function(e){k.timers.push(e),k.fx.start()},k.fx.interval=13,k.fx.start=function(){it||(it=!0,lt())},k.fx.stop=function(){it=null},k.fx.speeds={slow:600,fast:200,_default:400},k.fn.delay=function(r,e){return r=k.fx&&k.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},ot=E.createElement("input"),at=E.createElement("select").appendChild(E.createElement("option")),ot.type="checkbox",y.checkOn=""!==ot.value,y.optSelected=at.selected,(ot=E.createElement("input")).value="t",ot.type="radio",y.radioValue="t"===ot.value;var ht,gt=k.expr.attrHandle;k.fn.extend({attr:function(e,t){return _(this,k.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){k.removeAttr(this,e)})}}),k.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?k.prop(e,t,n):(1===o&&k.isXMLDoc(e)||(i=k.attrHooks[t.toLowerCase()]||(k.expr.match.bool.test(t)?ht:void 0)),void 0!==n?null===n?void k.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=k.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(R);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),ht={set:function(e,t,n){return!1===t?k.removeAttr(e,n):e.setAttribute(n,n),n}},k.each(k.expr.match.bool.source.match(/\w+/g),function(e,t){var a=gt[t]||k.find.attr;gt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=gt[o],gt[o]=r,r=null!=a(e,t,n)?o:null,gt[o]=i),r}});var vt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;function mt(e){return(e.match(R)||[]).join(" ")}function xt(e){return e.getAttribute&&e.getAttribute("class")||""}function bt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(R)||[]}k.fn.extend({prop:function(e,t){return _(this,k.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[k.propFix[e]||e]})}}),k.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&k.isXMLDoc(e)||(t=k.propFix[t]||t,i=k.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=k.find.attr(e,"tabindex");return t?parseInt(t,10):vt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),y.optSelected||(k.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),k.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){k.propFix[this.toLowerCase()]=this}),k.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){k(this).addClass(t.call(this,e,xt(this)))});if((e=bt(t)).length)while(n=this[u++])if(i=xt(n),r=1===n.nodeType&&" "+mt(i)+" "){a=0;while(o=e[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=mt(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){k(this).removeClass(t.call(this,e,xt(this)))});if(!arguments.length)return this.attr("class","");if((e=bt(t)).length)while(n=this[u++])if(i=xt(n),r=1===n.nodeType&&" "+mt(i)+" "){a=0;while(o=e[a++])while(-1<r.indexOf(" "+o+" "))r=r.replace(" "+o+" "," ");i!==(s=mt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"===o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):m(i)?this.each(function(e){k(this).toggleClass(i.call(this,e,xt(this),t),t)}):this.each(function(){var e,t,n,r;if(a){t=0,n=k(this),r=bt(i);while(e=r[t++])n.hasClass(e)?n.removeClass(e):n.addClass(e)}else void 0!==i&&"boolean"!==o||((e=xt(this))&&Q.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===i?"":Q.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+mt(xt(n))+" ").indexOf(t))return!0;return!1}});var wt=/\r/g;k.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,k(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=k.map(t,function(e){return null==e?"":e+""})),(r=k.valHooks[this.type]||k.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=k.valHooks[t.type]||k.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(wt,""):null==e?"":e:void 0}}),k.extend({valHooks:{option:{get:function(e){var t=k.find.attr(e,"value");return null!=t?t:mt(k.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=k(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=k.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<k.inArray(k.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),k.each(["radio","checkbox"],function(){k.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<k.inArray(k(e).val(),t)}},y.checkOn||(k.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in C;var Tt=/^(?:focusinfocus|focusoutblur)$/,Ct=function(e){e.stopPropagation()};k.extend(k.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!Tt.test(d+k.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[k.expando]?e:new k.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:k.makeArray(t,[e]),c=k.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,Tt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Q.get(o,"events")||{})[e.type]&&Q.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&G(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!G(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),k.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,Ct),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,Ct),k.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=k.extend(new k.Event,n,{type:e,isSimulated:!0});k.event.trigger(r,null,t)}}),k.fn.extend({trigger:function(e,t){return this.each(function(){k.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return k.event.trigger(e,t,n,!0)}}),y.focusin||k.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){k.event.simulate(r,e.target,k.event.fix(e))};k.event.special[r]={setup:function(){var e=this.ownerDocument||this,t=Q.access(e,r);t||e.addEventListener(n,i,!0),Q.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this,t=Q.access(e,r)-1;t?Q.access(e,r,t):(e.removeEventListener(n,i,!0),Q.remove(e,r))}}});var Et=C.location,kt=Date.now(),St=/\?/;k.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||k.error("Invalid XML: "+e),t};var Nt=/\[\]$/,At=/\r?\n/g,Dt=/^(?:submit|button|image|reset|file)$/i,jt=/^(?:input|select|textarea|keygen)/i;function qt(n,e,r,i){var t;if(Array.isArray(e))k.each(e,function(e,t){r||Nt.test(n)?i(n,t):qt(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)qt(n+"["+t+"]",e[t],r,i)}k.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!k.isPlainObject(e))k.each(e,function(){i(this.name,this.value)});else for(n in e)qt(n,e[n],t,i);return r.join("&")},k.fn.extend({serialize:function(){return k.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=k.prop(this,"elements");return e?k.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!k(this).is(":disabled")&&jt.test(this.nodeName)&&!Dt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=k(this).val();return null==n?null:Array.isArray(n)?k.map(n,function(e){return{name:t.name,value:e.replace(At,"\r\n")}}):{name:t.name,value:n.replace(At,"\r\n")}}).get()}});var Lt=/%20/g,Ht=/#.*$/,Ot=/([?&])_=[^&]*/,Pt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Rt=/^(?:GET|HEAD)$/,Mt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Ft=E.createElement("a");function Bt(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(R)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function _t(t,i,o,a){var s={},u=t===Wt;function l(e){var r;return s[e]=!0,k.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function zt(e,t){var n,r,i=k.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&k.extend(!0,e,r),e}Ft.href=Et.href,k.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Et.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Et.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":k.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,k.ajaxSettings),t):zt(k.ajaxSettings,e)},ajaxPrefilter:Bt(It),ajaxTransport:Bt(Wt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=k.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?k(y):k.event,x=k.Deferred(),b=k.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=Pt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||Et.href)+"").replace(Mt,Et.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(R)||[""],null==v.crossDomain){r=E.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Ft.protocol+"//"+Ft.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=k.param(v.data,v.traditional)),_t(It,v,t,T),h)return T;for(i in(g=k.event&&v.global)&&0==k.active++&&k.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Rt.test(v.type),f=v.url.replace(Ht,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(Lt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(St.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(Ot,"$1"),o=(St.test(f)?"&":"?")+"_="+kt+++o),v.url=f+o),v.ifModified&&(k.lastModified[f]&&T.setRequestHeader("If-Modified-Since",k.lastModified[f]),k.etag[f]&&T.setRequestHeader("If-None-Match",k.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+$t+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=_t(Wt,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(v,T,n)),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(k.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(k.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--k.active||k.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return k.get(e,t,n,"json")},getScript:function(e,t){return k.get(e,void 0,t,"script")}}),k.each(["get","post"],function(e,i){k[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),k.ajax(k.extend({url:e,type:i,dataType:r,data:t,success:n},k.isPlainObject(e)&&e))}}),k._evalUrl=function(e,t){return k.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){k.globalEval(e,t)}})},k.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=k(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return m(n)?this.each(function(e){k(this).wrapInner(n.call(this,e))}):this.each(function(){var e=k(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){k(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){k(this).replaceWith(this.childNodes)}),this}}),k.expr.pseudos.hidden=function(e){return!k.expr.pseudos.visible(e)},k.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},k.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var Ut={0:200,1223:204},Xt=k.ajaxSettings.xhr();y.cors=!!Xt&&"withCredentials"in Xt,y.ajax=Xt=!!Xt,k.ajaxTransport(function(i){var o,a;if(y.cors||Xt&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Ut[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),k.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),k.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return k.globalEval(e),e}}}),k.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),k.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=k("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=mt(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&k.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?k("<div>").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}}),k.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),k.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),k.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||k.guid++,i},k.holdReady=function(e){e?k.readyWait++:k.ready(!0)},k.isArray=Array.isArray,k.parseJSON=JSON.parse,k.nodeName=A,k.isFunction=m,k.isWindow=x,k.camelCase=V,k.type=w,k.now=Date.now,k.isNumeric=function(e){var t=k.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return k});var Qt=C.jQuery,Jt=C.$;return k.noConflict=function(e){return C.$===k&&(C.$=Jt),e&&C.jQuery===k&&(C.jQuery=Qt),k},e||(C.jQuery=C.$=k),k});
/*!
  * Bootstrap v4.3.1 (https://getbootstrap.com/)
  * Copyright 2011-2019 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("jquery"),require("popper.js")):"function"==typeof define&&define.amd?define(["exports","jquery","popper.js"],e):e((t=t||self).bootstrap={},t.jQuery,t.Popper)}(this,function(t,g,u){"use strict";function i(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function s(t,e,n){return e&&i(t.prototype,e),n&&i(t,n),t}function l(o){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},e=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(e=e.concat(Object.getOwnPropertySymbols(r).filter(function(t){return Object.getOwnPropertyDescriptor(r,t).enumerable}))),e.forEach(function(t){var e,n,i;e=o,i=r[n=t],n in e?Object.defineProperty(e,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[n]=i})}return o}g=g&&g.hasOwnProperty("default")?g.default:g,u=u&&u.hasOwnProperty("default")?u.default:u;var e="transitionend";function n(t){var e=this,n=!1;return g(this).one(_.TRANSITION_END,function(){n=!0}),setTimeout(function(){n||_.triggerTransitionEnd(e)},t),this}var _={TRANSITION_END:"bsTransitionEnd",getUID:function(t){for(;t+=~~(1e6*Math.random()),document.getElementById(t););return t},getSelectorFromElement:function(t){var e=t.getAttribute("data-target");if(!e||"#"===e){var n=t.getAttribute("href");e=n&&"#"!==n?n.trim():""}try{return document.querySelector(e)?e:null}catch(t){return null}},getTransitionDurationFromElement:function(t){if(!t)return 0;var e=g(t).css("transition-duration"),n=g(t).css("transition-delay"),i=parseFloat(e),o=parseFloat(n);return i||o?(e=e.split(",")[0],n=n.split(",")[0],1e3*(parseFloat(e)+parseFloat(n))):0},reflow:function(t){return t.offsetHeight},triggerTransitionEnd:function(t){g(t).trigger(e)},supportsTransitionEnd:function(){return Boolean(e)},isElement:function(t){return(t[0]||t).nodeType},typeCheckConfig:function(t,e,n){for(var i in n)if(Object.prototype.hasOwnProperty.call(n,i)){var o=n[i],r=e[i],s=r&&_.isElement(r)?"element":(a=r,{}.toString.call(a).match(/\s([a-z]+)/i)[1].toLowerCase());if(!new RegExp(o).test(s))throw new Error(t.toUpperCase()+': Option "'+i+'" provided type "'+s+'" but expected type "'+o+'".')}var a},findShadowRoot:function(t){if(!document.documentElement.attachShadow)return null;if("function"!=typeof t.getRootNode)return t instanceof ShadowRoot?t:t.parentNode?_.findShadowRoot(t.parentNode):null;var e=t.getRootNode();return e instanceof ShadowRoot?e:null}};g.fn.emulateTransitionEnd=n,g.event.special[_.TRANSITION_END]={bindType:e,delegateType:e,handle:function(t){if(g(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}};var o="alert",r="bs.alert",a="."+r,c=g.fn[o],h={CLOSE:"close"+a,CLOSED:"closed"+a,CLICK_DATA_API:"click"+a+".data-api"},f="alert",d="fade",m="show",p=function(){function i(t){this._element=t}var t=i.prototype;return t.close=function(t){var e=this._element;t&&(e=this._getRootElement(t)),this._triggerCloseEvent(e).isDefaultPrevented()||this._removeElement(e)},t.dispose=function(){g.removeData(this._element,r),this._element=null},t._getRootElement=function(t){var e=_.getSelectorFromElement(t),n=!1;return e&&(n=document.querySelector(e)),n||(n=g(t).closest("."+f)[0]),n},t._triggerCloseEvent=function(t){var e=g.Event(h.CLOSE);return g(t).trigger(e),e},t._removeElement=function(e){var n=this;if(g(e).removeClass(m),g(e).hasClass(d)){var t=_.getTransitionDurationFromElement(e);g(e).one(_.TRANSITION_END,function(t){return n._destroyElement(e,t)}).emulateTransitionEnd(t)}else this._destroyElement(e)},t._destroyElement=function(t){g(t).detach().trigger(h.CLOSED).remove()},i._jQueryInterface=function(n){return this.each(function(){var t=g(this),e=t.data(r);e||(e=new i(this),t.data(r,e)),"close"===n&&e[n](this)})},i._handleDismiss=function(e){return function(t){t&&t.preventDefault(),e.close(this)}},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}}]),i}();g(document).on(h.CLICK_DATA_API,'[data-dismiss="alert"]',p._handleDismiss(new p)),g.fn[o]=p._jQueryInterface,g.fn[o].Constructor=p,g.fn[o].noConflict=function(){return g.fn[o]=c,p._jQueryInterface};var v="button",y="bs.button",E="."+y,C=".data-api",T=g.fn[v],S="active",b="btn",I="focus",D='[data-toggle^="button"]',w='[data-toggle="buttons"]',A='input:not([type="hidden"])',N=".active",O=".btn",k={CLICK_DATA_API:"click"+E+C,FOCUS_BLUR_DATA_API:"focus"+E+C+" blur"+E+C},P=function(){function n(t){this._element=t}var t=n.prototype;return t.toggle=function(){var t=!0,e=!0,n=g(this._element).closest(w)[0];if(n){var i=this._element.querySelector(A);if(i){if("radio"===i.type)if(i.checked&&this._element.classList.contains(S))t=!1;else{var o=n.querySelector(N);o&&g(o).removeClass(S)}if(t){if(i.hasAttribute("disabled")||n.hasAttribute("disabled")||i.classList.contains("disabled")||n.classList.contains("disabled"))return;i.checked=!this._element.classList.contains(S),g(i).trigger("change")}i.focus(),e=!1}}e&&this._element.setAttribute("aria-pressed",!this._element.classList.contains(S)),t&&g(this._element).toggleClass(S)},t.dispose=function(){g.removeData(this._element,y),this._element=null},n._jQueryInterface=function(e){return this.each(function(){var t=g(this).data(y);t||(t=new n(this),g(this).data(y,t)),"toggle"===e&&t[e]()})},s(n,null,[{key:"VERSION",get:function(){return"4.3.1"}}]),n}();g(document).on(k.CLICK_DATA_API,D,function(t){t.preventDefault();var e=t.target;g(e).hasClass(b)||(e=g(e).closest(O)),P._jQueryInterface.call(g(e),"toggle")}).on(k.FOCUS_BLUR_DATA_API,D,function(t){var e=g(t.target).closest(O)[0];g(e).toggleClass(I,/^focus(in)?$/.test(t.type))}),g.fn[v]=P._jQueryInterface,g.fn[v].Constructor=P,g.fn[v].noConflict=function(){return g.fn[v]=T,P._jQueryInterface};var L="carousel",j="bs.carousel",H="."+j,R=".data-api",x=g.fn[L],F={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0,touch:!0},U={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean",touch:"boolean"},W="next",q="prev",M="left",K="right",Q={SLIDE:"slide"+H,SLID:"slid"+H,KEYDOWN:"keydown"+H,MOUSEENTER:"mouseenter"+H,MOUSELEAVE:"mouseleave"+H,TOUCHSTART:"touchstart"+H,TOUCHMOVE:"touchmove"+H,TOUCHEND:"touchend"+H,POINTERDOWN:"pointerdown"+H,POINTERUP:"pointerup"+H,DRAG_START:"dragstart"+H,LOAD_DATA_API:"load"+H+R,CLICK_DATA_API:"click"+H+R},B="carousel",V="active",Y="slide",z="carousel-item-right",X="carousel-item-left",$="carousel-item-next",G="carousel-item-prev",J="pointer-event",Z=".active",tt=".active.carousel-item",et=".carousel-item",nt=".carousel-item img",it=".carousel-item-next, .carousel-item-prev",ot=".carousel-indicators",rt="[data-slide], [data-slide-to]",st='[data-ride="carousel"]',at={TOUCH:"touch",PEN:"pen"},lt=function(){function r(t,e){this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this.touchStartX=0,this.touchDeltaX=0,this._config=this._getConfig(e),this._element=t,this._indicatorsElement=this._element.querySelector(ot),this._touchSupported="ontouchstart"in document.documentElement||0<navigator.maxTouchPoints,this._pointerEvent=Boolean(window.PointerEvent||window.MSPointerEvent),this._addEventListeners()}var t=r.prototype;return t.next=function(){this._isSliding||this._slide(W)},t.nextWhenVisible=function(){!document.hidden&&g(this._element).is(":visible")&&"hidden"!==g(this._element).css("visibility")&&this.next()},t.prev=function(){this._isSliding||this._slide(q)},t.pause=function(t){t||(this._isPaused=!0),this._element.querySelector(it)&&(_.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null},t.cycle=function(t){t||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))},t.to=function(t){var e=this;this._activeElement=this._element.querySelector(tt);var n=this._getItemIndex(this._activeElement);if(!(t>this._items.length-1||t<0))if(this._isSliding)g(this._element).one(Q.SLID,function(){return e.to(t)});else{if(n===t)return this.pause(),void this.cycle();var i=n<t?W:q;this._slide(i,this._items[t])}},t.dispose=function(){g(this._element).off(H),g.removeData(this._element,j),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null},t._getConfig=function(t){return t=l({},F,t),_.typeCheckConfig(L,t,U),t},t._handleSwipe=function(){var t=Math.abs(this.touchDeltaX);if(!(t<=40)){var e=t/this.touchDeltaX;0<e&&this.prev(),e<0&&this.next()}},t._addEventListeners=function(){var e=this;this._config.keyboard&&g(this._element).on(Q.KEYDOWN,function(t){return e._keydown(t)}),"hover"===this._config.pause&&g(this._element).on(Q.MOUSEENTER,function(t){return e.pause(t)}).on(Q.MOUSELEAVE,function(t){return e.cycle(t)}),this._config.touch&&this._addTouchEventListeners()},t._addTouchEventListeners=function(){var n=this;if(this._touchSupported){var e=function(t){n._pointerEvent&&at[t.originalEvent.pointerType.toUpperCase()]?n.touchStartX=t.originalEvent.clientX:n._pointerEvent||(n.touchStartX=t.originalEvent.touches[0].clientX)},i=function(t){n._pointerEvent&&at[t.originalEvent.pointerType.toUpperCase()]&&(n.touchDeltaX=t.originalEvent.clientX-n.touchStartX),n._handleSwipe(),"hover"===n._config.pause&&(n.pause(),n.touchTimeout&&clearTimeout(n.touchTimeout),n.touchTimeout=setTimeout(function(t){return n.cycle(t)},500+n._config.interval))};g(this._element.querySelectorAll(nt)).on(Q.DRAG_START,function(t){return t.preventDefault()}),this._pointerEvent?(g(this._element).on(Q.POINTERDOWN,function(t){return e(t)}),g(this._element).on(Q.POINTERUP,function(t){return i(t)}),this._element.classList.add(J)):(g(this._element).on(Q.TOUCHSTART,function(t){return e(t)}),g(this._element).on(Q.TOUCHMOVE,function(t){var e;(e=t).originalEvent.touches&&1<e.originalEvent.touches.length?n.touchDeltaX=0:n.touchDeltaX=e.originalEvent.touches[0].clientX-n.touchStartX}),g(this._element).on(Q.TOUCHEND,function(t){return i(t)}))}},t._keydown=function(t){if(!/input|textarea/i.test(t.target.tagName))switch(t.which){case 37:t.preventDefault(),this.prev();break;case 39:t.preventDefault(),this.next()}},t._getItemIndex=function(t){return this._items=t&&t.parentNode?[].slice.call(t.parentNode.querySelectorAll(et)):[],this._items.indexOf(t)},t._getItemByDirection=function(t,e){var n=t===W,i=t===q,o=this._getItemIndex(e),r=this._items.length-1;if((i&&0===o||n&&o===r)&&!this._config.wrap)return e;var s=(o+(t===q?-1:1))%this._items.length;return-1===s?this._items[this._items.length-1]:this._items[s]},t._triggerSlideEvent=function(t,e){var n=this._getItemIndex(t),i=this._getItemIndex(this._element.querySelector(tt)),o=g.Event(Q.SLIDE,{relatedTarget:t,direction:e,from:i,to:n});return g(this._element).trigger(o),o},t._setActiveIndicatorElement=function(t){if(this._indicatorsElement){var e=[].slice.call(this._indicatorsElement.querySelectorAll(Z));g(e).removeClass(V);var n=this._indicatorsElement.children[this._getItemIndex(t)];n&&g(n).addClass(V)}},t._slide=function(t,e){var n,i,o,r=this,s=this._element.querySelector(tt),a=this._getItemIndex(s),l=e||s&&this._getItemByDirection(t,s),c=this._getItemIndex(l),h=Boolean(this._interval);if(o=t===W?(n=X,i=$,M):(n=z,i=G,K),l&&g(l).hasClass(V))this._isSliding=!1;else if(!this._triggerSlideEvent(l,o).isDefaultPrevented()&&s&&l){this._isSliding=!0,h&&this.pause(),this._setActiveIndicatorElement(l);var u=g.Event(Q.SLID,{relatedTarget:l,direction:o,from:a,to:c});if(g(this._element).hasClass(Y)){g(l).addClass(i),_.reflow(l),g(s).addClass(n),g(l).addClass(n);var f=parseInt(l.getAttribute("data-interval"),10);this._config.interval=f?(this._config.defaultInterval=this._config.defaultInterval||this._config.interval,f):this._config.defaultInterval||this._config.interval;var d=_.getTransitionDurationFromElement(s);g(s).one(_.TRANSITION_END,function(){g(l).removeClass(n+" "+i).addClass(V),g(s).removeClass(V+" "+i+" "+n),r._isSliding=!1,setTimeout(function(){return g(r._element).trigger(u)},0)}).emulateTransitionEnd(d)}else g(s).removeClass(V),g(l).addClass(V),this._isSliding=!1,g(this._element).trigger(u);h&&this.cycle()}},r._jQueryInterface=function(i){return this.each(function(){var t=g(this).data(j),e=l({},F,g(this).data());"object"==typeof i&&(e=l({},e,i));var n="string"==typeof i?i:e.slide;if(t||(t=new r(this,e),g(this).data(j,t)),"number"==typeof i)t.to(i);else if("string"==typeof n){if("undefined"==typeof t[n])throw new TypeError('No method named "'+n+'"');t[n]()}else e.interval&&e.ride&&(t.pause(),t.cycle())})},r._dataApiClickHandler=function(t){var e=_.getSelectorFromElement(this);if(e){var n=g(e)[0];if(n&&g(n).hasClass(B)){var i=l({},g(n).data(),g(this).data()),o=this.getAttribute("data-slide-to");o&&(i.interval=!1),r._jQueryInterface.call(g(n),i),o&&g(n).data(j).to(o),t.preventDefault()}}},s(r,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return F}}]),r}();g(document).on(Q.CLICK_DATA_API,rt,lt._dataApiClickHandler),g(window).on(Q.LOAD_DATA_API,function(){for(var t=[].slice.call(document.querySelectorAll(st)),e=0,n=t.length;e<n;e++){var i=g(t[e]);lt._jQueryInterface.call(i,i.data())}}),g.fn[L]=lt._jQueryInterface,g.fn[L].Constructor=lt,g.fn[L].noConflict=function(){return g.fn[L]=x,lt._jQueryInterface};var ct="collapse",ht="bs.collapse",ut="."+ht,ft=g.fn[ct],dt={toggle:!0,parent:""},gt={toggle:"boolean",parent:"(string|element)"},_t={SHOW:"show"+ut,SHOWN:"shown"+ut,HIDE:"hide"+ut,HIDDEN:"hidden"+ut,CLICK_DATA_API:"click"+ut+".data-api"},mt="show",pt="collapse",vt="collapsing",yt="collapsed",Et="width",Ct="height",Tt=".show, .collapsing",St='[data-toggle="collapse"]',bt=function(){function a(e,t){this._isTransitioning=!1,this._element=e,this._config=this._getConfig(t),this._triggerArray=[].slice.call(document.querySelectorAll('[data-toggle="collapse"][href="#'+e.id+'"],[data-toggle="collapse"][data-target="#'+e.id+'"]'));for(var n=[].slice.call(document.querySelectorAll(St)),i=0,o=n.length;i<o;i++){var r=n[i],s=_.getSelectorFromElement(r),a=[].slice.call(document.querySelectorAll(s)).filter(function(t){return t===e});null!==s&&0<a.length&&(this._selector=s,this._triggerArray.push(r))}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}var t=a.prototype;return t.toggle=function(){g(this._element).hasClass(mt)?this.hide():this.show()},t.show=function(){var t,e,n=this;if(!this._isTransitioning&&!g(this._element).hasClass(mt)&&(this._parent&&0===(t=[].slice.call(this._parent.querySelectorAll(Tt)).filter(function(t){return"string"==typeof n._config.parent?t.getAttribute("data-parent")===n._config.parent:t.classList.contains(pt)})).length&&(t=null),!(t&&(e=g(t).not(this._selector).data(ht))&&e._isTransitioning))){var i=g.Event(_t.SHOW);if(g(this._element).trigger(i),!i.isDefaultPrevented()){t&&(a._jQueryInterface.call(g(t).not(this._selector),"hide"),e||g(t).data(ht,null));var o=this._getDimension();g(this._element).removeClass(pt).addClass(vt),this._element.style[o]=0,this._triggerArray.length&&g(this._triggerArray).removeClass(yt).attr("aria-expanded",!0),this.setTransitioning(!0);var r="scroll"+(o[0].toUpperCase()+o.slice(1)),s=_.getTransitionDurationFromElement(this._element);g(this._element).one(_.TRANSITION_END,function(){g(n._element).removeClass(vt).addClass(pt).addClass(mt),n._element.style[o]="",n.setTransitioning(!1),g(n._element).trigger(_t.SHOWN)}).emulateTransitionEnd(s),this._element.style[o]=this._element[r]+"px"}}},t.hide=function(){var t=this;if(!this._isTransitioning&&g(this._element).hasClass(mt)){var e=g.Event(_t.HIDE);if(g(this._element).trigger(e),!e.isDefaultPrevented()){var n=this._getDimension();this._element.style[n]=this._element.getBoundingClientRect()[n]+"px",_.reflow(this._element),g(this._element).addClass(vt).removeClass(pt).removeClass(mt);var i=this._triggerArray.length;if(0<i)for(var o=0;o<i;o++){var r=this._triggerArray[o],s=_.getSelectorFromElement(r);if(null!==s)g([].slice.call(document.querySelectorAll(s))).hasClass(mt)||g(r).addClass(yt).attr("aria-expanded",!1)}this.setTransitioning(!0);this._element.style[n]="";var a=_.getTransitionDurationFromElement(this._element);g(this._element).one(_.TRANSITION_END,function(){t.setTransitioning(!1),g(t._element).removeClass(vt).addClass(pt).trigger(_t.HIDDEN)}).emulateTransitionEnd(a)}}},t.setTransitioning=function(t){this._isTransitioning=t},t.dispose=function(){g.removeData(this._element,ht),this._config=null,this._parent=null,this._element=null,this._triggerArray=null,this._isTransitioning=null},t._getConfig=function(t){return(t=l({},dt,t)).toggle=Boolean(t.toggle),_.typeCheckConfig(ct,t,gt),t},t._getDimension=function(){return g(this._element).hasClass(Et)?Et:Ct},t._getParent=function(){var t,n=this;_.isElement(this._config.parent)?(t=this._config.parent,"undefined"!=typeof this._config.parent.jquery&&(t=this._config.parent[0])):t=document.querySelector(this._config.parent);var e='[data-toggle="collapse"][data-parent="'+this._config.parent+'"]',i=[].slice.call(t.querySelectorAll(e));return g(i).each(function(t,e){n._addAriaAndCollapsedClass(a._getTargetFromElement(e),[e])}),t},t._addAriaAndCollapsedClass=function(t,e){var n=g(t).hasClass(mt);e.length&&g(e).toggleClass(yt,!n).attr("aria-expanded",n)},a._getTargetFromElement=function(t){var e=_.getSelectorFromElement(t);return e?document.querySelector(e):null},a._jQueryInterface=function(i){return this.each(function(){var t=g(this),e=t.data(ht),n=l({},dt,t.data(),"object"==typeof i&&i?i:{});if(!e&&n.toggle&&/show|hide/.test(i)&&(n.toggle=!1),e||(e=new a(this,n),t.data(ht,e)),"string"==typeof i){if("undefined"==typeof e[i])throw new TypeError('No method named "'+i+'"');e[i]()}})},s(a,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return dt}}]),a}();g(document).on(_t.CLICK_DATA_API,St,function(t){"A"===t.currentTarget.tagName&&t.preventDefault();var n=g(this),e=_.getSelectorFromElement(this),i=[].slice.call(document.querySelectorAll(e));g(i).each(function(){var t=g(this),e=t.data(ht)?"toggle":n.data();bt._jQueryInterface.call(t,e)})}),g.fn[ct]=bt._jQueryInterface,g.fn[ct].Constructor=bt,g.fn[ct].noConflict=function(){return g.fn[ct]=ft,bt._jQueryInterface};var It="dropdown",Dt="bs.dropdown",wt="."+Dt,At=".data-api",Nt=g.fn[It],Ot=new RegExp("38|40|27"),kt={HIDE:"hide"+wt,HIDDEN:"hidden"+wt,SHOW:"show"+wt,SHOWN:"shown"+wt,CLICK:"click"+wt,CLICK_DATA_API:"click"+wt+At,KEYDOWN_DATA_API:"keydown"+wt+At,KEYUP_DATA_API:"keyup"+wt+At},Pt="disabled",Lt="show",jt="dropup",Ht="dropright",Rt="dropleft",xt="dropdown-menu-right",Ft="position-static",Ut='[data-toggle="dropdown"]',Wt=".dropdown form",qt=".dropdown-menu",Mt=".navbar-nav",Kt=".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",Qt="top-start",Bt="top-end",Vt="bottom-start",Yt="bottom-end",zt="right-start",Xt="left-start",$t={offset:0,flip:!0,boundary:"scrollParent",reference:"toggle",display:"dynamic"},Gt={offset:"(number|string|function)",flip:"boolean",boundary:"(string|element)",reference:"(string|element)",display:"string"},Jt=function(){function c(t,e){this._element=t,this._popper=null,this._config=this._getConfig(e),this._menu=this._getMenuElement(),this._inNavbar=this._detectNavbar(),this._addEventListeners()}var t=c.prototype;return t.toggle=function(){if(!this._element.disabled&&!g(this._element).hasClass(Pt)){var t=c._getParentFromElement(this._element),e=g(this._menu).hasClass(Lt);if(c._clearMenus(),!e){var n={relatedTarget:this._element},i=g.Event(kt.SHOW,n);if(g(t).trigger(i),!i.isDefaultPrevented()){if(!this._inNavbar){if("undefined"==typeof u)throw new TypeError("Bootstrap's dropdowns require Popper.js (https://popper.js.org/)");var o=this._element;"parent"===this._config.reference?o=t:_.isElement(this._config.reference)&&(o=this._config.reference,"undefined"!=typeof this._config.reference.jquery&&(o=this._config.reference[0])),"scrollParent"!==this._config.boundary&&g(t).addClass(Ft),this._popper=new u(o,this._menu,this._getPopperConfig())}"ontouchstart"in document.documentElement&&0===g(t).closest(Mt).length&&g(document.body).children().on("mouseover",null,g.noop),this._element.focus(),this._element.setAttribute("aria-expanded",!0),g(this._menu).toggleClass(Lt),g(t).toggleClass(Lt).trigger(g.Event(kt.SHOWN,n))}}}},t.show=function(){if(!(this._element.disabled||g(this._element).hasClass(Pt)||g(this._menu).hasClass(Lt))){var t={relatedTarget:this._element},e=g.Event(kt.SHOW,t),n=c._getParentFromElement(this._element);g(n).trigger(e),e.isDefaultPrevented()||(g(this._menu).toggleClass(Lt),g(n).toggleClass(Lt).trigger(g.Event(kt.SHOWN,t)))}},t.hide=function(){if(!this._element.disabled&&!g(this._element).hasClass(Pt)&&g(this._menu).hasClass(Lt)){var t={relatedTarget:this._element},e=g.Event(kt.HIDE,t),n=c._getParentFromElement(this._element);g(n).trigger(e),e.isDefaultPrevented()||(g(this._menu).toggleClass(Lt),g(n).toggleClass(Lt).trigger(g.Event(kt.HIDDEN,t)))}},t.dispose=function(){g.removeData(this._element,Dt),g(this._element).off(wt),this._element=null,(this._menu=null)!==this._popper&&(this._popper.destroy(),this._popper=null)},t.update=function(){this._inNavbar=this._detectNavbar(),null!==this._popper&&this._popper.scheduleUpdate()},t._addEventListeners=function(){var e=this;g(this._element).on(kt.CLICK,function(t){t.preventDefault(),t.stopPropagation(),e.toggle()})},t._getConfig=function(t){return t=l({},this.constructor.Default,g(this._element).data(),t),_.typeCheckConfig(It,t,this.constructor.DefaultType),t},t._getMenuElement=function(){if(!this._menu){var t=c._getParentFromElement(this._element);t&&(this._menu=t.querySelector(qt))}return this._menu},t._getPlacement=function(){var t=g(this._element.parentNode),e=Vt;return t.hasClass(jt)?(e=Qt,g(this._menu).hasClass(xt)&&(e=Bt)):t.hasClass(Ht)?e=zt:t.hasClass(Rt)?e=Xt:g(this._menu).hasClass(xt)&&(e=Yt),e},t._detectNavbar=function(){return 0<g(this._element).closest(".navbar").length},t._getOffset=function(){var e=this,t={};return"function"==typeof this._config.offset?t.fn=function(t){return t.offsets=l({},t.offsets,e._config.offset(t.offsets,e._element)||{}),t}:t.offset=this._config.offset,t},t._getPopperConfig=function(){var t={placement:this._getPlacement(),modifiers:{offset:this._getOffset(),flip:{enabled:this._config.flip},preventOverflow:{boundariesElement:this._config.boundary}}};return"static"===this._config.display&&(t.modifiers.applyStyle={enabled:!1}),t},c._jQueryInterface=function(e){return this.each(function(){var t=g(this).data(Dt);if(t||(t=new c(this,"object"==typeof e?e:null),g(this).data(Dt,t)),"string"==typeof e){if("undefined"==typeof t[e])throw new TypeError('No method named "'+e+'"');t[e]()}})},c._clearMenus=function(t){if(!t||3!==t.which&&("keyup"!==t.type||9===t.which))for(var e=[].slice.call(document.querySelectorAll(Ut)),n=0,i=e.length;n<i;n++){var o=c._getParentFromElement(e[n]),r=g(e[n]).data(Dt),s={relatedTarget:e[n]};if(t&&"click"===t.type&&(s.clickEvent=t),r){var a=r._menu;if(g(o).hasClass(Lt)&&!(t&&("click"===t.type&&/input|textarea/i.test(t.target.tagName)||"keyup"===t.type&&9===t.which)&&g.contains(o,t.target))){var l=g.Event(kt.HIDE,s);g(o).trigger(l),l.isDefaultPrevented()||("ontouchstart"in document.documentElement&&g(document.body).children().off("mouseover",null,g.noop),e[n].setAttribute("aria-expanded","false"),g(a).removeClass(Lt),g(o).removeClass(Lt).trigger(g.Event(kt.HIDDEN,s)))}}}},c._getParentFromElement=function(t){var e,n=_.getSelectorFromElement(t);return n&&(e=document.querySelector(n)),e||t.parentNode},c._dataApiKeydownHandler=function(t){if((/input|textarea/i.test(t.target.tagName)?!(32===t.which||27!==t.which&&(40!==t.which&&38!==t.which||g(t.target).closest(qt).length)):Ot.test(t.which))&&(t.preventDefault(),t.stopPropagation(),!this.disabled&&!g(this).hasClass(Pt))){var e=c._getParentFromElement(this),n=g(e).hasClass(Lt);if(n&&(!n||27!==t.which&&32!==t.which)){var i=[].slice.call(e.querySelectorAll(Kt));if(0!==i.length){var o=i.indexOf(t.target);38===t.which&&0<o&&o--,40===t.which&&o<i.length-1&&o++,o<0&&(o=0),i[o].focus()}}else{if(27===t.which){var r=e.querySelector(Ut);g(r).trigger("focus")}g(this).trigger("click")}}},s(c,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return $t}},{key:"DefaultType",get:function(){return Gt}}]),c}();g(document).on(kt.KEYDOWN_DATA_API,Ut,Jt._dataApiKeydownHandler).on(kt.KEYDOWN_DATA_API,qt,Jt._dataApiKeydownHandler).on(kt.CLICK_DATA_API+" "+kt.KEYUP_DATA_API,Jt._clearMenus).on(kt.CLICK_DATA_API,Ut,function(t){t.preventDefault(),t.stopPropagation(),Jt._jQueryInterface.call(g(this),"toggle")}).on(kt.CLICK_DATA_API,Wt,function(t){t.stopPropagation()}),g.fn[It]=Jt._jQueryInterface,g.fn[It].Constructor=Jt,g.fn[It].noConflict=function(){return g.fn[It]=Nt,Jt._jQueryInterface};var Zt="modal",te="bs.modal",ee="."+te,ne=g.fn[Zt],ie={backdrop:!0,keyboard:!0,focus:!0,show:!0},oe={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean",show:"boolean"},re={HIDE:"hide"+ee,HIDDEN:"hidden"+ee,SHOW:"show"+ee,SHOWN:"shown"+ee,FOCUSIN:"focusin"+ee,RESIZE:"resize"+ee,CLICK_DISMISS:"click.dismiss"+ee,KEYDOWN_DISMISS:"keydown.dismiss"+ee,MOUSEUP_DISMISS:"mouseup.dismiss"+ee,MOUSEDOWN_DISMISS:"mousedown.dismiss"+ee,CLICK_DATA_API:"click"+ee+".data-api"},se="modal-dialog-scrollable",ae="modal-scrollbar-measure",le="modal-backdrop",ce="modal-open",he="fade",ue="show",fe=".modal-dialog",de=".modal-body",ge='[data-toggle="modal"]',_e='[data-dismiss="modal"]',me=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",pe=".sticky-top",ve=function(){function o(t,e){this._config=this._getConfig(e),this._element=t,this._dialog=t.querySelector(fe),this._backdrop=null,this._isShown=!1,this._isBodyOverflowing=!1,this._ignoreBackdropClick=!1,this._isTransitioning=!1,this._scrollbarWidth=0}var t=o.prototype;return t.toggle=function(t){return this._isShown?this.hide():this.show(t)},t.show=function(t){var e=this;if(!this._isShown&&!this._isTransitioning){g(this._element).hasClass(he)&&(this._isTransitioning=!0);var n=g.Event(re.SHOW,{relatedTarget:t});g(this._element).trigger(n),this._isShown||n.isDefaultPrevented()||(this._isShown=!0,this._checkScrollbar(),this._setScrollbar(),this._adjustDialog(),this._setEscapeEvent(),this._setResizeEvent(),g(this._element).on(re.CLICK_DISMISS,_e,function(t){return e.hide(t)}),g(this._dialog).on(re.MOUSEDOWN_DISMISS,function(){g(e._element).one(re.MOUSEUP_DISMISS,function(t){g(t.target).is(e._element)&&(e._ignoreBackdropClick=!0)})}),this._showBackdrop(function(){return e._showElement(t)}))}},t.hide=function(t){var e=this;if(t&&t.preventDefault(),this._isShown&&!this._isTransitioning){var n=g.Event(re.HIDE);if(g(this._element).trigger(n),this._isShown&&!n.isDefaultPrevented()){this._isShown=!1;var i=g(this._element).hasClass(he);if(i&&(this._isTransitioning=!0),this._setEscapeEvent(),this._setResizeEvent(),g(document).off(re.FOCUSIN),g(this._element).removeClass(ue),g(this._element).off(re.CLICK_DISMISS),g(this._dialog).off(re.MOUSEDOWN_DISMISS),i){var o=_.getTransitionDurationFromElement(this._element);g(this._element).one(_.TRANSITION_END,function(t){return e._hideModal(t)}).emulateTransitionEnd(o)}else this._hideModal()}}},t.dispose=function(){[window,this._element,this._dialog].forEach(function(t){return g(t).off(ee)}),g(document).off(re.FOCUSIN),g.removeData(this._element,te),this._config=null,this._element=null,this._dialog=null,this._backdrop=null,this._isShown=null,this._isBodyOverflowing=null,this._ignoreBackdropClick=null,this._isTransitioning=null,this._scrollbarWidth=null},t.handleUpdate=function(){this._adjustDialog()},t._getConfig=function(t){return t=l({},ie,t),_.typeCheckConfig(Zt,t,oe),t},t._showElement=function(t){var e=this,n=g(this._element).hasClass(he);this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),g(this._dialog).hasClass(se)?this._dialog.querySelector(de).scrollTop=0:this._element.scrollTop=0,n&&_.reflow(this._element),g(this._element).addClass(ue),this._config.focus&&this._enforceFocus();var i=g.Event(re.SHOWN,{relatedTarget:t}),o=function(){e._config.focus&&e._element.focus(),e._isTransitioning=!1,g(e._element).trigger(i)};if(n){var r=_.getTransitionDurationFromElement(this._dialog);g(this._dialog).one(_.TRANSITION_END,o).emulateTransitionEnd(r)}else o()},t._enforceFocus=function(){var e=this;g(document).off(re.FOCUSIN).on(re.FOCUSIN,function(t){document!==t.target&&e._element!==t.target&&0===g(e._element).has(t.target).length&&e._element.focus()})},t._setEscapeEvent=function(){var e=this;this._isShown&&this._config.keyboard?g(this._element).on(re.KEYDOWN_DISMISS,function(t){27===t.which&&(t.preventDefault(),e.hide())}):this._isShown||g(this._element).off(re.KEYDOWN_DISMISS)},t._setResizeEvent=function(){var e=this;this._isShown?g(window).on(re.RESIZE,function(t){return e.handleUpdate(t)}):g(window).off(re.RESIZE)},t._hideModal=function(){var t=this;this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._isTransitioning=!1,this._showBackdrop(function(){g(document.body).removeClass(ce),t._resetAdjustments(),t._resetScrollbar(),g(t._element).trigger(re.HIDDEN)})},t._removeBackdrop=function(){this._backdrop&&(g(this._backdrop).remove(),this._backdrop=null)},t._showBackdrop=function(t){var e=this,n=g(this._element).hasClass(he)?he:"";if(this._isShown&&this._config.backdrop){if(this._backdrop=document.createElement("div"),this._backdrop.className=le,n&&this._backdrop.classList.add(n),g(this._backdrop).appendTo(document.body),g(this._element).on(re.CLICK_DISMISS,function(t){e._ignoreBackdropClick?e._ignoreBackdropClick=!1:t.target===t.currentTarget&&("static"===e._config.backdrop?e._element.focus():e.hide())}),n&&_.reflow(this._backdrop),g(this._backdrop).addClass(ue),!t)return;if(!n)return void t();var i=_.getTransitionDurationFromElement(this._backdrop);g(this._backdrop).one(_.TRANSITION_END,t).emulateTransitionEnd(i)}else if(!this._isShown&&this._backdrop){g(this._backdrop).removeClass(ue);var o=function(){e._removeBackdrop(),t&&t()};if(g(this._element).hasClass(he)){var r=_.getTransitionDurationFromElement(this._backdrop);g(this._backdrop).one(_.TRANSITION_END,o).emulateTransitionEnd(r)}else o()}else t&&t()},t._adjustDialog=function(){var t=this._element.scrollHeight>document.documentElement.clientHeight;!this._isBodyOverflowing&&t&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!t&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},t._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},t._checkScrollbar=function(){var t=document.body.getBoundingClientRect();this._isBodyOverflowing=t.left+t.right<window.innerWidth,this._scrollbarWidth=this._getScrollbarWidth()},t._setScrollbar=function(){var o=this;if(this._isBodyOverflowing){var t=[].slice.call(document.querySelectorAll(me)),e=[].slice.call(document.querySelectorAll(pe));g(t).each(function(t,e){var n=e.style.paddingRight,i=g(e).css("padding-right");g(e).data("padding-right",n).css("padding-right",parseFloat(i)+o._scrollbarWidth+"px")}),g(e).each(function(t,e){var n=e.style.marginRight,i=g(e).css("margin-right");g(e).data("margin-right",n).css("margin-right",parseFloat(i)-o._scrollbarWidth+"px")});var n=document.body.style.paddingRight,i=g(document.body).css("padding-right");g(document.body).data("padding-right",n).css("padding-right",parseFloat(i)+this._scrollbarWidth+"px")}g(document.body).addClass(ce)},t._resetScrollbar=function(){var t=[].slice.call(document.querySelectorAll(me));g(t).each(function(t,e){var n=g(e).data("padding-right");g(e).removeData("padding-right"),e.style.paddingRight=n||""});var e=[].slice.call(document.querySelectorAll(""+pe));g(e).each(function(t,e){var n=g(e).data("margin-right");"undefined"!=typeof n&&g(e).css("margin-right",n).removeData("margin-right")});var n=g(document.body).data("padding-right");g(document.body).removeData("padding-right"),document.body.style.paddingRight=n||""},t._getScrollbarWidth=function(){var t=document.createElement("div");t.className=ae,document.body.appendChild(t);var e=t.getBoundingClientRect().width-t.clientWidth;return document.body.removeChild(t),e},o._jQueryInterface=function(n,i){return this.each(function(){var t=g(this).data(te),e=l({},ie,g(this).data(),"object"==typeof n&&n?n:{});if(t||(t=new o(this,e),g(this).data(te,t)),"string"==typeof n){if("undefined"==typeof t[n])throw new TypeError('No method named "'+n+'"');t[n](i)}else e.show&&t.show(i)})},s(o,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return ie}}]),o}();g(document).on(re.CLICK_DATA_API,ge,function(t){var e,n=this,i=_.getSelectorFromElement(this);i&&(e=document.querySelector(i));var o=g(e).data(te)?"toggle":l({},g(e).data(),g(this).data());"A"!==this.tagName&&"AREA"!==this.tagName||t.preventDefault();var r=g(e).one(re.SHOW,function(t){t.isDefaultPrevented()||r.one(re.HIDDEN,function(){g(n).is(":visible")&&n.focus()})});ve._jQueryInterface.call(g(e),o,this)}),g.fn[Zt]=ve._jQueryInterface,g.fn[Zt].Constructor=ve,g.fn[Zt].noConflict=function(){return g.fn[Zt]=ne,ve._jQueryInterface};var ye=["background","cite","href","itemtype","longdesc","poster","src","xlink:href"],Ee={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Ce=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi,Te=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;function Se(t,s,e){if(0===t.length)return t;if(e&&"function"==typeof e)return e(t);for(var n=(new window.DOMParser).parseFromString(t,"text/html"),a=Object.keys(s),l=[].slice.call(n.body.querySelectorAll("*")),i=function(t,e){var n=l[t],i=n.nodeName.toLowerCase();if(-1===a.indexOf(n.nodeName.toLowerCase()))return n.parentNode.removeChild(n),"continue";var o=[].slice.call(n.attributes),r=[].concat(s["*"]||[],s[i]||[]);o.forEach(function(t){(function(t,e){var n=t.nodeName.toLowerCase();if(-1!==e.indexOf(n))return-1===ye.indexOf(n)||Boolean(t.nodeValue.match(Ce)||t.nodeValue.match(Te));for(var i=e.filter(function(t){return t instanceof RegExp}),o=0,r=i.length;o<r;o++)if(n.match(i[o]))return!0;return!1})(t,r)||n.removeAttribute(t.nodeName)})},o=0,r=l.length;o<r;o++)i(o);return n.body.innerHTML}var be="tooltip",Ie="bs.tooltip",De="."+Ie,we=g.fn[be],Ae="bs-tooltip",Ne=new RegExp("(^|\\s)"+Ae+"\\S+","g"),Oe=["sanitize","whiteList","sanitizeFn"],ke={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(number|string|function)",container:"(string|element|boolean)",fallbackPlacement:"(string|array)",boundary:"(string|element)",sanitize:"boolean",sanitizeFn:"(null|function)",whiteList:"object"},Pe={AUTO:"auto",TOP:"top",RIGHT:"right",BOTTOM:"bottom",LEFT:"left"},Le={animation:!0,template:'<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent",sanitize:!0,sanitizeFn:null,whiteList:Ee},je="show",He="out",Re={HIDE:"hide"+De,HIDDEN:"hidden"+De,SHOW:"show"+De,SHOWN:"shown"+De,INSERTED:"inserted"+De,CLICK:"click"+De,FOCUSIN:"focusin"+De,FOCUSOUT:"focusout"+De,MOUSEENTER:"mouseenter"+De,MOUSELEAVE:"mouseleave"+De},xe="fade",Fe="show",Ue=".tooltip-inner",We=".arrow",qe="hover",Me="focus",Ke="click",Qe="manual",Be=function(){function i(t,e){if("undefined"==typeof u)throw new TypeError("Bootstrap's tooltips require Popper.js (https://popper.js.org/)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=t,this.config=this._getConfig(e),this.tip=null,this._setListeners()}var t=i.prototype;return t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.toggleEnabled=function(){this._isEnabled=!this._isEnabled},t.toggle=function(t){if(this._isEnabled)if(t){var e=this.constructor.DATA_KEY,n=g(t.currentTarget).data(e);n||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(e,n)),n._activeTrigger.click=!n._activeTrigger.click,n._isWithActiveTrigger()?n._enter(null,n):n._leave(null,n)}else{if(g(this.getTipElement()).hasClass(Fe))return void this._leave(null,this);this._enter(null,this)}},t.dispose=function(){clearTimeout(this._timeout),g.removeData(this.element,this.constructor.DATA_KEY),g(this.element).off(this.constructor.EVENT_KEY),g(this.element).closest(".modal").off("hide.bs.modal"),this.tip&&g(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,(this._activeTrigger=null)!==this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},t.show=function(){var e=this;if("none"===g(this.element).css("display"))throw new Error("Please use show on visible elements");var t=g.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){g(this.element).trigger(t);var n=_.findShadowRoot(this.element),i=g.contains(null!==n?n:this.element.ownerDocument.documentElement,this.element);if(t.isDefaultPrevented()||!i)return;var o=this.getTipElement(),r=_.getUID(this.constructor.NAME);o.setAttribute("id",r),this.element.setAttribute("aria-describedby",r),this.setContent(),this.config.animation&&g(o).addClass(xe);var s="function"==typeof this.config.placement?this.config.placement.call(this,o,this.element):this.config.placement,a=this._getAttachment(s);this.addAttachmentClass(a);var l=this._getContainer();g(o).data(this.constructor.DATA_KEY,this),g.contains(this.element.ownerDocument.documentElement,this.tip)||g(o).appendTo(l),g(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new u(this.element,o,{placement:a,modifiers:{offset:this._getOffset(),flip:{behavior:this.config.fallbackPlacement},arrow:{element:We},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(t){t.originalPlacement!==t.placement&&e._handlePopperPlacementChange(t)},onUpdate:function(t){return e._handlePopperPlacementChange(t)}}),g(o).addClass(Fe),"ontouchstart"in document.documentElement&&g(document.body).children().on("mouseover",null,g.noop);var c=function(){e.config.animation&&e._fixTransition();var t=e._hoverState;e._hoverState=null,g(e.element).trigger(e.constructor.Event.SHOWN),t===He&&e._leave(null,e)};if(g(this.tip).hasClass(xe)){var h=_.getTransitionDurationFromElement(this.tip);g(this.tip).one(_.TRANSITION_END,c).emulateTransitionEnd(h)}else c()}},t.hide=function(t){var e=this,n=this.getTipElement(),i=g.Event(this.constructor.Event.HIDE),o=function(){e._hoverState!==je&&n.parentNode&&n.parentNode.removeChild(n),e._cleanTipClass(),e.element.removeAttribute("aria-describedby"),g(e.element).trigger(e.constructor.Event.HIDDEN),null!==e._popper&&e._popper.destroy(),t&&t()};if(g(this.element).trigger(i),!i.isDefaultPrevented()){if(g(n).removeClass(Fe),"ontouchstart"in document.documentElement&&g(document.body).children().off("mouseover",null,g.noop),this._activeTrigger[Ke]=!1,this._activeTrigger[Me]=!1,this._activeTrigger[qe]=!1,g(this.tip).hasClass(xe)){var r=_.getTransitionDurationFromElement(n);g(n).one(_.TRANSITION_END,o).emulateTransitionEnd(r)}else o();this._hoverState=""}},t.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},t.isWithContent=function(){return Boolean(this.getTitle())},t.addAttachmentClass=function(t){g(this.getTipElement()).addClass(Ae+"-"+t)},t.getTipElement=function(){return this.tip=this.tip||g(this.config.template)[0],this.tip},t.setContent=function(){var t=this.getTipElement();this.setElementContent(g(t.querySelectorAll(Ue)),this.getTitle()),g(t).removeClass(xe+" "+Fe)},t.setElementContent=function(t,e){"object"!=typeof e||!e.nodeType&&!e.jquery?this.config.html?(this.config.sanitize&&(e=Se(e,this.config.whiteList,this.config.sanitizeFn)),t.html(e)):t.text(e):this.config.html?g(e).parent().is(t)||t.empty().append(e):t.text(g(e).text())},t.getTitle=function(){var t=this.element.getAttribute("data-original-title");return t||(t="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),t},t._getOffset=function(){var e=this,t={};return"function"==typeof this.config.offset?t.fn=function(t){return t.offsets=l({},t.offsets,e.config.offset(t.offsets,e.element)||{}),t}:t.offset=this.config.offset,t},t._getContainer=function(){return!1===this.config.container?document.body:_.isElement(this.config.container)?g(this.config.container):g(document).find(this.config.container)},t._getAttachment=function(t){return Pe[t.toUpperCase()]},t._setListeners=function(){var i=this;this.config.trigger.split(" ").forEach(function(t){if("click"===t)g(i.element).on(i.constructor.Event.CLICK,i.config.selector,function(t){return i.toggle(t)});else if(t!==Qe){var e=t===qe?i.constructor.Event.MOUSEENTER:i.constructor.Event.FOCUSIN,n=t===qe?i.constructor.Event.MOUSELEAVE:i.constructor.Event.FOCUSOUT;g(i.element).on(e,i.config.selector,function(t){return i._enter(t)}).on(n,i.config.selector,function(t){return i._leave(t)})}}),g(this.element).closest(".modal").on("hide.bs.modal",function(){i.element&&i.hide()}),this.config.selector?this.config=l({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},t._fixTitle=function(){var t=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==t)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},t._enter=function(t,e){var n=this.constructor.DATA_KEY;(e=e||g(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusin"===t.type?Me:qe]=!0),g(e.getTipElement()).hasClass(Fe)||e._hoverState===je?e._hoverState=je:(clearTimeout(e._timeout),e._hoverState=je,e.config.delay&&e.config.delay.show?e._timeout=setTimeout(function(){e._hoverState===je&&e.show()},e.config.delay.show):e.show())},t._leave=function(t,e){var n=this.constructor.DATA_KEY;(e=e||g(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusout"===t.type?Me:qe]=!1),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState=He,e.config.delay&&e.config.delay.hide?e._timeout=setTimeout(function(){e._hoverState===He&&e.hide()},e.config.delay.hide):e.hide())},t._isWithActiveTrigger=function(){for(var t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1},t._getConfig=function(t){var e=g(this.element).data();return Object.keys(e).forEach(function(t){-1!==Oe.indexOf(t)&&delete e[t]}),"number"==typeof(t=l({},this.constructor.Default,e,"object"==typeof t&&t?t:{})).delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),_.typeCheckConfig(be,t,this.constructor.DefaultType),t.sanitize&&(t.template=Se(t.template,t.whiteList,t.sanitizeFn)),t},t._getDelegateConfig=function(){var t={};if(this.config)for(var e in this.config)this.constructor.Default[e]!==this.config[e]&&(t[e]=this.config[e]);return t},t._cleanTipClass=function(){var t=g(this.getTipElement()),e=t.attr("class").match(Ne);null!==e&&e.length&&t.removeClass(e.join(""))},t._handlePopperPlacementChange=function(t){var e=t.instance;this.tip=e.popper,this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(t.placement))},t._fixTransition=function(){var t=this.getTipElement(),e=this.config.animation;null===t.getAttribute("x-placement")&&(g(t).removeClass(xe),this.config.animation=!1,this.hide(),this.show(),this.config.animation=e)},i._jQueryInterface=function(n){return this.each(function(){var t=g(this).data(Ie),e="object"==typeof n&&n;if((t||!/dispose|hide/.test(n))&&(t||(t=new i(this,e),g(this).data(Ie,t)),"string"==typeof n)){if("undefined"==typeof t[n])throw new TypeError('No method named "'+n+'"');t[n]()}})},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return Le}},{key:"NAME",get:function(){return be}},{key:"DATA_KEY",get:function(){return Ie}},{key:"Event",get:function(){return Re}},{key:"EVENT_KEY",get:function(){return De}},{key:"DefaultType",get:function(){return ke}}]),i}();g.fn[be]=Be._jQueryInterface,g.fn[be].Constructor=Be,g.fn[be].noConflict=function(){return g.fn[be]=we,Be._jQueryInterface};var Ve="popover",Ye="bs.popover",ze="."+Ye,Xe=g.fn[Ve],$e="bs-popover",Ge=new RegExp("(^|\\s)"+$e+"\\S+","g"),Je=l({},Be.Default,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'}),Ze=l({},Be.DefaultType,{content:"(string|element|function)"}),tn="fade",en="show",nn=".popover-header",on=".popover-body",rn={HIDE:"hide"+ze,HIDDEN:"hidden"+ze,SHOW:"show"+ze,SHOWN:"shown"+ze,INSERTED:"inserted"+ze,CLICK:"click"+ze,FOCUSIN:"focusin"+ze,FOCUSOUT:"focusout"+ze,MOUSEENTER:"mouseenter"+ze,MOUSELEAVE:"mouseleave"+ze},sn=function(t){var e,n;function i(){return t.apply(this,arguments)||this}n=t,(e=i).prototype=Object.create(n.prototype),(e.prototype.constructor=e).__proto__=n;var o=i.prototype;return o.isWithContent=function(){return this.getTitle()||this._getContent()},o.addAttachmentClass=function(t){g(this.getTipElement()).addClass($e+"-"+t)},o.getTipElement=function(){return this.tip=this.tip||g(this.config.template)[0],this.tip},o.setContent=function(){var t=g(this.getTipElement());this.setElementContent(t.find(nn),this.getTitle());var e=this._getContent();"function"==typeof e&&(e=e.call(this.element)),this.setElementContent(t.find(on),e),t.removeClass(tn+" "+en)},o._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},o._cleanTipClass=function(){var t=g(this.getTipElement()),e=t.attr("class").match(Ge);null!==e&&0<e.length&&t.removeClass(e.join(""))},i._jQueryInterface=function(n){return this.each(function(){var t=g(this).data(Ye),e="object"==typeof n?n:null;if((t||!/dispose|hide/.test(n))&&(t||(t=new i(this,e),g(this).data(Ye,t)),"string"==typeof n)){if("undefined"==typeof t[n])throw new TypeError('No method named "'+n+'"');t[n]()}})},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return Je}},{key:"NAME",get:function(){return Ve}},{key:"DATA_KEY",get:function(){return Ye}},{key:"Event",get:function(){return rn}},{key:"EVENT_KEY",get:function(){return ze}},{key:"DefaultType",get:function(){return Ze}}]),i}(Be);g.fn[Ve]=sn._jQueryInterface,g.fn[Ve].Constructor=sn,g.fn[Ve].noConflict=function(){return g.fn[Ve]=Xe,sn._jQueryInterface};var an="scrollspy",ln="bs.scrollspy",cn="."+ln,hn=g.fn[an],un={offset:10,method:"auto",target:""},fn={offset:"number",method:"string",target:"(string|element)"},dn={ACTIVATE:"activate"+cn,SCROLL:"scroll"+cn,LOAD_DATA_API:"load"+cn+".data-api"},gn="dropdown-item",_n="active",mn='[data-spy="scroll"]',pn=".nav, .list-group",vn=".nav-link",yn=".nav-item",En=".list-group-item",Cn=".dropdown",Tn=".dropdown-item",Sn=".dropdown-toggle",bn="offset",In="position",Dn=function(){function n(t,e){var n=this;this._element=t,this._scrollElement="BODY"===t.tagName?window:t,this._config=this._getConfig(e),this._selector=this._config.target+" "+vn+","+this._config.target+" "+En+","+this._config.target+" "+Tn,this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,g(this._scrollElement).on(dn.SCROLL,function(t){return n._process(t)}),this.refresh(),this._process()}var t=n.prototype;return t.refresh=function(){var e=this,t=this._scrollElement===this._scrollElement.window?bn:In,o="auto"===this._config.method?t:this._config.method,r=o===In?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight(),[].slice.call(document.querySelectorAll(this._selector)).map(function(t){var e,n=_.getSelectorFromElement(t);if(n&&(e=document.querySelector(n)),e){var i=e.getBoundingClientRect();if(i.width||i.height)return[g(e)[o]().top+r,n]}return null}).filter(function(t){return t}).sort(function(t,e){return t[0]-e[0]}).forEach(function(t){e._offsets.push(t[0]),e._targets.push(t[1])})},t.dispose=function(){g.removeData(this._element,ln),g(this._scrollElement).off(cn),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},t._getConfig=function(t){if("string"!=typeof(t=l({},un,"object"==typeof t&&t?t:{})).target){var e=g(t.target).attr("id");e||(e=_.getUID(an),g(t.target).attr("id",e)),t.target="#"+e}return _.typeCheckConfig(an,t,fn),t},t._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop},t._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},t._getOffsetHeight=function(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height},t._process=function(){var t=this._getScrollTop()+this._config.offset,e=this._getScrollHeight(),n=this._config.offset+e-this._getOffsetHeight();if(this._scrollHeight!==e&&this.refresh(),n<=t){var i=this._targets[this._targets.length-1];this._activeTarget!==i&&this._activate(i)}else{if(this._activeTarget&&t<this._offsets[0]&&0<this._offsets[0])return this._activeTarget=null,void this._clear();for(var o=this._offsets.length;o--;){this._activeTarget!==this._targets[o]&&t>=this._offsets[o]&&("undefined"==typeof this._offsets[o+1]||t<this._offsets[o+1])&&this._activate(this._targets[o])}}},t._activate=function(e){this._activeTarget=e,this._clear();var t=this._selector.split(",").map(function(t){return t+'[data-target="'+e+'"],'+t+'[href="'+e+'"]'}),n=g([].slice.call(document.querySelectorAll(t.join(","))));n.hasClass(gn)?(n.closest(Cn).find(Sn).addClass(_n),n.addClass(_n)):(n.addClass(_n),n.parents(pn).prev(vn+", "+En).addClass(_n),n.parents(pn).prev(yn).children(vn).addClass(_n)),g(this._scrollElement).trigger(dn.ACTIVATE,{relatedTarget:e})},t._clear=function(){[].slice.call(document.querySelectorAll(this._selector)).filter(function(t){return t.classList.contains(_n)}).forEach(function(t){return t.classList.remove(_n)})},n._jQueryInterface=function(e){return this.each(function(){var t=g(this).data(ln);if(t||(t=new n(this,"object"==typeof e&&e),g(this).data(ln,t)),"string"==typeof e){if("undefined"==typeof t[e])throw new TypeError('No method named "'+e+'"');t[e]()}})},s(n,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return un}}]),n}();g(window).on(dn.LOAD_DATA_API,function(){for(var t=[].slice.call(document.querySelectorAll(mn)),e=t.length;e--;){var n=g(t[e]);Dn._jQueryInterface.call(n,n.data())}}),g.fn[an]=Dn._jQueryInterface,g.fn[an].Constructor=Dn,g.fn[an].noConflict=function(){return g.fn[an]=hn,Dn._jQueryInterface};var wn="bs.tab",An="."+wn,Nn=g.fn.tab,On={HIDE:"hide"+An,HIDDEN:"hidden"+An,SHOW:"show"+An,SHOWN:"shown"+An,CLICK_DATA_API:"click"+An+".data-api"},kn="dropdown-menu",Pn="active",Ln="disabled",jn="fade",Hn="show",Rn=".dropdown",xn=".nav, .list-group",Fn=".active",Un="> li > .active",Wn='[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',qn=".dropdown-toggle",Mn="> .dropdown-menu .active",Kn=function(){function i(t){this._element=t}var t=i.prototype;return t.show=function(){var n=this;if(!(this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE&&g(this._element).hasClass(Pn)||g(this._element).hasClass(Ln))){var t,i,e=g(this._element).closest(xn)[0],o=_.getSelectorFromElement(this._element);if(e){var r="UL"===e.nodeName||"OL"===e.nodeName?Un:Fn;i=(i=g.makeArray(g(e).find(r)))[i.length-1]}var s=g.Event(On.HIDE,{relatedTarget:this._element}),a=g.Event(On.SHOW,{relatedTarget:i});if(i&&g(i).trigger(s),g(this._element).trigger(a),!a.isDefaultPrevented()&&!s.isDefaultPrevented()){o&&(t=document.querySelector(o)),this._activate(this._element,e);var l=function(){var t=g.Event(On.HIDDEN,{relatedTarget:n._element}),e=g.Event(On.SHOWN,{relatedTarget:i});g(i).trigger(t),g(n._element).trigger(e)};t?this._activate(t,t.parentNode,l):l()}}},t.dispose=function(){g.removeData(this._element,wn),this._element=null},t._activate=function(t,e,n){var i=this,o=(!e||"UL"!==e.nodeName&&"OL"!==e.nodeName?g(e).children(Fn):g(e).find(Un))[0],r=n&&o&&g(o).hasClass(jn),s=function(){return i._transitionComplete(t,o,n)};if(o&&r){var a=_.getTransitionDurationFromElement(o);g(o).removeClass(Hn).one(_.TRANSITION_END,s).emulateTransitionEnd(a)}else s()},t._transitionComplete=function(t,e,n){if(e){g(e).removeClass(Pn);var i=g(e.parentNode).find(Mn)[0];i&&g(i).removeClass(Pn),"tab"===e.getAttribute("role")&&e.setAttribute("aria-selected",!1)}if(g(t).addClass(Pn),"tab"===t.getAttribute("role")&&t.setAttribute("aria-selected",!0),_.reflow(t),t.classList.contains(jn)&&t.classList.add(Hn),t.parentNode&&g(t.parentNode).hasClass(kn)){var o=g(t).closest(Rn)[0];if(o){var r=[].slice.call(o.querySelectorAll(qn));g(r).addClass(Pn)}t.setAttribute("aria-expanded",!0)}n&&n()},i._jQueryInterface=function(n){return this.each(function(){var t=g(this),e=t.data(wn);if(e||(e=new i(this),t.data(wn,e)),"string"==typeof n){if("undefined"==typeof e[n])throw new TypeError('No method named "'+n+'"');e[n]()}})},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}}]),i}();g(document).on(On.CLICK_DATA_API,Wn,function(t){t.preventDefault(),Kn._jQueryInterface.call(g(this),"show")}),g.fn.tab=Kn._jQueryInterface,g.fn.tab.Constructor=Kn,g.fn.tab.noConflict=function(){return g.fn.tab=Nn,Kn._jQueryInterface};var Qn="toast",Bn="bs.toast",Vn="."+Bn,Yn=g.fn[Qn],zn={CLICK_DISMISS:"click.dismiss"+Vn,HIDE:"hide"+Vn,HIDDEN:"hidden"+Vn,SHOW:"show"+Vn,SHOWN:"shown"+Vn},Xn="fade",$n="hide",Gn="show",Jn="showing",Zn={animation:"boolean",autohide:"boolean",delay:"number"},ti={animation:!0,autohide:!0,delay:500},ei='[data-dismiss="toast"]',ni=function(){function i(t,e){this._element=t,this._config=this._getConfig(e),this._timeout=null,this._setListeners()}var t=i.prototype;return t.show=function(){var t=this;g(this._element).trigger(zn.SHOW),this._config.animation&&this._element.classList.add(Xn);var e=function(){t._element.classList.remove(Jn),t._element.classList.add(Gn),g(t._element).trigger(zn.SHOWN),t._config.autohide&&t.hide()};if(this._element.classList.remove($n),this._element.classList.add(Jn),this._config.animation){var n=_.getTransitionDurationFromElement(this._element);g(this._element).one(_.TRANSITION_END,e).emulateTransitionEnd(n)}else e()},t.hide=function(t){var e=this;this._element.classList.contains(Gn)&&(g(this._element).trigger(zn.HIDE),t?this._close():this._timeout=setTimeout(function(){e._close()},this._config.delay))},t.dispose=function(){clearTimeout(this._timeout),this._timeout=null,this._element.classList.contains(Gn)&&this._element.classList.remove(Gn),g(this._element).off(zn.CLICK_DISMISS),g.removeData(this._element,Bn),this._element=null,this._config=null},t._getConfig=function(t){return t=l({},ti,g(this._element).data(),"object"==typeof t&&t?t:{}),_.typeCheckConfig(Qn,t,this.constructor.DefaultType),t},t._setListeners=function(){var t=this;g(this._element).on(zn.CLICK_DISMISS,ei,function(){return t.hide(!0)})},t._close=function(){var t=this,e=function(){t._element.classList.add($n),g(t._element).trigger(zn.HIDDEN)};if(this._element.classList.remove(Gn),this._config.animation){var n=_.getTransitionDurationFromElement(this._element);g(this._element).one(_.TRANSITION_END,e).emulateTransitionEnd(n)}else e()},i._jQueryInterface=function(n){return this.each(function(){var t=g(this),e=t.data(Bn);if(e||(e=new i(this,"object"==typeof n&&n),t.data(Bn,e)),"string"==typeof n){if("undefined"==typeof e[n])throw new TypeError('No method named "'+n+'"');e[n](this)}})},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"DefaultType",get:function(){return Zn}},{key:"Default",get:function(){return ti}}]),i}();g.fn[Qn]=ni._jQueryInterface,g.fn[Qn].Constructor=ni,g.fn[Qn].noConflict=function(){return g.fn[Qn]=Yn,ni._jQueryInterface},function(){if("undefined"==typeof g)throw new TypeError("Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.");var t=g.fn.jquery.split(" ")[0].split(".");if(t[0]<2&&t[1]<9||1===t[0]&&9===t[1]&&t[2]<1||4<=t[0])throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}(),t.Util=_,t.Alert=p,t.Button=P,t.Carousel=lt,t.Collapse=bt,t.Dropdown=Jt,t.Modal=ve,t.Popover=sn,t.Scrollspy=Dn,t.Tab=Kn,t.Toast=ni,t.Tooltip=Be,Object.defineProperty(t,"__esModule",{value:!0})});
//# sourceMappingURL=bootstrap.min.js.map  $(function() {
   var $window     = $(window)
     , $top_link   = $('#toplink')
     , $body       = $('body, html')
     , offset      = $('#code').offset().top
     , hidePopover = function ($target) {
        $target.data('popover-hover', false);

        setTimeout(function () {
         if (!$target.data('popover-hover')) {
          $target.popover('hide');
         }
        }, 300);
     };

   $top_link.hide().click(function(event) {
    event.preventDefault();
    $body.animate({scrollTop:0}, 800);
   });

   $window.scroll(function() {
    if($window.scrollTop() > offset) {
     $top_link.fadeIn();
    } else {
     $top_link.fadeOut();
    }
   }).scroll();

   $('.popin')
    .popover({trigger: 'manual'})
    .on({
     'mouseenter.popover': function () {
      var $target = $(this);
      var $container = $target.children().first();

      $target.data('popover-hover', true);

      // popover already displayed
      if ($target.next('.popover').length) {
       return;
      }

      // show the popover
      $container.popover('show');

      // register mouse events on the popover
      $target.next('.popover:not(.popover-initialized)')
       .on({
        'mouseenter': function () {
         $target.data('popover-hover', true);
        },
        'mouseleave': function () {
         hidePopover($container);
        }
       })
       .addClass('popover-initialized');
     },
     'mouseleave.popover': function () {
      hidePopover($(this).children().first());
     }
    });
  });
/*
 Copyright (C) Federico Zivolo 2019
 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
 */(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?module.exports=t():'function'==typeof define&&define.amd?define(t):e.Popper=t()})(this,function(){'use strict';function e(e){return e&&'[object Function]'==={}.toString.call(e)}function t(e,t){if(1!==e.nodeType)return[];var o=e.ownerDocument.defaultView,n=o.getComputedStyle(e,null);return t?n[t]:n}function o(e){return'HTML'===e.nodeName?e:e.parentNode||e.host}function n(e){if(!e)return document.body;switch(e.nodeName){case'HTML':case'BODY':return e.ownerDocument.body;case'#document':return e.body;}var i=t(e),r=i.overflow,p=i.overflowX,s=i.overflowY;return /(auto|scroll|overlay)/.test(r+s+p)?e:n(o(e))}function r(e){return 11===e?pe:10===e?se:pe||se}function p(e){if(!e)return document.documentElement;for(var o=r(10)?document.body:null,n=e.offsetParent||null;n===o&&e.nextElementSibling;)n=(e=e.nextElementSibling).offsetParent;var i=n&&n.nodeName;return i&&'BODY'!==i&&'HTML'!==i?-1!==['TH','TD','TABLE'].indexOf(n.nodeName)&&'static'===t(n,'position')?p(n):n:e?e.ownerDocument.documentElement:document.documentElement}function s(e){var t=e.nodeName;return'BODY'!==t&&('HTML'===t||p(e.firstElementChild)===e)}function d(e){return null===e.parentNode?e:d(e.parentNode)}function a(e,t){if(!e||!e.nodeType||!t||!t.nodeType)return document.documentElement;var o=e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING,n=o?e:t,i=o?t:e,r=document.createRange();r.setStart(n,0),r.setEnd(i,0);var l=r.commonAncestorContainer;if(e!==l&&t!==l||n.contains(i))return s(l)?l:p(l);var f=d(e);return f.host?a(f.host,t):a(e,d(t).host)}function l(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:'top',o='top'===t?'scrollTop':'scrollLeft',n=e.nodeName;if('BODY'===n||'HTML'===n){var i=e.ownerDocument.documentElement,r=e.ownerDocument.scrollingElement||i;return r[o]}return e[o]}function f(e,t){var o=2<arguments.length&&void 0!==arguments[2]&&arguments[2],n=l(t,'top'),i=l(t,'left'),r=o?-1:1;return e.top+=n*r,e.bottom+=n*r,e.left+=i*r,e.right+=i*r,e}function m(e,t){var o='x'===t?'Left':'Top',n='Left'==o?'Right':'Bottom';return parseFloat(e['border'+o+'Width'],10)+parseFloat(e['border'+n+'Width'],10)}function h(e,t,o,n){return ee(t['offset'+e],t['scroll'+e],o['client'+e],o['offset'+e],o['scroll'+e],r(10)?parseInt(o['offset'+e])+parseInt(n['margin'+('Height'===e?'Top':'Left')])+parseInt(n['margin'+('Height'===e?'Bottom':'Right')]):0)}function c(e){var t=e.body,o=e.documentElement,n=r(10)&&getComputedStyle(o);return{height:h('Height',t,o,n),width:h('Width',t,o,n)}}function g(e){return fe({},e,{right:e.left+e.width,bottom:e.top+e.height})}function u(e){var o={};try{if(r(10)){o=e.getBoundingClientRect();var n=l(e,'top'),i=l(e,'left');o.top+=n,o.left+=i,o.bottom+=n,o.right+=i}else o=e.getBoundingClientRect()}catch(t){}var p={left:o.left,top:o.top,width:o.right-o.left,height:o.bottom-o.top},s='HTML'===e.nodeName?c(e.ownerDocument):{},d=s.width||e.clientWidth||p.right-p.left,a=s.height||e.clientHeight||p.bottom-p.top,f=e.offsetWidth-d,h=e.offsetHeight-a;if(f||h){var u=t(e);f-=m(u,'x'),h-=m(u,'y'),p.width-=f,p.height-=h}return g(p)}function b(e,o){var i=2<arguments.length&&void 0!==arguments[2]&&arguments[2],p=r(10),s='HTML'===o.nodeName,d=u(e),a=u(o),l=n(e),m=t(o),h=parseFloat(m.borderTopWidth,10),c=parseFloat(m.borderLeftWidth,10);i&&s&&(a.top=ee(a.top,0),a.left=ee(a.left,0));var b=g({top:d.top-a.top-h,left:d.left-a.left-c,width:d.width,height:d.height});if(b.marginTop=0,b.marginLeft=0,!p&&s){var w=parseFloat(m.marginTop,10),y=parseFloat(m.marginLeft,10);b.top-=h-w,b.bottom-=h-w,b.left-=c-y,b.right-=c-y,b.marginTop=w,b.marginLeft=y}return(p&&!i?o.contains(l):o===l&&'BODY'!==l.nodeName)&&(b=f(b,o)),b}function w(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1],o=e.ownerDocument.documentElement,n=b(e,o),i=ee(o.clientWidth,window.innerWidth||0),r=ee(o.clientHeight,window.innerHeight||0),p=t?0:l(o),s=t?0:l(o,'left'),d={top:p-n.top+n.marginTop,left:s-n.left+n.marginLeft,width:i,height:r};return g(d)}function y(e){var n=e.nodeName;if('BODY'===n||'HTML'===n)return!1;if('fixed'===t(e,'position'))return!0;var i=o(e);return!!i&&y(i)}function E(e){if(!e||!e.parentElement||r())return document.documentElement;for(var o=e.parentElement;o&&'none'===t(o,'transform');)o=o.parentElement;return o||document.documentElement}function v(e,t,i,r){var p=4<arguments.length&&void 0!==arguments[4]&&arguments[4],s={top:0,left:0},d=p?E(e):a(e,t);if('viewport'===r)s=w(d,p);else{var l;'scrollParent'===r?(l=n(o(t)),'BODY'===l.nodeName&&(l=e.ownerDocument.documentElement)):'window'===r?l=e.ownerDocument.documentElement:l=r;var f=b(l,d,p);if('HTML'===l.nodeName&&!y(d)){var m=c(e.ownerDocument),h=m.height,g=m.width;s.top+=f.top-f.marginTop,s.bottom=h+f.top,s.left+=f.left-f.marginLeft,s.right=g+f.left}else s=f}i=i||0;var u='number'==typeof i;return s.left+=u?i:i.left||0,s.top+=u?i:i.top||0,s.right-=u?i:i.right||0,s.bottom-=u?i:i.bottom||0,s}function x(e){var t=e.width,o=e.height;return t*o}function O(e,t,o,n,i){var r=5<arguments.length&&void 0!==arguments[5]?arguments[5]:0;if(-1===e.indexOf('auto'))return e;var p=v(o,n,r,i),s={top:{width:p.width,height:t.top-p.top},right:{width:p.right-t.right,height:p.height},bottom:{width:p.width,height:p.bottom-t.bottom},left:{width:t.left-p.left,height:p.height}},d=Object.keys(s).map(function(e){return fe({key:e},s[e],{area:x(s[e])})}).sort(function(e,t){return t.area-e.area}),a=d.filter(function(e){var t=e.width,n=e.height;return t>=o.clientWidth&&n>=o.clientHeight}),l=0<a.length?a[0].key:d[0].key,f=e.split('-')[1];return l+(f?'-'+f:'')}function L(e,t,o){var n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null,i=n?E(t):a(t,o);return b(o,i,n)}function S(e){var t=e.ownerDocument.defaultView,o=t.getComputedStyle(e),n=parseFloat(o.marginTop||0)+parseFloat(o.marginBottom||0),i=parseFloat(o.marginLeft||0)+parseFloat(o.marginRight||0),r={width:e.offsetWidth+i,height:e.offsetHeight+n};return r}function T(e){var t={left:'right',right:'left',bottom:'top',top:'bottom'};return e.replace(/left|right|bottom|top/g,function(e){return t[e]})}function C(e,t,o){o=o.split('-')[0];var n=S(e),i={width:n.width,height:n.height},r=-1!==['right','left'].indexOf(o),p=r?'top':'left',s=r?'left':'top',d=r?'height':'width',a=r?'width':'height';return i[p]=t[p]+t[d]/2-n[d]/2,i[s]=o===s?t[s]-n[a]:t[T(s)],i}function D(e,t){return Array.prototype.find?e.find(t):e.filter(t)[0]}function N(e,t,o){if(Array.prototype.findIndex)return e.findIndex(function(e){return e[t]===o});var n=D(e,function(e){return e[t]===o});return e.indexOf(n)}function P(t,o,n){var i=void 0===n?t:t.slice(0,N(t,'name',n));return i.forEach(function(t){t['function']&&console.warn('`modifier.function` is deprecated, use `modifier.fn`!');var n=t['function']||t.fn;t.enabled&&e(n)&&(o.offsets.popper=g(o.offsets.popper),o.offsets.reference=g(o.offsets.reference),o=n(o,t))}),o}function k(){if(!this.state.isDestroyed){var e={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}};e.offsets.reference=L(this.state,this.popper,this.reference,this.options.positionFixed),e.placement=O(this.options.placement,e.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),e.originalPlacement=e.placement,e.positionFixed=this.options.positionFixed,e.offsets.popper=C(this.popper,e.offsets.reference,e.placement),e.offsets.popper.position=this.options.positionFixed?'fixed':'absolute',e=P(this.modifiers,e),this.state.isCreated?this.options.onUpdate(e):(this.state.isCreated=!0,this.options.onCreate(e))}}function W(e,t){return e.some(function(e){var o=e.name,n=e.enabled;return n&&o===t})}function B(e){for(var t=[!1,'ms','Webkit','Moz','O'],o=e.charAt(0).toUpperCase()+e.slice(1),n=0;n<t.length;n++){var i=t[n],r=i?''+i+o:e;if('undefined'!=typeof document.body.style[r])return r}return null}function H(){return this.state.isDestroyed=!0,W(this.modifiers,'applyStyle')&&(this.popper.removeAttribute('x-placement'),this.popper.style.position='',this.popper.style.top='',this.popper.style.left='',this.popper.style.right='',this.popper.style.bottom='',this.popper.style.willChange='',this.popper.style[B('transform')]=''),this.disableEventListeners(),this.options.removeOnDestroy&&this.popper.parentNode.removeChild(this.popper),this}function A(e){var t=e.ownerDocument;return t?t.defaultView:window}function M(e,t,o,i){var r='BODY'===e.nodeName,p=r?e.ownerDocument.defaultView:e;p.addEventListener(t,o,{passive:!0}),r||M(n(p.parentNode),t,o,i),i.push(p)}function F(e,t,o,i){o.updateBound=i,A(e).addEventListener('resize',o.updateBound,{passive:!0});var r=n(e);return M(r,'scroll',o.updateBound,o.scrollParents),o.scrollElement=r,o.eventsEnabled=!0,o}function I(){this.state.eventsEnabled||(this.state=F(this.reference,this.options,this.state,this.scheduleUpdate))}function R(e,t){return A(e).removeEventListener('resize',t.updateBound),t.scrollParents.forEach(function(e){e.removeEventListener('scroll',t.updateBound)}),t.updateBound=null,t.scrollParents=[],t.scrollElement=null,t.eventsEnabled=!1,t}function U(){this.state.eventsEnabled&&(cancelAnimationFrame(this.scheduleUpdate),this.state=R(this.reference,this.state))}function Y(e){return''!==e&&!isNaN(parseFloat(e))&&isFinite(e)}function V(e,t){Object.keys(t).forEach(function(o){var n='';-1!==['width','height','top','right','bottom','left'].indexOf(o)&&Y(t[o])&&(n='px'),e.style[o]=t[o]+n})}function j(e,t){Object.keys(t).forEach(function(o){var n=t[o];!1===n?e.removeAttribute(o):e.setAttribute(o,t[o])})}function q(e,t){var o=e.offsets,n=o.popper,i=o.reference,r=$,p=function(e){return e},s=r(i.width),d=r(n.width),a=-1!==['left','right'].indexOf(e.placement),l=-1!==e.placement.indexOf('-'),f=t?a||l||s%2==d%2?r:Z:p,m=t?r:p;return{left:f(1==s%2&&1==d%2&&!l&&t?n.left-1:n.left),top:m(n.top),bottom:m(n.bottom),right:f(n.right)}}function K(e,t,o){var n=D(e,function(e){var o=e.name;return o===t}),i=!!n&&e.some(function(e){return e.name===o&&e.enabled&&e.order<n.order});if(!i){var r='`'+t+'`';console.warn('`'+o+'`'+' modifier is required by '+r+' modifier in order to work, be sure to include it before '+r+'!')}return i}function z(e){return'end'===e?'start':'start'===e?'end':e}function G(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1],o=ce.indexOf(e),n=ce.slice(o+1).concat(ce.slice(0,o));return t?n.reverse():n}function _(e,t,o,n){var i=e.match(/((?:\-|\+)?\d*\.?\d*)(.*)/),r=+i[1],p=i[2];if(!r)return e;if(0===p.indexOf('%')){var s;switch(p){case'%p':s=o;break;case'%':case'%r':default:s=n;}var d=g(s);return d[t]/100*r}if('vh'===p||'vw'===p){var a;return a='vh'===p?ee(document.documentElement.clientHeight,window.innerHeight||0):ee(document.documentElement.clientWidth,window.innerWidth||0),a/100*r}return r}function X(e,t,o,n){var i=[0,0],r=-1!==['right','left'].indexOf(n),p=e.split(/(\+|\-)/).map(function(e){return e.trim()}),s=p.indexOf(D(p,function(e){return-1!==e.search(/,|\s/)}));p[s]&&-1===p[s].indexOf(',')&&console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');var d=/\s*,\s*|\s+/,a=-1===s?[p]:[p.slice(0,s).concat([p[s].split(d)[0]]),[p[s].split(d)[1]].concat(p.slice(s+1))];return a=a.map(function(e,n){var i=(1===n?!r:r)?'height':'width',p=!1;return e.reduce(function(e,t){return''===e[e.length-1]&&-1!==['+','-'].indexOf(t)?(e[e.length-1]=t,p=!0,e):p?(e[e.length-1]+=t,p=!1,e):e.concat(t)},[]).map(function(e){return _(e,i,t,o)})}),a.forEach(function(e,t){e.forEach(function(o,n){Y(o)&&(i[t]+=o*('-'===e[n-1]?-1:1))})}),i}function J(e,t){var o,n=t.offset,i=e.placement,r=e.offsets,p=r.popper,s=r.reference,d=i.split('-')[0];return o=Y(+n)?[+n,0]:X(n,p,s,d),'left'===d?(p.top+=o[0],p.left-=o[1]):'right'===d?(p.top+=o[0],p.left+=o[1]):'top'===d?(p.left+=o[0],p.top-=o[1]):'bottom'===d&&(p.left+=o[0],p.top+=o[1]),e.popper=p,e}for(var Q=Math.min,Z=Math.floor,$=Math.round,ee=Math.max,te='undefined'!=typeof window&&'undefined'!=typeof document,oe=['Edge','Trident','Firefox'],ne=0,ie=0;ie<oe.length;ie+=1)if(te&&0<=navigator.userAgent.indexOf(oe[ie])){ne=1;break}var i=te&&window.Promise,re=i?function(e){var t=!1;return function(){t||(t=!0,window.Promise.resolve().then(function(){t=!1,e()}))}}:function(e){var t=!1;return function(){t||(t=!0,setTimeout(function(){t=!1,e()},ne))}},pe=te&&!!(window.MSInputMethodContext&&document.documentMode),se=te&&/MSIE 10/.test(navigator.userAgent),de=function(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')},ae=function(){function e(e,t){for(var o,n=0;n<t.length;n++)o=t[n],o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),le=function(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e},fe=Object.assign||function(e){for(var t,o=1;o<arguments.length;o++)for(var n in t=arguments[o],t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},me=te&&/Firefox/i.test(navigator.userAgent),he=['auto-start','auto','auto-end','top-start','top','top-end','right-start','right','right-end','bottom-end','bottom','bottom-start','left-end','left','left-start'],ce=he.slice(3),ge={FLIP:'flip',CLOCKWISE:'clockwise',COUNTERCLOCKWISE:'counterclockwise'},ue=function(){function t(o,n){var i=this,r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};de(this,t),this.scheduleUpdate=function(){return requestAnimationFrame(i.update)},this.update=re(this.update.bind(this)),this.options=fe({},t.Defaults,r),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=o&&o.jquery?o[0]:o,this.popper=n&&n.jquery?n[0]:n,this.options.modifiers={},Object.keys(fe({},t.Defaults.modifiers,r.modifiers)).forEach(function(e){i.options.modifiers[e]=fe({},t.Defaults.modifiers[e]||{},r.modifiers?r.modifiers[e]:{})}),this.modifiers=Object.keys(this.options.modifiers).map(function(e){return fe({name:e},i.options.modifiers[e])}).sort(function(e,t){return e.order-t.order}),this.modifiers.forEach(function(t){t.enabled&&e(t.onLoad)&&t.onLoad(i.reference,i.popper,i.options,t,i.state)}),this.update();var p=this.options.eventsEnabled;p&&this.enableEventListeners(),this.state.eventsEnabled=p}return ae(t,[{key:'update',value:function(){return k.call(this)}},{key:'destroy',value:function(){return H.call(this)}},{key:'enableEventListeners',value:function(){return I.call(this)}},{key:'disableEventListeners',value:function(){return U.call(this)}}]),t}();return ue.Utils=('undefined'==typeof window?global:window).PopperUtils,ue.placements=he,ue.Defaults={placement:'bottom',positionFixed:!1,eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:{shift:{order:100,enabled:!0,fn:function(e){var t=e.placement,o=t.split('-')[0],n=t.split('-')[1];if(n){var i=e.offsets,r=i.reference,p=i.popper,s=-1!==['bottom','top'].indexOf(o),d=s?'left':'top',a=s?'width':'height',l={start:le({},d,r[d]),end:le({},d,r[d]+r[a]-p[a])};e.offsets.popper=fe({},p,l[n])}return e}},offset:{order:200,enabled:!0,fn:J,offset:0},preventOverflow:{order:300,enabled:!0,fn:function(e,t){var o=t.boundariesElement||p(e.instance.popper);e.instance.reference===o&&(o=p(o));var n=B('transform'),i=e.instance.popper.style,r=i.top,s=i.left,d=i[n];i.top='',i.left='',i[n]='';var a=v(e.instance.popper,e.instance.reference,t.padding,o,e.positionFixed);i.top=r,i.left=s,i[n]=d,t.boundaries=a;var l=t.priority,f=e.offsets.popper,m={primary:function(e){var o=f[e];return f[e]<a[e]&&!t.escapeWithReference&&(o=ee(f[e],a[e])),le({},e,o)},secondary:function(e){var o='right'===e?'left':'top',n=f[o];return f[e]>a[e]&&!t.escapeWithReference&&(n=Q(f[o],a[e]-('right'===e?f.width:f.height))),le({},o,n)}};return l.forEach(function(e){var t=-1===['left','top'].indexOf(e)?'secondary':'primary';f=fe({},f,m[t](e))}),e.offsets.popper=f,e},priority:['left','right','top','bottom'],padding:5,boundariesElement:'scrollParent'},keepTogether:{order:400,enabled:!0,fn:function(e){var t=e.offsets,o=t.popper,n=t.reference,i=e.placement.split('-')[0],r=Z,p=-1!==['top','bottom'].indexOf(i),s=p?'right':'bottom',d=p?'left':'top',a=p?'width':'height';return o[s]<r(n[d])&&(e.offsets.popper[d]=r(n[d])-o[a]),o[d]>r(n[s])&&(e.offsets.popper[d]=r(n[s])),e}},arrow:{order:500,enabled:!0,fn:function(e,o){var n;if(!K(e.instance.modifiers,'arrow','keepTogether'))return e;var i=o.element;if('string'==typeof i){if(i=e.instance.popper.querySelector(i),!i)return e;}else if(!e.instance.popper.contains(i))return console.warn('WARNING: `arrow.element` must be child of its popper element!'),e;var r=e.placement.split('-')[0],p=e.offsets,s=p.popper,d=p.reference,a=-1!==['left','right'].indexOf(r),l=a?'height':'width',f=a?'Top':'Left',m=f.toLowerCase(),h=a?'left':'top',c=a?'bottom':'right',u=S(i)[l];d[c]-u<s[m]&&(e.offsets.popper[m]-=s[m]-(d[c]-u)),d[m]+u>s[c]&&(e.offsets.popper[m]+=d[m]+u-s[c]),e.offsets.popper=g(e.offsets.popper);var b=d[m]+d[l]/2-u/2,w=t(e.instance.popper),y=parseFloat(w['margin'+f],10),E=parseFloat(w['border'+f+'Width'],10),v=b-e.offsets.popper[m]-y-E;return v=ee(Q(s[l]-u,v),0),e.arrowElement=i,e.offsets.arrow=(n={},le(n,m,$(v)),le(n,h,''),n),e},element:'[x-arrow]'},flip:{order:600,enabled:!0,fn:function(e,t){if(W(e.instance.modifiers,'inner'))return e;if(e.flipped&&e.placement===e.originalPlacement)return e;var o=v(e.instance.popper,e.instance.reference,t.padding,t.boundariesElement,e.positionFixed),n=e.placement.split('-')[0],i=T(n),r=e.placement.split('-')[1]||'',p=[];switch(t.behavior){case ge.FLIP:p=[n,i];break;case ge.CLOCKWISE:p=G(n);break;case ge.COUNTERCLOCKWISE:p=G(n,!0);break;default:p=t.behavior;}return p.forEach(function(s,d){if(n!==s||p.length===d+1)return e;n=e.placement.split('-')[0],i=T(n);var a=e.offsets.popper,l=e.offsets.reference,f=Z,m='left'===n&&f(a.right)>f(l.left)||'right'===n&&f(a.left)<f(l.right)||'top'===n&&f(a.bottom)>f(l.top)||'bottom'===n&&f(a.top)<f(l.bottom),h=f(a.left)<f(o.left),c=f(a.right)>f(o.right),g=f(a.top)<f(o.top),u=f(a.bottom)>f(o.bottom),b='left'===n&&h||'right'===n&&c||'top'===n&&g||'bottom'===n&&u,w=-1!==['top','bottom'].indexOf(n),y=!!t.flipVariations&&(w&&'start'===r&&h||w&&'end'===r&&c||!w&&'start'===r&&g||!w&&'end'===r&&u),E=!!t.flipVariationsByContent&&(w&&'start'===r&&c||w&&'end'===r&&h||!w&&'start'===r&&u||!w&&'end'===r&&g),v=y||E;(m||b||v)&&(e.flipped=!0,(m||b)&&(n=p[d+1]),v&&(r=z(r)),e.placement=n+(r?'-'+r:''),e.offsets.popper=fe({},e.offsets.popper,C(e.instance.popper,e.offsets.reference,e.placement)),e=P(e.instance.modifiers,e,'flip'))}),e},behavior:'flip',padding:5,boundariesElement:'viewport',flipVariations:!1,flipVariationsByContent:!1},inner:{order:700,enabled:!1,fn:function(e){var t=e.placement,o=t.split('-')[0],n=e.offsets,i=n.popper,r=n.reference,p=-1!==['left','right'].indexOf(o),s=-1===['top','left'].indexOf(o);return i[p?'left':'top']=r[o]-(s?i[p?'width':'height']:0),e.placement=T(t),e.offsets.popper=g(i),e}},hide:{order:800,enabled:!0,fn:function(e){if(!K(e.instance.modifiers,'hide','preventOverflow'))return e;var t=e.offsets.reference,o=D(e.instance.modifiers,function(e){return'preventOverflow'===e.name}).boundaries;if(t.bottom<o.top||t.left>o.right||t.top>o.bottom||t.right<o.left){if(!0===e.hide)return e;e.hide=!0,e.attributes['x-out-of-boundaries']=''}else{if(!1===e.hide)return e;e.hide=!1,e.attributes['x-out-of-boundaries']=!1}return e}},computeStyle:{order:850,enabled:!0,fn:function(e,t){var o=t.x,n=t.y,i=e.offsets.popper,r=D(e.instance.modifiers,function(e){return'applyStyle'===e.name}).gpuAcceleration;void 0!==r&&console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');var s,d,a=void 0===r?t.gpuAcceleration:r,l=p(e.instance.popper),f=u(l),m={position:i.position},h=q(e,2>window.devicePixelRatio||!me),c='bottom'===o?'top':'bottom',g='right'===n?'left':'right',b=B('transform');if(d='bottom'==c?'HTML'===l.nodeName?-l.clientHeight+h.bottom:-f.height+h.bottom:h.top,s='right'==g?'HTML'===l.nodeName?-l.clientWidth+h.right:-f.width+h.right:h.left,a&&b)m[b]='translate3d('+s+'px, '+d+'px, 0)',m[c]=0,m[g]=0,m.willChange='transform';else{var w='bottom'==c?-1:1,y='right'==g?-1:1;m[c]=d*w,m[g]=s*y,m.willChange=c+', '+g}var E={"x-placement":e.placement};return e.attributes=fe({},E,e.attributes),e.styles=fe({},m,e.styles),e.arrowStyles=fe({},e.offsets.arrow,e.arrowStyles),e},gpuAcceleration:!0,x:'bottom',y:'right'},applyStyle:{order:900,enabled:!0,fn:function(e){return V(e.instance.popper,e.styles),j(e.instance.popper,e.attributes),e.arrowElement&&Object.keys(e.arrowStyles).length&&V(e.arrowElement,e.arrowStyles),e},onLoad:function(e,t,o,n,i){var r=L(i,t,e,o.positionFixed),p=O(o.placement,r,t,e,o.modifiers.flip.boundariesElement,o.modifiers.flip.padding);return t.setAttribute('x-placement',p),V(t,{position:o.positionFixed?'fixed':'absolute'}),o},gpuAcceleration:void 0}}},ue});
//# sourceMappingURL=popper.min.js.map
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="16" viewBox="0 0 14 16"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"/></svg><svg xmlns="http://www.w3.org/2000/svg" width="12" height="16" viewBox="0 0 12 16"><path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM5 6.98L3.5 8.5 5 10l-.5 1L2 8.5 4.5 6l.5.98zM7.5 6L10 8.5 7.5 11l-.5-.98L8.5 8.5 7 7l.5-1z"/></svg>      <tr>
       <td class="{{lines_level}}">{{icon}}{{name}}</td>
       <td class="{{lines_level}} big">{{lines_bar}}</td>
       <td class="{{lines_level}} small"><div align="right">{{lines_executed_percent}}</div></td>
       <td class="{{lines_level}} small"><div align="right">{{lines_number}}</div></td>
       <td class="{{methods_level}} big">{{methods_bar}}</td>
       <td class="{{methods_level}} small"><div align="right">{{methods_tested_percent}}</div></td>
       <td class="{{methods_level}} small"><div align="right">{{methods_number}}</div></td>
       <td class="{{classes_level}} big">{{classes_bar}}</td>
       <td class="{{classes_level}} small"><div align="right">{{classes_tested_percent}}</div></td>
       <td class="{{classes_level}} small"><div align="right">{{classes_number}}</div></td>
      </tr>

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Code Coverage for {{full_path}}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{{path_to_root}}_css/bootstrap.min.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/octicons.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/style.css" rel="stylesheet" type="text/css">
  <link href="{{path_to_root}}_css/custom.css" rel="stylesheet" type="text/css">
 </head>
 <body>
  <header>
   <div class="container-fluid">
    <div class="row">
     <div class="col-md-12">
      <nav aria-label="breadcrumb">
       <ol class="breadcrumb">
{{breadcrumbs}}
       </ol>
      </nav>
     </div>
    </div>
   </div>
  </header>
  <div class="container-fluid">
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
      <tr>
       <td>&nbsp;</td>
       <td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
      </tr>
      <tr>
       <td>&nbsp;</td>
       <td colspan="3"><div align="center"><strong>Lines</strong></div></td>
       <td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
       <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
      </tr>
     </thead>
     <tbody>
{{items}}
     </tbody>
    </table>
   </div>
   <footer>
    <hr/>
    <h4>Legend</h4>
    <p>
     <span class="danger"><strong>Low</strong>: 0% to {{low_upper_bound}}%</span>
     <span class="warning"><strong>Medium</strong>: {{low_upper_bound}}% to {{high_lower_bound}}%</span>
     <span class="success"><strong>High</strong>: {{high_lower_bound}}% to 100%</span>
    </p>
    <p>
     <small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage {{version}}</a> using {{runtime}}{{generator}} at {{date}}.</small>
    </p>
   </footer>
  </div>
 </body>
</html>
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\Node\AbstractNode as Node;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;

/**
 * Renders a directory node.
 */
final class Directory extends Renderer
{
    /**
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function render(DirectoryNode $node, string $file): void
    {
        $template = new \Text_Template($this->templatePath . 'directory.html', '{{', '}}');

        $this->setCommonTemplateVariables($template, $node);

        $items = $this->renderItem($node, true);

        foreach ($node->getDirectories() as $item) {
            $items .= $this->renderItem($item);
        }

        foreach ($node->getFiles() as $item) {
            $items .= $this->renderItem($item);
        }

        $template->setVar(
            [
                'id'    => $node->getId(),
                'items' => $items,
            ]
        );

        $template->renderTo($file);
    }

    protected function renderItem(Node $node, bool $total = false): string
    {
        $data = [
            'numClasses'                   => $node->getNumClassesAndTraits(),
            'numTestedClasses'             => $node->getNumTestedClassesAndTraits(),
            'numMethods'                   => $node->getNumFunctionsAndMethods(),
            'numTestedMethods'             => $node->getNumTestedFunctionsAndMethods(),
            'linesExecutedPercent'         => $node->getLineExecutedPercent(false),
            'linesExecutedPercentAsString' => $node->getLineExecutedPercent(),
            'numExecutedLines'             => $node->getNumExecutedLines(),
            'numExecutableLines'           => $node->getNumExecutableLines(),
            'testedMethodsPercent'         => $node->getTestedFunctionsAndMethodsPercent(false),
            'testedMethodsPercentAsString' => $node->getTestedFunctionsAndMethodsPercent(),
            'testedClassesPercent'         => $node->getTestedClassesAndTraitsPercent(false),
            'testedClassesPercentAsString' => $node->getTestedClassesAndTraitsPercent(),
        ];

        if ($total) {
            $data['name'] = 'Total';
        } else {
            if ($node instanceof DirectoryNode) {
                $data['name'] = \sprintf(
                    '<a href="%s/index.html">%s</a>',
                    $node->getName(),
                    $node->getName()
                );

                $up = \str_repeat('../', \count($node->getPathAsArray()) - 2);

                $data['icon'] = \sprintf('<img src="%s_icons/file-directory.svg" class="octicon" />', $up);
            } else {
                $data['name'] = \sprintf(
                    '<a href="%s.html">%s</a>',
                    $node->getName(),
                    $node->getName()
                );

                $up = \str_repeat('../', \count($node->getPathAsArray()) - 2);

                $data['icon'] = \sprintf('<img src="%s_icons/file-code.svg" class="octicon" />', $up);
            }
        }

        return $this->renderItemTemplate(
            new \Text_Template($this->templatePath . 'directory_item.html', '{{', '}}'),
            $data
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\Node\AbstractNode;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
use SebastianBergmann\CodeCoverage\Node\File as FileNode;
use SebastianBergmann\CodeCoverage\Version;
use SebastianBergmann\Environment\Runtime;

/**
 * Base class for node renderers.
 */
abstract class Renderer
{
    /**
     * @var string
     */
    protected $templatePath;

    /**
     * @var string
     */
    protected $generator;

    /**
     * @var string
     */
    protected $date;

    /**
     * @var int
     */
    protected $lowUpperBound;

    /**
     * @var int
     */
    protected $highLowerBound;

    /**
     * @var string
     */
    protected $version;

    public function __construct(string $templatePath, string $generator, string $date, int $lowUpperBound, int $highLowerBound)
    {
        $this->templatePath   = $templatePath;
        $this->generator      = $generator;
        $this->date           = $date;
        $this->lowUpperBound  = $lowUpperBound;
        $this->highLowerBound = $highLowerBound;
        $this->version        = Version::id();
    }

    protected function renderItemTemplate(\Text_Template $template, array $data): string
    {
        $numSeparator  = '&nbsp;/&nbsp;';

        if (isset($data['numClasses']) && $data['numClasses'] > 0) {
            $classesLevel = $this->getColorLevel($data['testedClassesPercent']);

            $classesNumber = $data['numTestedClasses'] . $numSeparator .
                $data['numClasses'];

            $classesBar = $this->getCoverageBar(
                $data['testedClassesPercent']
            );
        } else {
            $classesLevel                         = '';
            $classesNumber                        = '0' . $numSeparator . '0';
            $classesBar                           = '';
            $data['testedClassesPercentAsString'] = 'n/a';
        }

        if ($data['numMethods'] > 0) {
            $methodsLevel = $this->getColorLevel($data['testedMethodsPercent']);

            $methodsNumber = $data['numTestedMethods'] . $numSeparator .
                $data['numMethods'];

            $methodsBar = $this->getCoverageBar(
                $data['testedMethodsPercent']
            );
        } else {
            $methodsLevel                         = '';
            $methodsNumber                        = '0' . $numSeparator . '0';
            $methodsBar                           = '';
            $data['testedMethodsPercentAsString'] = 'n/a';
        }

        if ($data['numExecutableLines'] > 0) {
            $linesLevel = $this->getColorLevel($data['linesExecutedPercent']);

            $linesNumber = $data['numExecutedLines'] . $numSeparator .
                $data['numExecutableLines'];

            $linesBar = $this->getCoverageBar(
                $data['linesExecutedPercent']
            );
        } else {
            $linesLevel                           = '';
            $linesNumber                          = '0' . $numSeparator . '0';
            $linesBar                             = '';
            $data['linesExecutedPercentAsString'] = 'n/a';
        }

        $template->setVar(
            [
                'icon'                   => $data['icon'] ?? '',
                'crap'                   => $data['crap'] ?? '',
                'name'                   => $data['name'],
                'lines_bar'              => $linesBar,
                'lines_executed_percent' => $data['linesExecutedPercentAsString'],
                'lines_level'            => $linesLevel,
                'lines_number'           => $linesNumber,
                'methods_bar'            => $methodsBar,
                'methods_tested_percent' => $data['testedMethodsPercentAsString'],
                'methods_level'          => $methodsLevel,
                'methods_number'         => $methodsNumber,
                'classes_bar'            => $classesBar,
                'classes_tested_percent' => $data['testedClassesPercentAsString'] ?? '',
                'classes_level'          => $classesLevel,
                'classes_number'         => $classesNumber,
            ]
        );

        return $template->render();
    }

    protected function setCommonTemplateVariables(\Text_Template $template, AbstractNode $node): void
    {
        $template->setVar(
            [
                'id'               => $node->getId(),
                'full_path'        => $node->getPath(),
                'path_to_root'     => $this->getPathToRoot($node),
                'breadcrumbs'      => $this->getBreadcrumbs($node),
                'date'             => $this->date,
                'version'          => $this->version,
                'runtime'          => $this->getRuntimeString(),
                'generator'        => $this->generator,
                'low_upper_bound'  => $this->lowUpperBound,
                'high_lower_bound' => $this->highLowerBound,
            ]
        );
    }

    protected function getBreadcrumbs(AbstractNode $node): string
    {
        $breadcrumbs = '';
        $path        = $node->getPathAsArray();
        $pathToRoot  = [];
        $max         = \count($path);

        if ($node instanceof FileNode) {
            $max--;
        }

        for ($i = 0; $i < $max; $i++) {
            $pathToRoot[] = \str_repeat('../', $i);
        }

        foreach ($path as $step) {
            if ($step !== $node) {
                $breadcrumbs .= $this->getInactiveBreadcrumb(
                    $step,
                    \array_pop($pathToRoot)
                );
            } else {
                $breadcrumbs .= $this->getActiveBreadcrumb($step);
            }
        }

        return $breadcrumbs;
    }

    protected function getActiveBreadcrumb(AbstractNode $node): string
    {
        $buffer = \sprintf(
            '         <li class="breadcrumb-item active">%s</li>' . "\n",
            $node->getName()
        );

        if ($node instanceof DirectoryNode) {
            $buffer .= '         <li class="breadcrumb-item">(<a href="dashboard.html">Dashboard</a>)</li>' . "\n";
        }

        return $buffer;
    }

    protected function getInactiveBreadcrumb(AbstractNode $node, string $pathToRoot): string
    {
        return \sprintf(
            '         <li class="breadcrumb-item"><a href="%sindex.html">%s</a></li>' . "\n",
            $pathToRoot,
            $node->getName()
        );
    }

    protected function getPathToRoot(AbstractNode $node): string
    {
        $id    = $node->getId();
        $depth = \substr_count($id, '/');

        if ($id !== 'index' &&
            $node instanceof DirectoryNode) {
            $depth++;
        }

        return \str_repeat('../', $depth);
    }

    protected function getCoverageBar(float $percent): string
    {
        $level = $this->getColorLevel($percent);

        $template = new \Text_Template(
            $this->templatePath . 'coverage_bar.html',
            '{{',
            '}}'
        );

        $template->setVar(['level' => $level, 'percent' => \sprintf('%.2F', $percent)]);

        return $template->render();
    }

    protected function getColorLevel(float $percent): string
    {
        if ($percent <= $this->lowUpperBound) {
            return 'danger';
        }

        if ($percent > $this->lowUpperBound &&
            $percent < $this->highLowerBound) {
            return 'warning';
        }

        return 'success';
    }

    private function getRuntimeString(): string
    {
        $runtime = new Runtime;

        $buffer = \sprintf(
            '<a href="%s" target="_top">%s %s</a>',
            $runtime->getVendorUrl(),
            $runtime->getName(),
            $runtime->getVersion()
        );

        if ($runtime->hasXdebug() && !$runtime->hasPHPDBGCodeCoverage()) {
            $buffer .= \sprintf(
                ' with <a href="https://xdebug.org/">Xdebug %s</a>',
                \phpversion('xdebug')
            );
        }

        if ($runtime->hasPCOV() && !$runtime->hasPHPDBGCodeCoverage()) {
            $buffer .= \sprintf(
                ' with <a href="https://github.com/krakjoe/pcov">PCOV %s</a>',
                \phpversion('pcov')
            );
        }

        return $buffer;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Html;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
use SebastianBergmann\CodeCoverage\RuntimeException;

/**
 * Generates an HTML report from a code coverage object.
 */
final class Facade
{
    /**
     * @var string
     */
    private $templatePath;

    /**
     * @var string
     */
    private $generator;

    /**
     * @var int
     */
    private $lowUpperBound;

    /**
     * @var int
     */
    private $highLowerBound;

    public function __construct(int $lowUpperBound = 50, int $highLowerBound = 90, string $generator = '')
    {
        $this->generator      = $generator;
        $this->highLowerBound = $highLowerBound;
        $this->lowUpperBound  = $lowUpperBound;
        $this->templatePath   = __DIR__ . '/Renderer/Template/';
    }

    /**
     * @throws RuntimeException
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function process(CodeCoverage $coverage, string $target): void
    {
        $target = $this->getDirectory($target);
        $report = $coverage->getReport();

        if (!isset($_SERVER['REQUEST_TIME'])) {
            $_SERVER['REQUEST_TIME'] = \time();
        }

        $date = \date('D M j G:i:s T Y', $_SERVER['REQUEST_TIME']);

        $dashboard = new Dashboard(
            $this->templatePath,
            $this->generator,
            $date,
            $this->lowUpperBound,
            $this->highLowerBound
        );

        $directory = new Directory(
            $this->templatePath,
            $this->generator,
            $date,
            $this->lowUpperBound,
            $this->highLowerBound
        );

        $file = new File(
            $this->templatePath,
            $this->generator,
            $date,
            $this->lowUpperBound,
            $this->highLowerBound
        );

        $directory->render($report, $target . 'index.html');
        $dashboard->render($report, $target . 'dashboard.html');

        foreach ($report as $node) {
            $id = $node->getId();

            if ($node instanceof DirectoryNode) {
                if (!$this->createDirectory($target . $id)) {
                    throw new \RuntimeException(\sprintf('Directory "%s" was not created', $target . $id));
                }

                $directory->render($node, $target . $id . '/index.html');
                $dashboard->render($node, $target . $id . '/dashboard.html');
            } else {
                $dir = \dirname($target . $id);

                if (!$this->createDirectory($dir)) {
                    throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dir));
                }

                $file->render($node, $target . $id . '.html');
            }
        }

        $this->copyFiles($target);
    }

    /**
     * @throws RuntimeException
     */
    private function copyFiles(string $target): void
    {
        $dir = $this->getDirectory($target . '_css');

        \copy($this->templatePath . 'css/bootstrap.min.css', $dir . 'bootstrap.min.css');
        \copy($this->templatePath . 'css/nv.d3.min.css', $dir . 'nv.d3.min.css');
        \copy($this->templatePath . 'css/style.css', $dir . 'style.css');
        \copy($this->templatePath . 'css/custom.css', $dir . 'custom.css');
        \copy($this->templatePath . 'css/octicons.css', $dir . 'octicons.css');

        $dir = $this->getDirectory($target . '_icons');
        \copy($this->templatePath . 'icons/file-code.svg', $dir . 'file-code.svg');
        \copy($this->templatePath . 'icons/file-directory.svg', $dir . 'file-directory.svg');

        $dir = $this->getDirectory($target . '_js');
        \copy($this->templatePath . 'js/bootstrap.min.js', $dir . 'bootstrap.min.js');
        \copy($this->templatePath . 'js/popper.min.js', $dir . 'popper.min.js');
        \copy($this->templatePath . 'js/d3.min.js', $dir . 'd3.min.js');
        \copy($this->templatePath . 'js/jquery.min.js', $dir . 'jquery.min.js');
        \copy($this->templatePath . 'js/nv.d3.min.js', $dir . 'nv.d3.min.js');
        \copy($this->templatePath . 'js/file.js', $dir . 'file.js');
    }

    /**
     * @throws RuntimeException
     */
    private function getDirectory(string $directory): string
    {
        if (\substr($directory, -1, 1) != \DIRECTORY_SEPARATOR) {
            $directory .= \DIRECTORY_SEPARATOR;
        }

        if (!$this->createDirectory($directory)) {
            throw new RuntimeException(
                \sprintf(
                    'Directory "%s" does not exist.',
                    $directory
                )
            );
        }

        return $directory;
    }

    private function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use SebastianBergmann\CodeCoverage\Util;

final class Totals
{
    /**
     * @var \DOMNode
     */
    private $container;

    /**
     * @var \DOMElement
     */
    private $linesNode;

    /**
     * @var \DOMElement
     */
    private $methodsNode;

    /**
     * @var \DOMElement
     */
    private $functionsNode;

    /**
     * @var \DOMElement
     */
    private $classesNode;

    /**
     * @var \DOMElement
     */
    private $traitsNode;

    public function __construct(\DOMElement $container)
    {
        $this->container = $container;
        $dom             = $container->ownerDocument;

        $this->linesNode = $dom->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'lines'
        );

        $this->methodsNode = $dom->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'methods'
        );

        $this->functionsNode = $dom->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'functions'
        );

        $this->classesNode = $dom->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'classes'
        );

        $this->traitsNode = $dom->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'traits'
        );

        $container->appendChild($this->linesNode);
        $container->appendChild($this->methodsNode);
        $container->appendChild($this->functionsNode);
        $container->appendChild($this->classesNode);
        $container->appendChild($this->traitsNode);
    }

    public function getContainer(): \DOMNode
    {
        return $this->container;
    }

    public function setNumLines(int $loc, int $cloc, int $ncloc, int $executable, int $executed): void
    {
        $this->linesNode->setAttribute('total', (string) $loc);
        $this->linesNode->setAttribute('comments', (string) $cloc);
        $this->linesNode->setAttribute('code', (string) $ncloc);
        $this->linesNode->setAttribute('executable', (string) $executable);
        $this->linesNode->setAttribute('executed', (string) $executed);
        $this->linesNode->setAttribute(
            'percent',
            $executable === 0 ? '0' : \sprintf('%01.2F', Util::percent($executed, $executable))
        );
    }

    public function setNumClasses(int $count, int $tested): void
    {
        $this->classesNode->setAttribute('count', (string) $count);
        $this->classesNode->setAttribute('tested', (string) $tested);
        $this->classesNode->setAttribute(
            'percent',
            $count === 0 ? '0' : \sprintf('%01.2F', Util::percent($tested, $count))
        );
    }

    public function setNumTraits(int $count, int $tested): void
    {
        $this->traitsNode->setAttribute('count', (string) $count);
        $this->traitsNode->setAttribute('tested', (string) $tested);
        $this->traitsNode->setAttribute(
            'percent',
            $count === 0 ? '0' : \sprintf('%01.2F', Util::percent($tested, $count))
        );
    }

    public function setNumMethods(int $count, int $tested): void
    {
        $this->methodsNode->setAttribute('count', (string) $count);
        $this->methodsNode->setAttribute('tested', (string) $tested);
        $this->methodsNode->setAttribute(
            'percent',
            $count === 0 ? '0' : \sprintf('%01.2F', Util::percent($tested, $count))
        );
    }

    public function setNumFunctions(int $count, int $tested): void
    {
        $this->functionsNode->setAttribute('count', (string) $count);
        $this->functionsNode->setAttribute('tested', (string) $tested);
        $this->functionsNode->setAttribute(
            'percent',
            $count === 0 ? '0' : \sprintf('%01.2F', Util::percent($tested, $count))
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

class File
{
    /**
     * @var \DOMDocument
     */
    private $dom;

    /**
     * @var \DOMElement
     */
    private $contextNode;

    public function __construct(\DOMElement $context)
    {
        $this->dom         = $context->ownerDocument;
        $this->contextNode = $context;
    }

    public function getTotals(): Totals
    {
        $totalsContainer = $this->contextNode->firstChild;

        if (!$totalsContainer) {
            $totalsContainer = $this->contextNode->appendChild(
                $this->dom->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'totals'
                )
            );
        }

        return new Totals($totalsContainer);
    }

    public function getLineCoverage(string $line): Coverage
    {
        $coverage = $this->contextNode->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'coverage'
        )->item(0);

        if (!$coverage) {
            $coverage = $this->contextNode->appendChild(
                $this->dom->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'coverage'
                )
            );
        }

        $lineNode = $coverage->appendChild(
            $this->dom->createElementNS(
                'https://schema.phpunit.de/coverage/1.0',
                'line'
            )
        );

        return new Coverage($lineNode, $line);
    }

    protected function getContextNode(): \DOMElement
    {
        return $this->contextNode;
    }

    protected function getDomDocument(): \DOMDocument
    {
        return $this->dom;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Method
{
    /**
     * @var \DOMElement
     */
    private $contextNode;

    public function __construct(\DOMElement $context, string $name)
    {
        $this->contextNode = $context;

        $this->setName($name);
    }

    public function setSignature(string $signature): void
    {
        $this->contextNode->setAttribute('signature', $signature);
    }

    public function setLines(string $start, ?string $end = null): void
    {
        $this->contextNode->setAttribute('start', $start);

        if ($end !== null) {
            $this->contextNode->setAttribute('end', $end);
        }
    }

    public function setTotals(string $executable, string $executed, string $coverage): void
    {
        $this->contextNode->setAttribute('executable', $executable);
        $this->contextNode->setAttribute('executed', $executed);
        $this->contextNode->setAttribute('coverage', $coverage);
    }

    public function setCrap(string $crap): void
    {
        $this->contextNode->setAttribute('crap', $crap);
    }

    private function setName(string $name): void
    {
        $this->contextNode->setAttribute('name', $name);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Unit
{
    /**
     * @var \DOMElement
     */
    private $contextNode;

    public function __construct(\DOMElement $context, string $name)
    {
        $this->contextNode = $context;

        $this->setName($name);
    }

    public function setLines(int $start, int $executable, int $executed): void
    {
        $this->contextNode->setAttribute('start', (string) $start);
        $this->contextNode->setAttribute('executable', (string) $executable);
        $this->contextNode->setAttribute('executed', (string) $executed);
    }

    public function setCrap(float $crap): void
    {
        $this->contextNode->setAttribute('crap', (string) $crap);
    }

    public function setPackage(string $full, string $package, string $sub, string $category): void
    {
        $node = $this->contextNode->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'package'
        )->item(0);

        if (!$node) {
            $node = $this->contextNode->appendChild(
                $this->contextNode->ownerDocument->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'package'
                )
            );
        }

        $node->setAttribute('full', $full);
        $node->setAttribute('name', $package);
        $node->setAttribute('sub', $sub);
        $node->setAttribute('category', $category);
    }

    public function setNamespace(string $namespace): void
    {
        $node = $this->contextNode->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'namespace'
        )->item(0);

        if (!$node) {
            $node = $this->contextNode->appendChild(
                $this->contextNode->ownerDocument->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'namespace'
                )
            );
        }

        $node->setAttribute('name', $namespace);
    }

    public function addMethod(string $name): Method
    {
        $node = $this->contextNode->appendChild(
            $this->contextNode->ownerDocument->createElementNS(
                'https://schema.phpunit.de/coverage/1.0',
                'method'
            )
        );

        return new Method($node, $name);
    }

    private function setName(string $name): void
    {
        $this->contextNode->setAttribute('name', $name);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Tests
{
    private $contextNode;

    private $codeMap = [
        -1 => 'UNKNOWN',    // PHPUnit_Runner_BaseTestRunner::STATUS_UNKNOWN
        0  => 'PASSED',     // PHPUnit_Runner_BaseTestRunner::STATUS_PASSED
        1  => 'SKIPPED',    // PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED
        2  => 'INCOMPLETE', // PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE
        3  => 'FAILURE',    // PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE
        4  => 'ERROR',      // PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
        5  => 'RISKY',      // PHPUnit_Runner_BaseTestRunner::STATUS_RISKY
        6  => 'WARNING',     // PHPUnit_Runner_BaseTestRunner::STATUS_WARNING
    ];

    public function __construct(\DOMElement $context)
    {
        $this->contextNode = $context;
    }

    public function addTest(string $test, array $result): void
    {
        $node = $this->contextNode->appendChild(
            $this->contextNode->ownerDocument->createElementNS(
                'https://schema.phpunit.de/coverage/1.0',
                'test'
            )
        );

        $node->setAttribute('name', $test);
        $node->setAttribute('size', $result['size']);
        $node->setAttribute('result', (string) $result['status']);
        $node->setAttribute('status', $this->codeMap[(int) $result['status']]);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Project extends Node
{
    public function __construct(string $directory)
    {
        $this->init();
        $this->setProjectSourceDirectory($directory);
    }

    public function getProjectSourceDirectory(): string
    {
        return $this->getContextNode()->getAttribute('source');
    }

    public function getBuildInformation(): BuildInformation
    {
        $buildNode = $this->getDom()->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'build'
        )->item(0);

        if (!$buildNode) {
            $buildNode = $this->getDom()->documentElement->appendChild(
                $this->getDom()->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'build'
                )
            );
        }

        return new BuildInformation($buildNode);
    }

    public function getTests(): Tests
    {
        $testsNode = $this->getContextNode()->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'tests'
        )->item(0);

        if (!$testsNode) {
            $testsNode = $this->getContextNode()->appendChild(
                $this->getDom()->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'tests'
                )
            );
        }

        return new Tests($testsNode);
    }

    public function asDom(): \DOMDocument
    {
        return $this->getDom();
    }

    private function init(): void
    {
        $dom = new \DOMDocument;
        $dom->loadXML('<?xml version="1.0" ?><phpunit xmlns="https://schema.phpunit.de/coverage/1.0"><build/><project/></phpunit>');

        $this->setContextNode(
            $dom->getElementsByTagNameNS(
                'https://schema.phpunit.de/coverage/1.0',
                'project'
            )->item(0)
        );
    }

    private function setProjectSourceDirectory(string $name): void
    {
        $this->getContextNode()->setAttribute('source', $name);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

abstract class Node
{
    /**
     * @var \DOMDocument
     */
    private $dom;

    /**
     * @var \DOMElement
     */
    private $contextNode;

    public function __construct(\DOMElement $context)
    {
        $this->setContextNode($context);
    }

    public function getDom(): \DOMDocument
    {
        return $this->dom;
    }

    public function getTotals(): Totals
    {
        $totalsContainer = $this->getContextNode()->firstChild;

        if (!$totalsContainer) {
            $totalsContainer = $this->getContextNode()->appendChild(
                $this->dom->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'totals'
                )
            );
        }

        return new Totals($totalsContainer);
    }

    public function addDirectory(string $name): Directory
    {
        $dirNode = $this->getDom()->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'directory'
        );

        $dirNode->setAttribute('name', $name);
        $this->getContextNode()->appendChild($dirNode);

        return new Directory($dirNode);
    }

    public function addFile(string $name, string $href): File
    {
        $fileNode = $this->getDom()->createElementNS(
            'https://schema.phpunit.de/coverage/1.0',
            'file'
        );

        $fileNode->setAttribute('name', $name);
        $fileNode->setAttribute('href', $href);
        $this->getContextNode()->appendChild($fileNode);

        return new File($fileNode);
    }

    protected function setContextNode(\DOMElement $context): void
    {
        $this->dom         = $context->ownerDocument;
        $this->contextNode = $context;
    }

    protected function getContextNode(): \DOMElement
    {
        return $this->contextNode;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Directory extends Node
{
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use SebastianBergmann\CodeCoverage\RuntimeException;

final class Coverage
{
    /**
     * @var \XMLWriter
     */
    private $writer;

    /**
     * @var \DOMElement
     */
    private $contextNode;

    /**
     * @var bool
     */
    private $finalized = false;

    public function __construct(\DOMElement $context, string $line)
    {
        $this->contextNode = $context;

        $this->writer = new \XMLWriter();
        $this->writer->openMemory();
        $this->writer->startElementNS(null, $context->nodeName, 'https://schema.phpunit.de/coverage/1.0');
        $this->writer->writeAttribute('nr', $line);
    }

    /**
     * @throws RuntimeException
     */
    public function addTest(string $test): void
    {
        if ($this->finalized) {
            throw new RuntimeException('Coverage Report already finalized');
        }

        $this->writer->startElement('covered');
        $this->writer->writeAttribute('by', $test);
        $this->writer->endElement();
    }

    public function finalize(): void
    {
        $this->writer->endElement();

        $fragment = $this->contextNode->ownerDocument->createDocumentFragment();
        $fragment->appendXML($this->writer->outputMemory());

        $this->contextNode->parentNode->replaceChild(
            $fragment,
            $this->contextNode
        );

        $this->finalized = true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use TheSeer\Tokenizer\NamespaceUri;
use TheSeer\Tokenizer\Tokenizer;
use TheSeer\Tokenizer\XMLSerializer;

final class Source
{
    /** @var \DOMElement */
    private $context;

    public function __construct(\DOMElement $context)
    {
        $this->context = $context;
    }

    public function setSourceCode(string $source): void
    {
        $context = $this->context;

        $tokens = (new Tokenizer())->parse($source);
        $srcDom = (new XMLSerializer(new NamespaceUri($context->namespaceURI)))->toDom($tokens);

        $context->parentNode->replaceChild(
            $context->ownerDocument->importNode($srcDom->documentElement, true),
            $context
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use SebastianBergmann\Environment\Runtime;

final class BuildInformation
{
    /**
     * @var \DOMElement
     */
    private $contextNode;

    public function __construct(\DOMElement $contextNode)
    {
        $this->contextNode = $contextNode;
    }

    public function setRuntimeInformation(Runtime $runtime): void
    {
        $runtimeNode = $this->getNodeByName('runtime');

        $runtimeNode->setAttribute('name', $runtime->getName());
        $runtimeNode->setAttribute('version', $runtime->getVersion());
        $runtimeNode->setAttribute('url', $runtime->getVendorUrl());

        $driverNode = $this->getNodeByName('driver');

        if ($runtime->hasPHPDBGCodeCoverage()) {
            $driverNode->setAttribute('name', 'phpdbg');
            $driverNode->setAttribute('version', \constant('PHPDBG_VERSION'));
        }

        if ($runtime->hasXdebug()) {
            $driverNode->setAttribute('name', 'xdebug');
            $driverNode->setAttribute('version', \phpversion('xdebug'));
        }

        if ($runtime->hasPCOV()) {
            $driverNode->setAttribute('name', 'pcov');
            $driverNode->setAttribute('version', \phpversion('pcov'));
        }
    }

    public function setBuildTime(\DateTime $date): void
    {
        $this->contextNode->setAttribute('time', $date->format('D M j G:i:s T Y'));
    }

    public function setGeneratorVersions(string $phpUnitVersion, string $coverageVersion): void
    {
        $this->contextNode->setAttribute('phpunit', $phpUnitVersion);
        $this->contextNode->setAttribute('coverage', $coverageVersion);
    }

    private function getNodeByName(string $name): \DOMElement
    {
        $node = $this->contextNode->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            $name
        )->item(0);

        if (!$node) {
            $node = $this->contextNode->appendChild(
                $this->contextNode->ownerDocument->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    $name
                )
            );
        }

        return $node;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

final class Report extends File
{
    public function __construct(string $name)
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<?xml version="1.0" ?><phpunit xmlns="https://schema.phpunit.de/coverage/1.0"><file /></phpunit>');

        $contextNode = $dom->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'file'
        )->item(0);

        parent::__construct($contextNode);

        $this->setName($name);
    }

    public function asDom(): \DOMDocument
    {
        return $this->getDomDocument();
    }

    public function getFunctionObject($name): Method
    {
        $node = $this->getContextNode()->appendChild(
            $this->getDomDocument()->createElementNS(
                'https://schema.phpunit.de/coverage/1.0',
                'function'
            )
        );

        return new Method($node, $name);
    }

    public function getClassObject($name): Unit
    {
        return $this->getUnitObject('class', $name);
    }

    public function getTraitObject($name): Unit
    {
        return $this->getUnitObject('trait', $name);
    }

    public function getSource(): Source
    {
        $source = $this->getContextNode()->getElementsByTagNameNS(
            'https://schema.phpunit.de/coverage/1.0',
            'source'
        )->item(0);

        if (!$source) {
            $source = $this->getContextNode()->appendChild(
                $this->getDomDocument()->createElementNS(
                    'https://schema.phpunit.de/coverage/1.0',
                    'source'
                )
            );
        }

        return new Source($source);
    }

    private function setName($name): void
    {
        $this->getContextNode()->setAttribute('name', \basename($name));
        $this->getContextNode()->setAttribute('path', \dirname($name));
    }

    private function getUnitObject($tagName, $name): Unit
    {
        $node = $this->getContextNode()->appendChild(
            $this->getDomDocument()->createElementNS(
                'https://schema.phpunit.de/coverage/1.0',
                $tagName
            )
        );

        return new Unit($node, $name);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report\Xml;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\AbstractNode;
use SebastianBergmann\CodeCoverage\Node\Directory as DirectoryNode;
use SebastianBergmann\CodeCoverage\Node\File as FileNode;
use SebastianBergmann\CodeCoverage\RuntimeException;
use SebastianBergmann\CodeCoverage\Version;
use SebastianBergmann\Environment\Runtime;

final class Facade
{
    /**
     * @var string
     */
    private $target;

    /**
     * @var Project
     */
    private $project;

    /**
     * @var string
     */
    private $phpUnitVersion;

    public function __construct(string $version)
    {
        $this->phpUnitVersion = $version;
    }

    /**
     * @throws RuntimeException
     */
    public function process(CodeCoverage $coverage, string $target): void
    {
        if (\substr($target, -1, 1) !== \DIRECTORY_SEPARATOR) {
            $target .= \DIRECTORY_SEPARATOR;
        }

        $this->target = $target;
        $this->initTargetDirectory($target);

        $report = $coverage->getReport();

        $this->project = new Project(
            $coverage->getReport()->getName()
        );

        $this->setBuildInformation();
        $this->processTests($coverage->getTests());
        $this->processDirectory($report, $this->project);

        $this->saveDocument($this->project->asDom(), 'index');
    }

    private function setBuildInformation(): void
    {
        $buildNode = $this->project->getBuildInformation();
        $buildNode->setRuntimeInformation(new Runtime());
        $buildNode->setBuildTime(\DateTime::createFromFormat('U', (string) $_SERVER['REQUEST_TIME']));
        $buildNode->setGeneratorVersions($this->phpUnitVersion, Version::id());
    }

    /**
     * @throws RuntimeException
     */
    private function initTargetDirectory(string $directory): void
    {
        if (\file_exists($directory)) {
            if (!\is_dir($directory)) {
                throw new RuntimeException(
                    "'$directory' exists but is not a directory."
                );
            }

            if (!\is_writable($directory)) {
                throw new RuntimeException(
                    "'$directory' exists but is not writable."
                );
            }
        } elseif (!$this->createDirectory($directory)) {
            throw new RuntimeException(
                "'$directory' could not be created."
            );
        }
    }

    private function processDirectory(DirectoryNode $directory, Node $context): void
    {
        $directoryName = $directory->getName();

        if ($this->project->getProjectSourceDirectory() === $directoryName) {
            $directoryName = '/';
        }

        $directoryObject = $context->addDirectory($directoryName);

        $this->setTotals($directory, $directoryObject->getTotals());

        foreach ($directory->getDirectories() as $node) {
            $this->processDirectory($node, $directoryObject);
        }

        foreach ($directory->getFiles() as $node) {
            $this->processFile($node, $directoryObject);
        }
    }

    /**
     * @throws RuntimeException
     */
    private function processFile(FileNode $file, Directory $context): void
    {
        $fileObject = $context->addFile(
            $file->getName(),
            $file->getId() . '.xml'
        );

        $this->setTotals($file, $fileObject->getTotals());

        $path = \substr(
            $file->getPath(),
            \strlen($this->project->getProjectSourceDirectory())
        );

        $fileReport = new Report($path);

        $this->setTotals($file, $fileReport->getTotals());

        foreach ($file->getClassesAndTraits() as $unit) {
            $this->processUnit($unit, $fileReport);
        }

        foreach ($file->getFunctions() as $function) {
            $this->processFunction($function, $fileReport);
        }

        foreach ($file->getCoverageData() as $line => $tests) {
            if (!\is_array($tests) || \count($tests) === 0) {
                continue;
            }

            $coverage = $fileReport->getLineCoverage((string) $line);

            foreach ($tests as $test) {
                $coverage->addTest($test);
            }

            $coverage->finalize();
        }

        $fileReport->getSource()->setSourceCode(
            \file_get_contents($file->getPath())
        );

        $this->saveDocument($fileReport->asDom(), $file->getId());
    }

    private function processUnit(array $unit, Report $report): void
    {
        if (isset($unit['className'])) {
            $unitObject = $report->getClassObject($unit['className']);
        } else {
            $unitObject = $report->getTraitObject($unit['traitName']);
        }

        $unitObject->setLines(
            $unit['startLine'],
            $unit['executableLines'],
            $unit['executedLines']
        );

        $unitObject->setCrap((float) $unit['crap']);

        $unitObject->setPackage(
            $unit['package']['fullPackage'],
            $unit['package']['package'],
            $unit['package']['subpackage'],
            $unit['package']['category']
        );

        $unitObject->setNamespace($unit['package']['namespace']);

        foreach ($unit['methods'] as $method) {
            $methodObject = $unitObject->addMethod($method['methodName']);
            $methodObject->setSignature($method['signature']);
            $methodObject->setLines((string) $method['startLine'], (string) $method['endLine']);
            $methodObject->setCrap($method['crap']);
            $methodObject->setTotals(
                (string) $method['executableLines'],
                (string) $method['executedLines'],
                (string) $method['coverage']
            );
        }
    }

    private function processFunction(array $function, Report $report): void
    {
        $functionObject = $report->getFunctionObject($function['functionName']);

        $functionObject->setSignature($function['signature']);
        $functionObject->setLines((string) $function['startLine']);
        $functionObject->setCrap($function['crap']);
        $functionObject->setTotals((string) $function['executableLines'], (string) $function['executedLines'], (string) $function['coverage']);
    }

    private function processTests(array $tests): void
    {
        $testsObject = $this->project->getTests();

        foreach ($tests as $test => $result) {
            if ($test === 'UNCOVERED_FILES_FROM_WHITELIST') {
                continue;
            }

            $testsObject->addTest($test, $result);
        }
    }

    private function setTotals(AbstractNode $node, Totals $totals): void
    {
        $loc = $node->getLinesOfCode();

        $totals->setNumLines(
            $loc['loc'],
            $loc['cloc'],
            $loc['ncloc'],
            $node->getNumExecutableLines(),
            $node->getNumExecutedLines()
        );

        $totals->setNumClasses(
            $node->getNumClasses(),
            $node->getNumTestedClasses()
        );

        $totals->setNumTraits(
            $node->getNumTraits(),
            $node->getNumTestedTraits()
        );

        $totals->setNumMethods(
            $node->getNumMethods(),
            $node->getNumTestedMethods()
        );

        $totals->setNumFunctions(
            $node->getNumFunctions(),
            $node->getNumTestedFunctions()
        );
    }

    private function getTargetDirectory(): string
    {
        return $this->target;
    }

    /**
     * @throws RuntimeException
     */
    private function saveDocument(\DOMDocument $document, string $name): void
    {
        $filename = \sprintf('%s/%s.xml', $this->getTargetDirectory(), $name);

        $document->formatOutput       = true;
        $document->preserveWhiteSpace = false;
        $this->initTargetDirectory(\dirname($filename));

        $document->save($filename);
    }

    private function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\RuntimeException;

/**
 * Uses var_export() to write a SebastianBergmann\CodeCoverage\CodeCoverage object to a file.
 */
final class PHP
{
    /**
     * @throws \SebastianBergmann\CodeCoverage\RuntimeException
     */
    public function process(CodeCoverage $coverage, ?string $target = null): string
    {
        $filter = $coverage->filter();

        $buffer = \sprintf(
            '<?php
$coverage = new SebastianBergmann\CodeCoverage\CodeCoverage;
$coverage->setData(%s);
$coverage->setTests(%s);

$filter = $coverage->filter();
$filter->setWhitelistedFiles(%s);

return $coverage;',
            \var_export($coverage->getData(true), true),
            \var_export($coverage->getTests(), true),
            \var_export($filter->getWhitelistedFiles(), true)
        );

        if ($target !== null) {
            if (!$this->createDirectory(\dirname($target))) {
                throw new \RuntimeException(\sprintf('Directory "%s" was not created', \dirname($target)));
            }

            if (@\file_put_contents($target, $buffer) === false) {
                throw new RuntimeException(
                    \sprintf(
                        'Could not write to "%s',
                        $target
                    )
                );
            }
        }

        return $buffer;
    }

    private function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\Util;

/**
 * Generates human readable output from a code coverage object.
 *
 * The output gets put into a text file our written to the CLI.
 */
final class Text
{
    /**
     * @var string
     */
    private const COLOR_GREEN = "\x1b[30;42m";

    /**
     * @var string
     */
    private const COLOR_YELLOW = "\x1b[30;43m";

    /**
     * @var string
     */
    private const COLOR_RED = "\x1b[37;41m";

    /**
     * @var string
     */
    private const COLOR_HEADER = "\x1b[1;37;40m";

    /**
     * @var string
     */
    private const COLOR_RESET = "\x1b[0m";

    /**
     * @var string
     */
    private const COLOR_EOL = "\x1b[2K";

    /**
     * @var int
     */
    private $lowUpperBound;

    /**
     * @var int
     */
    private $highLowerBound;

    /**
     * @var bool
     */
    private $showUncoveredFiles;

    /**
     * @var bool
     */
    private $showOnlySummary;

    public function __construct(int $lowUpperBound = 50, int $highLowerBound = 90, bool $showUncoveredFiles = false, bool $showOnlySummary = false)
    {
        $this->lowUpperBound      = $lowUpperBound;
        $this->highLowerBound     = $highLowerBound;
        $this->showUncoveredFiles = $showUncoveredFiles;
        $this->showOnlySummary    = $showOnlySummary;
    }

    public function process(CodeCoverage $coverage, bool $showColors = false): string
    {
        $output = \PHP_EOL . \PHP_EOL;
        $report = $coverage->getReport();

        $colors = [
            'header'  => '',
            'classes' => '',
            'methods' => '',
            'lines'   => '',
            'reset'   => '',
            'eol'     => '',
        ];

        if ($showColors) {
            $colors['classes'] = $this->getCoverageColor(
                $report->getNumTestedClassesAndTraits(),
                $report->getNumClassesAndTraits()
            );

            $colors['methods'] = $this->getCoverageColor(
                $report->getNumTestedMethods(),
                $report->getNumMethods()
            );

            $colors['lines']   = $this->getCoverageColor(
                $report->getNumExecutedLines(),
                $report->getNumExecutableLines()
            );

            $colors['reset']  = self::COLOR_RESET;
            $colors['header'] = self::COLOR_HEADER;
            $colors['eol']    = self::COLOR_EOL;
        }

        $classes = \sprintf(
            '  Classes: %6s (%d/%d)',
            Util::percent(
                $report->getNumTestedClassesAndTraits(),
                $report->getNumClassesAndTraits(),
                true
            ),
            $report->getNumTestedClassesAndTraits(),
            $report->getNumClassesAndTraits()
        );

        $methods = \sprintf(
            '  Methods: %6s (%d/%d)',
            Util::percent(
                $report->getNumTestedMethods(),
                $report->getNumMethods(),
                true
            ),
            $report->getNumTestedMethods(),
            $report->getNumMethods()
        );

        $lines = \sprintf(
            '  Lines:   %6s (%d/%d)',
            Util::percent(
                $report->getNumExecutedLines(),
                $report->getNumExecutableLines(),
                true
            ),
            $report->getNumExecutedLines(),
            $report->getNumExecutableLines()
        );

        $padding = \max(\array_map('strlen', [$classes, $methods, $lines]));

        if ($this->showOnlySummary) {
            $title   = 'Code Coverage Report Summary:';
            $padding = \max($padding, \strlen($title));

            $output .= $this->format($colors['header'], $padding, $title);
        } else {
            $date  = \date('  Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
            $title = 'Code Coverage Report:';

            $output .= $this->format($colors['header'], $padding, $title);
            $output .= $this->format($colors['header'], $padding, $date);
            $output .= $this->format($colors['header'], $padding, '');
            $output .= $this->format($colors['header'], $padding, ' Summary:');
        }

        $output .= $this->format($colors['classes'], $padding, $classes);
        $output .= $this->format($colors['methods'], $padding, $methods);
        $output .= $this->format($colors['lines'], $padding, $lines);

        if ($this->showOnlySummary) {
            return $output . \PHP_EOL;
        }

        $classCoverage = [];

        foreach ($report as $item) {
            if (!$item instanceof File) {
                continue;
            }

            $classes = $item->getClassesAndTraits();

            foreach ($classes as $className => $class) {
                $classStatements        = 0;
                $coveredClassStatements = 0;
                $coveredMethods         = 0;
                $classMethods           = 0;

                foreach ($class['methods'] as $method) {
                    if ($method['executableLines'] == 0) {
                        continue;
                    }

                    $classMethods++;
                    $classStatements += $method['executableLines'];
                    $coveredClassStatements += $method['executedLines'];

                    if ($method['coverage'] == 100) {
                        $coveredMethods++;
                    }
                }

                $namespace = '';

                if (!empty($class['package']['namespace'])) {
                    $namespace = '\\' . $class['package']['namespace'] . '::';
                } elseif (!empty($class['package']['fullPackage'])) {
                    $namespace = '@' . $class['package']['fullPackage'] . '::';
                }

                $classCoverage[$namespace . $className] = [
                    'namespace'         => $namespace,
                    'className '        => $className,
                    'methodsCovered'    => $coveredMethods,
                    'methodCount'       => $classMethods,
                    'statementsCovered' => $coveredClassStatements,
                    'statementCount'    => $classStatements,
                ];
            }
        }

        \ksort($classCoverage);

        $methodColor = '';
        $linesColor  = '';
        $resetColor  = '';

        foreach ($classCoverage as $fullQualifiedPath => $classInfo) {
            if ($this->showUncoveredFiles || $classInfo['statementsCovered'] != 0) {
                if ($showColors) {
                    $methodColor = $this->getCoverageColor($classInfo['methodsCovered'], $classInfo['methodCount']);
                    $linesColor  = $this->getCoverageColor($classInfo['statementsCovered'], $classInfo['statementCount']);
                    $resetColor  = $colors['reset'];
                }

                $output .= \PHP_EOL . $fullQualifiedPath . \PHP_EOL
                    . '  ' . $methodColor . 'Methods: ' . $this->printCoverageCounts($classInfo['methodsCovered'], $classInfo['methodCount'], 2) . $resetColor . ' '
                    . '  ' . $linesColor . 'Lines: ' . $this->printCoverageCounts($classInfo['statementsCovered'], $classInfo['statementCount'], 3) . $resetColor;
            }
        }

        return $output . \PHP_EOL;
    }

    private function getCoverageColor(int $numberOfCoveredElements, int $totalNumberOfElements): string
    {
        $coverage = Util::percent(
            $numberOfCoveredElements,
            $totalNumberOfElements
        );

        if ($coverage >= $this->highLowerBound) {
            return self::COLOR_GREEN;
        }

        if ($coverage > $this->lowUpperBound) {
            return self::COLOR_YELLOW;
        }

        return self::COLOR_RED;
    }

    private function printCoverageCounts(int $numberOfCoveredElements, int $totalNumberOfElements, int $precision): string
    {
        $format = '%' . $precision . 's';

        return Util::percent(
            $numberOfCoveredElements,
            $totalNumberOfElements,
            true,
            true
        ) .
        ' (' . \sprintf($format, $numberOfCoveredElements) . '/' .
        \sprintf($format, $totalNumberOfElements) . ')';
    }

    private function format($color, $padding, $string): string
    {
        $reset = $color ? self::COLOR_RESET : '';

        return $color . \str_pad($string, $padding) . $reset . \PHP_EOL;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Report;

use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\CodeCoverage\RuntimeException;

final class Crap4j
{
    /**
     * @var int
     */
    private $threshold;

    public function __construct(int $threshold = 30)
    {
        $this->threshold = $threshold;
    }

    /**
     * @throws \RuntimeException
     */
    public function process(CodeCoverage $coverage, ?string $target = null, ?string $name = null): string
    {
        $document               = new \DOMDocument('1.0', 'UTF-8');
        $document->formatOutput = true;

        $root = $document->createElement('crap_result');
        $document->appendChild($root);

        $project = $document->createElement('project', \is_string($name) ? $name : '');
        $root->appendChild($project);
        $root->appendChild($document->createElement('timestamp', \date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME'])));

        $stats       = $document->createElement('stats');
        $methodsNode = $document->createElement('methods');

        $report = $coverage->getReport();
        unset($coverage);

        $fullMethodCount     = 0;
        $fullCrapMethodCount = 0;
        $fullCrapLoad        = 0;
        $fullCrap            = 0;

        foreach ($report as $item) {
            $namespace = 'global';

            if (!$item instanceof File) {
                continue;
            }

            $file = $document->createElement('file');
            $file->setAttribute('name', $item->getPath());

            $classes = $item->getClassesAndTraits();

            foreach ($classes as $className => $class) {
                foreach ($class['methods'] as $methodName => $method) {
                    $crapLoad = $this->getCrapLoad($method['crap'], $method['ccn'], $method['coverage']);

                    $fullCrap += $method['crap'];
                    $fullCrapLoad += $crapLoad;
                    $fullMethodCount++;

                    if ($method['crap'] >= $this->threshold) {
                        $fullCrapMethodCount++;
                    }

                    $methodNode = $document->createElement('method');

                    if (!empty($class['package']['namespace'])) {
                        $namespace = $class['package']['namespace'];
                    }

                    $methodNode->appendChild($document->createElement('package', $namespace));
                    $methodNode->appendChild($document->createElement('className', $className));
                    $methodNode->appendChild($document->createElement('methodName', $methodName));
                    $methodNode->appendChild($document->createElement('methodSignature', \htmlspecialchars($method['signature'])));
                    $methodNode->appendChild($document->createElement('fullMethod', \htmlspecialchars($method['signature'])));
                    $methodNode->appendChild($document->createElement('crap', (string) $this->roundValue($method['crap'])));
                    $methodNode->appendChild($document->createElement('complexity', (string) $method['ccn']));
                    $methodNode->appendChild($document->createElement('coverage', (string) $this->roundValue($method['coverage'])));
                    $methodNode->appendChild($document->createElement('crapLoad', (string) \round($crapLoad)));

                    $methodsNode->appendChild($methodNode);
                }
            }
        }

        $stats->appendChild($document->createElement('name', 'Method Crap Stats'));
        $stats->appendChild($document->createElement('methodCount', (string) $fullMethodCount));
        $stats->appendChild($document->createElement('crapMethodCount', (string) $fullCrapMethodCount));
        $stats->appendChild($document->createElement('crapLoad', (string) \round($fullCrapLoad)));
        $stats->appendChild($document->createElement('totalCrap', (string) $fullCrap));

        $crapMethodPercent = 0;

        if ($fullMethodCount > 0) {
            $crapMethodPercent = $this->roundValue((100 * $fullCrapMethodCount) / $fullMethodCount);
        }

        $stats->appendChild($document->createElement('crapMethodPercent', (string) $crapMethodPercent));

        $root->appendChild($stats);
        $root->appendChild($methodsNode);

        $buffer = $document->saveXML();

        if ($target !== null) {
            if (!$this->createDirectory(\dirname($target))) {
                throw new \RuntimeException(\sprintf('Directory "%s" was not created', \dirname($target)));
            }

            if (@\file_put_contents($target, $buffer) === false) {
                throw new RuntimeException(
                    \sprintf(
                        'Could not write to "%s',
                        $target
                    )
                );
            }
        }

        return $buffer;
    }

    /**
     * @param float $crapValue
     * @param int   $cyclomaticComplexity
     * @param float $coveragePercent
     */
    private function getCrapLoad($crapValue, $cyclomaticComplexity, $coveragePercent): float
    {
        $crapLoad = 0;

        if ($crapValue >= $this->threshold) {
            $crapLoad += $cyclomaticComplexity * (1.0 - $coveragePercent / 100);
            $crapLoad += $cyclomaticComplexity / $this->threshold;
        }

        return $crapLoad;
    }

    /**
     * @param float $value
     */
    private function roundValue($value): float
    {
        return \round($value, 2);
    }

    private function createDirectory(string $directory): bool
    {
        return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

/**
 * Utility methods.
 */
final class Util
{
    /**
     * @return float|int|string
     */
    public static function percent(float $a, float $b, bool $asString = false, bool $fixedWidth = false)
    {
        if ($asString && $b == 0) {
            return '';
        }

        $percent = 100;

        if ($b > 0) {
            $percent = ($a / $b) * 100;
        }

        if ($asString) {
            $format = $fixedWidth ? '%6.2F%%' : '%01.2F%%';

            return \sprintf($format, $percent);
        }

        return $percent;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Node;

/**
 * Represents a file in the code coverage information tree.
 */
final class File extends AbstractNode
{
    /**
     * @var array
     */
    private $coverageData;

    /**
     * @var array
     */
    private $testData;

    /**
     * @var int
     */
    private $numExecutableLines = 0;

    /**
     * @var int
     */
    private $numExecutedLines = 0;

    /**
     * @var array
     */
    private $classes = [];

    /**
     * @var array
     */
    private $traits = [];

    /**
     * @var array
     */
    private $functions = [];

    /**
     * @var array
     */
    private $linesOfCode = [];

    /**
     * @var int
     */
    private $numClasses;

    /**
     * @var int
     */
    private $numTestedClasses = 0;

    /**
     * @var int
     */
    private $numTraits;

    /**
     * @var int
     */
    private $numTestedTraits = 0;

    /**
     * @var int
     */
    private $numMethods;

    /**
     * @var int
     */
    private $numTestedMethods;

    /**
     * @var int
     */
    private $numTestedFunctions;

    /**
     * @var bool
     */
    private $cacheTokens;

    /**
     * @var array
     */
    private $codeUnitsByLine = [];

    public function __construct(string $name, AbstractNode $parent, array $coverageData, array $testData, bool $cacheTokens)
    {
        parent::__construct($name, $parent);

        $this->coverageData = $coverageData;
        $this->testData     = $testData;
        $this->cacheTokens  = $cacheTokens;

        $this->calculateStatistics();
    }

    /**
     * Returns the number of files in/under this node.
     */
    public function count(): int
    {
        return 1;
    }

    /**
     * Returns the code coverage data of this node.
     */
    public function getCoverageData(): array
    {
        return $this->coverageData;
    }

    /**
     * Returns the test data of this node.
     */
    public function getTestData(): array
    {
        return $this->testData;
    }

    /**
     * Returns the classes of this node.
     */
    public function getClasses(): array
    {
        return $this->classes;
    }

    /**
     * Returns the traits of this node.
     */
    public function getTraits(): array
    {
        return $this->traits;
    }

    /**
     * Returns the functions of this node.
     */
    public function getFunctions(): array
    {
        return $this->functions;
    }

    /**
     * Returns the LOC/CLOC/NCLOC of this node.
     */
    public function getLinesOfCode(): array
    {
        return $this->linesOfCode;
    }

    /**
     * Returns the number of executable lines.
     */
    public function getNumExecutableLines(): int
    {
        return $this->numExecutableLines;
    }

    /**
     * Returns the number of executed lines.
     */
    public function getNumExecutedLines(): int
    {
        return $this->numExecutedLines;
    }

    /**
     * Returns the number of classes.
     */
    public function getNumClasses(): int
    {
        if ($this->numClasses === null) {
            $this->numClasses = 0;

            foreach ($this->classes as $class) {
                foreach ($class['methods'] as $method) {
                    if ($method['executableLines'] > 0) {
                        $this->numClasses++;

                        continue 2;
                    }
                }
            }
        }

        return $this->numClasses;
    }

    /**
     * Returns the number of tested classes.
     */
    public function getNumTestedClasses(): int
    {
        return $this->numTestedClasses;
    }

    /**
     * Returns the number of traits.
     */
    public function getNumTraits(): int
    {
        if ($this->numTraits === null) {
            $this->numTraits = 0;

            foreach ($this->traits as $trait) {
                foreach ($trait['methods'] as $method) {
                    if ($method['executableLines'] > 0) {
                        $this->numTraits++;

                        continue 2;
                    }
                }
            }
        }

        return $this->numTraits;
    }

    /**
     * Returns the number of tested traits.
     */
    public function getNumTestedTraits(): int
    {
        return $this->numTestedTraits;
    }

    /**
     * Returns the number of methods.
     */
    public function getNumMethods(): int
    {
        if ($this->numMethods === null) {
            $this->numMethods = 0;

            foreach ($this->classes as $class) {
                foreach ($class['methods'] as $method) {
                    if ($method['executableLines'] > 0) {
                        $this->numMethods++;
                    }
                }
            }

            foreach ($this->traits as $trait) {
                foreach ($trait['methods'] as $method) {
                    if ($method['executableLines'] > 0) {
                        $this->numMethods++;
                    }
                }
            }
        }

        return $this->numMethods;
    }

    /**
     * Returns the number of tested methods.
     */
    public function getNumTestedMethods(): int
    {
        if ($this->numTestedMethods === null) {
            $this->numTestedMethods = 0;

            foreach ($this->classes as $class) {
                foreach ($class['methods'] as $method) {
                    if ($method['executableLines'] > 0 &&
                        $method['coverage'] === 100) {
                        $this->numTestedMethods++;
                    }
                }
            }

            foreach ($this->traits as $trait) {
                foreach ($trait['methods'] as $method) {
                    if ($method['executableLines'] > 0 &&
                        $method['coverage'] === 100) {
                        $this->numTestedMethods++;
                    }
                }
            }
        }

        return $this->numTestedMethods;
    }

    /**
     * Returns the number of functions.
     */
    public function getNumFunctions(): int
    {
        return \count($this->functions);
    }

    /**
     * Returns the number of tested functions.
     */
    public function getNumTestedFunctions(): int
    {
        if ($this->numTestedFunctions === null) {
            $this->numTestedFunctions = 0;

            foreach ($this->functions as $function) {
                if ($function['executableLines'] > 0 &&
                    $function['coverage'] === 100) {
                    $this->numTestedFunctions++;
                }
            }
        }

        return $this->numTestedFunctions;
    }

    private function calculateStatistics(): void
    {
        if ($this->cacheTokens) {
            $tokens = \PHP_Token_Stream_CachingFactory::get($this->getPath());
        } else {
            $tokens = new \PHP_Token_Stream($this->getPath());
        }

        $this->linesOfCode = $tokens->getLinesOfCode();

        foreach (\range(1, $this->linesOfCode['loc']) as $lineNumber) {
            $this->codeUnitsByLine[$lineNumber] = [];
        }

        try {
            $this->processClasses($tokens);
            $this->processTraits($tokens);
            $this->processFunctions($tokens);
        } catch (\OutOfBoundsException $e) {
            // This can happen with PHP_Token_Stream if the file is syntactically invalid,
            // and probably affects a file that wasn't executed.
        }
        unset($tokens);

        foreach (\range(1, $this->linesOfCode['loc']) as $lineNumber) {
            if (isset($this->coverageData[$lineNumber])) {
                foreach ($this->codeUnitsByLine[$lineNumber] as &$codeUnit) {
                    $codeUnit['executableLines']++;
                }

                unset($codeUnit);

                $this->numExecutableLines++;

                if (\count($this->coverageData[$lineNumber]) > 0) {
                    foreach ($this->codeUnitsByLine[$lineNumber] as &$codeUnit) {
                        $codeUnit['executedLines']++;
                    }

                    unset($codeUnit);

                    $this->numExecutedLines++;
                }
            }
        }

        foreach ($this->traits as &$trait) {
            foreach ($trait['methods'] as &$method) {
                if ($method['executableLines'] > 0) {
                    $method['coverage'] = ($method['executedLines'] /
                            $method['executableLines']) * 100;
                } else {
                    $method['coverage'] = 100;
                }

                $method['crap'] = $this->crap(
                    $method['ccn'],
                    $method['coverage']
                );

                $trait['ccn'] += $method['ccn'];
            }

            unset($method);

            if ($trait['executableLines'] > 0) {
                $trait['coverage'] = ($trait['executedLines'] /
                        $trait['executableLines']) * 100;

                if ($trait['coverage'] === 100) {
                    $this->numTestedClasses++;
                }
            } else {
                $trait['coverage'] = 100;
            }

            $trait['crap'] = $this->crap(
                $trait['ccn'],
                $trait['coverage']
            );
        }

        unset($trait);

        foreach ($this->classes as &$class) {
            foreach ($class['methods'] as &$method) {
                if ($method['executableLines'] > 0) {
                    $method['coverage'] = ($method['executedLines'] /
                            $method['executableLines']) * 100;
                } else {
                    $method['coverage'] = 100;
                }

                $method['crap'] = $this->crap(
                    $method['ccn'],
                    $method['coverage']
                );

                $class['ccn'] += $method['ccn'];
            }

            unset($method);

            if ($class['executableLines'] > 0) {
                $class['coverage'] = ($class['executedLines'] /
                        $class['executableLines']) * 100;

                if ($class['coverage'] === 100) {
                    $this->numTestedClasses++;
                }
            } else {
                $class['coverage'] = 100;
            }

            $class['crap'] = $this->crap(
                $class['ccn'],
                $class['coverage']
            );
        }

        unset($class);

        foreach ($this->functions as &$function) {
            if ($function['executableLines'] > 0) {
                $function['coverage'] = ($function['executedLines'] /
                        $function['executableLines']) * 100;
            } else {
                $function['coverage'] = 100;
            }

            if ($function['coverage'] === 100) {
                $this->numTestedFunctions++;
            }

            $function['crap'] = $this->crap(
                $function['ccn'],
                $function['coverage']
            );
        }
    }

    private function processClasses(\PHP_Token_Stream $tokens): void
    {
        $classes = $tokens->getClasses();
        $link    = $this->getId() . '.html#';

        foreach ($classes as $className => $class) {
            if (\strpos($className, 'anonymous') === 0) {
                continue;
            }

            if (!empty($class['package']['namespace'])) {
                $className = $class['package']['namespace'] . '\\' . $className;
            }

            $this->classes[$className] = [
                'className'       => $className,
                'methods'         => [],
                'startLine'       => $class['startLine'],
                'executableLines' => 0,
                'executedLines'   => 0,
                'ccn'             => 0,
                'coverage'        => 0,
                'crap'            => 0,
                'package'         => $class['package'],
                'link'            => $link . $class['startLine'],
            ];

            foreach ($class['methods'] as $methodName => $method) {
                if (\strpos($methodName, 'anonymous') === 0) {
                    continue;
                }

                $this->classes[$className]['methods'][$methodName] = $this->newMethod($methodName, $method, $link);

                foreach (\range($method['startLine'], $method['endLine']) as $lineNumber) {
                    $this->codeUnitsByLine[$lineNumber] = [
                        &$this->classes[$className],
                        &$this->classes[$className]['methods'][$methodName],
                    ];
                }
            }
        }
    }

    private function processTraits(\PHP_Token_Stream $tokens): void
    {
        $traits = $tokens->getTraits();
        $link   = $this->getId() . '.html#';

        foreach ($traits as $traitName => $trait) {
            $this->traits[$traitName] = [
                'traitName'       => $traitName,
                'methods'         => [],
                'startLine'       => $trait['startLine'],
                'executableLines' => 0,
                'executedLines'   => 0,
                'ccn'             => 0,
                'coverage'        => 0,
                'crap'            => 0,
                'package'         => $trait['package'],
                'link'            => $link . $trait['startLine'],
            ];

            foreach ($trait['methods'] as $methodName => $method) {
                if (\strpos($methodName, 'anonymous') === 0) {
                    continue;
                }

                $this->traits[$traitName]['methods'][$methodName] = $this->newMethod($methodName, $method, $link);

                foreach (\range($method['startLine'], $method['endLine']) as $lineNumber) {
                    $this->codeUnitsByLine[$lineNumber] = [
                        &$this->traits[$traitName],
                        &$this->traits[$traitName]['methods'][$methodName],
                    ];
                }
            }
        }
    }

    private function processFunctions(\PHP_Token_Stream $tokens): void
    {
        $functions = $tokens->getFunctions();
        $link      = $this->getId() . '.html#';

        foreach ($functions as $functionName => $function) {
            if (\strpos($functionName, 'anonymous') === 0) {
                continue;
            }

            $this->functions[$functionName] = [
                'functionName'    => $functionName,
                'signature'       => $function['signature'],
                'startLine'       => $function['startLine'],
                'executableLines' => 0,
                'executedLines'   => 0,
                'ccn'             => $function['ccn'],
                'coverage'        => 0,
                'crap'            => 0,
                'link'            => $link . $function['startLine'],
            ];

            foreach (\range($function['startLine'], $function['endLine']) as $lineNumber) {
                $this->codeUnitsByLine[$lineNumber] = [&$this->functions[$functionName]];
            }
        }
    }

    private function crap(int $ccn, float $coverage): string
    {
        if ($coverage === 0.0) {
            return (string) ($ccn ** 2 + $ccn);
        }

        if ($coverage >= 95) {
            return (string) $ccn;
        }

        return \sprintf(
            '%01.2F',
            $ccn ** 2 * (1 - $coverage / 100) ** 3 + $ccn
        );
    }

    private function newMethod(string $methodName, array $method, string $link): array
    {
        return [
            'methodName'      => $methodName,
            'visibility'      => $method['visibility'],
            'signature'       => $method['signature'],
            'startLine'       => $method['startLine'],
            'endLine'         => $method['endLine'],
            'executableLines' => 0,
            'executedLines'   => 0,
            'ccn'             => $method['ccn'],
            'coverage'        => 0,
            'crap'            => 0,
            'link'            => $link . $method['startLine'],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Node;

use SebastianBergmann\CodeCoverage\CodeCoverage;

final class Builder
{
    public function build(CodeCoverage $coverage): Directory
    {
        $files      = $coverage->getData();
        $commonPath = $this->reducePaths($files);
        $root       = new Directory(
            $commonPath,
            null
        );

        $this->addItems(
            $root,
            $this->buildDirectoryStructure($files),
            $coverage->getTests(),
            $coverage->getCacheTokens()
        );

        return $root;
    }

    private function addItems(Directory $root, array $items, array $tests, bool $cacheTokens): void
    {
        foreach ($items as $key => $value) {
            $key = (string) $key;

            if (\substr($key, -2) === '/f') {
                $key = \substr($key, 0, -2);

                if (\file_exists($root->getPath() . \DIRECTORY_SEPARATOR . $key)) {
                    $root->addFile($key, $value, $tests, $cacheTokens);
                }
            } else {
                $child = $root->addDirectory($key);
                $this->addItems($child, $value, $tests, $cacheTokens);
            }
        }
    }

    /**
     * Builds an array representation of the directory structure.
     *
     * For instance,
     *
     * <code>
     * Array
     * (
     *     [Money.php] => Array
     *         (
     *             ...
     *         )
     *
     *     [MoneyBag.php] => Array
     *         (
     *             ...
     *         )
     * )
     * </code>
     *
     * is transformed into
     *
     * <code>
     * Array
     * (
     *     [.] => Array
     *         (
     *             [Money.php] => Array
     *                 (
     *                     ...
     *                 )
     *
     *             [MoneyBag.php] => Array
     *                 (
     *                     ...
     *                 )
     *         )
     * )
     * </code>
     */
    private function buildDirectoryStructure(array $files): array
    {
        $result = [];

        foreach ($files as $path => $file) {
            $path    = \explode(\DIRECTORY_SEPARATOR, $path);
            $pointer = &$result;
            $max     = \count($path);

            for ($i = 0; $i < $max; $i++) {
                $type = '';

                if ($i === ($max - 1)) {
                    $type = '/f';
                }

                $pointer = &$pointer[$path[$i] . $type];
            }

            $pointer = $file;
        }

        return $result;
    }

    /**
     * Reduces the paths by cutting the longest common start path.
     *
     * For instance,
     *
     * <code>
     * Array
     * (
     *     [/home/sb/Money/Money.php] => Array
     *         (
     *             ...
     *         )
     *
     *     [/home/sb/Money/MoneyBag.php] => Array
     *         (
     *             ...
     *         )
     * )
     * </code>
     *
     * is reduced to
     *
     * <code>
     * Array
     * (
     *     [Money.php] => Array
     *         (
     *             ...
     *         )
     *
     *     [MoneyBag.php] => Array
     *         (
     *             ...
     *         )
     * )
     * </code>
     */
    private function reducePaths(array &$files): string
    {
        if (empty($files)) {
            return '.';
        }

        $commonPath = '';
        $paths      = \array_keys($files);

        if (\count($files) === 1) {
            $commonPath                  = \dirname($paths[0]) . \DIRECTORY_SEPARATOR;
            $files[\basename($paths[0])] = $files[$paths[0]];

            unset($files[$paths[0]]);

            return $commonPath;
        }

        $max = \count($paths);

        for ($i = 0; $i < $max; $i++) {
            // strip phar:// prefixes
            if (\strpos($paths[$i], 'phar://') === 0) {
                $paths[$i] = \substr($paths[$i], 7);
                $paths[$i] = \str_replace('/', \DIRECTORY_SEPARATOR, $paths[$i]);
            }
            $paths[$i] = \explode(\DIRECTORY_SEPARATOR, $paths[$i]);

            if (empty($paths[$i][0])) {
                $paths[$i][0] = \DIRECTORY_SEPARATOR;
            }
        }

        $done = false;
        $max  = \count($paths);

        while (!$done) {
            for ($i = 0; $i < $max - 1; $i++) {
                if (!isset($paths[$i][0]) ||
                    !isset($paths[$i + 1][0]) ||
                    $paths[$i][0] !== $paths[$i + 1][0]) {
                    $done = true;

                    break;
                }
            }

            if (!$done) {
                $commonPath .= $paths[0][0];

                if ($paths[0][0] !== \DIRECTORY_SEPARATOR) {
                    $commonPath .= \DIRECTORY_SEPARATOR;
                }

                for ($i = 0; $i < $max; $i++) {
                    \array_shift($paths[$i]);
                }
            }
        }

        $original = \array_keys($files);
        $max      = \count($original);

        for ($i = 0; $i < $max; $i++) {
            $files[\implode(\DIRECTORY_SEPARATOR, $paths[$i])] = $files[$original[$i]];
            unset($files[$original[$i]]);
        }

        \ksort($files);

        return \substr($commonPath, 0, -1);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Node;

use SebastianBergmann\CodeCoverage\Util;

/**
 * Base class for nodes in the code coverage information tree.
 */
abstract class AbstractNode implements \Countable
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $path;

    /**
     * @var array
     */
    private $pathArray;

    /**
     * @var AbstractNode
     */
    private $parent;

    /**
     * @var string
     */
    private $id;

    public function __construct(string $name, self $parent = null)
    {
        if (\substr($name, -1) == \DIRECTORY_SEPARATOR) {
            $name = \substr($name, 0, -1);
        }

        $this->name   = $name;
        $this->parent = $parent;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getId(): string
    {
        if ($this->id === null) {
            $parent = $this->getParent();

            if ($parent === null) {
                $this->id = 'index';
            } else {
                $parentId = $parent->getId();

                if ($parentId === 'index') {
                    $this->id = \str_replace(':', '_', $this->name);
                } else {
                    $this->id = $parentId . '/' . $this->name;
                }
            }
        }

        return $this->id;
    }

    public function getPath(): string
    {
        if ($this->path === null) {
            if ($this->parent === null || $this->parent->getPath() === null || $this->parent->getPath() === false) {
                $this->path = $this->name;
            } else {
                $this->path = $this->parent->getPath() . \DIRECTORY_SEPARATOR . $this->name;
            }
        }

        return $this->path;
    }

    public function getPathAsArray(): array
    {
        if ($this->pathArray === null) {
            if ($this->parent === null) {
                $this->pathArray = [];
            } else {
                $this->pathArray = $this->parent->getPathAsArray();
            }

            $this->pathArray[] = $this;
        }

        return $this->pathArray;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    /**
     * Returns the percentage of classes that has been tested.
     *
     * @return int|string
     */
    public function getTestedClassesPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedClasses(),
            $this->getNumClasses(),
            $asString
        );
    }

    /**
     * Returns the percentage of traits that has been tested.
     *
     * @return int|string
     */
    public function getTestedTraitsPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedTraits(),
            $this->getNumTraits(),
            $asString
        );
    }

    /**
     * Returns the percentage of classes and traits that has been tested.
     *
     * @return int|string
     */
    public function getTestedClassesAndTraitsPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedClassesAndTraits(),
            $this->getNumClassesAndTraits(),
            $asString
        );
    }

    /**
     * Returns the percentage of functions that has been tested.
     *
     * @return int|string
     */
    public function getTestedFunctionsPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedFunctions(),
            $this->getNumFunctions(),
            $asString
        );
    }

    /**
     * Returns the percentage of methods that has been tested.
     *
     * @return int|string
     */
    public function getTestedMethodsPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedMethods(),
            $this->getNumMethods(),
            $asString
        );
    }

    /**
     * Returns the percentage of functions and methods that has been tested.
     *
     * @return int|string
     */
    public function getTestedFunctionsAndMethodsPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumTestedFunctionsAndMethods(),
            $this->getNumFunctionsAndMethods(),
            $asString
        );
    }

    /**
     * Returns the percentage of executed lines.
     *
     * @return int|string
     */
    public function getLineExecutedPercent(bool $asString = true)
    {
        return Util::percent(
            $this->getNumExecutedLines(),
            $this->getNumExecutableLines(),
            $asString
        );
    }

    /**
     * Returns the number of classes and traits.
     */
    public function getNumClassesAndTraits(): int
    {
        return $this->getNumClasses() + $this->getNumTraits();
    }

    /**
     * Returns the number of tested classes and traits.
     */
    public function getNumTestedClassesAndTraits(): int
    {
        return $this->getNumTestedClasses() + $this->getNumTestedTraits();
    }

    /**
     * Returns the classes and traits of this node.
     */
    public function getClassesAndTraits(): array
    {
        return \array_merge($this->getClasses(), $this->getTraits());
    }

    /**
     * Returns the number of functions and methods.
     */
    public function getNumFunctionsAndMethods(): int
    {
        return $this->getNumFunctions() + $this->getNumMethods();
    }

    /**
     * Returns the number of tested functions and methods.
     */
    public function getNumTestedFunctionsAndMethods(): int
    {
        return $this->getNumTestedFunctions() + $this->getNumTestedMethods();
    }

    /**
     * Returns the functions and methods of this node.
     */
    public function getFunctionsAndMethods(): array
    {
        return \array_merge($this->getFunctions(), $this->getMethods());
    }

    /**
     * Returns the classes of this node.
     */
    abstract public function getClasses(): array;

    /**
     * Returns the traits of this node.
     */
    abstract public function getTraits(): array;

    /**
     * Returns the functions of this node.
     */
    abstract public function getFunctions(): array;

    /**
     * Returns the LOC/CLOC/NCLOC of this node.
     */
    abstract public function getLinesOfCode(): array;

    /**
     * Returns the number of executable lines.
     */
    abstract public function getNumExecutableLines(): int;

    /**
     * Returns the number of executed lines.
     */
    abstract public function getNumExecutedLines(): int;

    /**
     * Returns the number of classes.
     */
    abstract public function getNumClasses(): int;

    /**
     * Returns the number of tested classes.
     */
    abstract public function getNumTestedClasses(): int;

    /**
     * Returns the number of traits.
     */
    abstract public function getNumTraits(): int;

    /**
     * Returns the number of tested traits.
     */
    abstract public function getNumTestedTraits(): int;

    /**
     * Returns the number of methods.
     */
    abstract public function getNumMethods(): int;

    /**
     * Returns the number of tested methods.
     */
    abstract public function getNumTestedMethods(): int;

    /**
     * Returns the number of functions.
     */
    abstract public function getNumFunctions(): int;

    /**
     * Returns the number of tested functions.
     */
    abstract public function getNumTestedFunctions(): int;
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Node;

use SebastianBergmann\CodeCoverage\InvalidArgumentException;

/**
 * Represents a directory in the code coverage information tree.
 */
final class Directory extends AbstractNode implements \IteratorAggregate
{
    /**
     * @var AbstractNode[]
     */
    private $children = [];

    /**
     * @var Directory[]
     */
    private $directories = [];

    /**
     * @var File[]
     */
    private $files = [];

    /**
     * @var array
     */
    private $classes;

    /**
     * @var array
     */
    private $traits;

    /**
     * @var array
     */
    private $functions;

    /**
     * @var array
     */
    private $linesOfCode;

    /**
     * @var int
     */
    private $numFiles = -1;

    /**
     * @var int
     */
    private $numExecutableLines = -1;

    /**
     * @var int
     */
    private $numExecutedLines = -1;

    /**
     * @var int
     */
    private $numClasses = -1;

    /**
     * @var int
     */
    private $numTestedClasses = -1;

    /**
     * @var int
     */
    private $numTraits = -1;

    /**
     * @var int
     */
    private $numTestedTraits = -1;

    /**
     * @var int
     */
    private $numMethods = -1;

    /**
     * @var int
     */
    private $numTestedMethods = -1;

    /**
     * @var int
     */
    private $numFunctions = -1;

    /**
     * @var int
     */
    private $numTestedFunctions = -1;

    /**
     * Returns the number of files in/under this node.
     */
    public function count(): int
    {
        if ($this->numFiles === -1) {
            $this->numFiles = 0;

            foreach ($this->children as $child) {
                $this->numFiles += \count($child);
            }
        }

        return $this->numFiles;
    }

    /**
     * Returns an iterator for this node.
     */
    public function getIterator(): \RecursiveIteratorIterator
    {
        return new \RecursiveIteratorIterator(
            new Iterator($this),
            \RecursiveIteratorIterator::SELF_FIRST
        );
    }

    /**
     * Adds a new directory.
     */
    public function addDirectory(string $name): self
    {
        $directory = new self($name, $this);

        $this->children[]    = $directory;
        $this->directories[] = &$this->children[\count($this->children) - 1];

        return $directory;
    }

    /**
     * Adds a new file.
     *
     * @throws InvalidArgumentException
     */
    public function addFile(string $name, array $coverageData, array $testData, bool $cacheTokens): File
    {
        $file = new File($name, $this, $coverageData, $testData, $cacheTokens);

        $this->children[] = $file;
        $this->files[]    = &$this->children[\count($this->children) - 1];

        $this->numExecutableLines = -1;
        $this->numExecutedLines   = -1;

        return $file;
    }

    /**
     * Returns the directories in this directory.
     */
    public function getDirectories(): array
    {
        return $this->directories;
    }

    /**
     * Returns the files in this directory.
     */
    public function getFiles(): array
    {
        return $this->files;
    }

    /**
     * Returns the child nodes of this node.
     */
    public function getChildNodes(): array
    {
        return $this->children;
    }

    /**
     * Returns the classes of this node.
     */
    public function getClasses(): array
    {
        if ($this->classes === null) {
            $this->classes = [];

            foreach ($this->children as $child) {
                $this->classes = \array_merge(
                    $this->classes,
                    $child->getClasses()
                );
            }
        }

        return $this->classes;
    }

    /**
     * Returns the traits of this node.
     */
    public function getTraits(): array
    {
        if ($this->traits === null) {
            $this->traits = [];

            foreach ($this->children as $child) {
                $this->traits = \array_merge(
                    $this->traits,
                    $child->getTraits()
                );
            }
        }

        return $this->traits;
    }

    /**
     * Returns the functions of this node.
     */
    public function getFunctions(): array
    {
        if ($this->functions === null) {
            $this->functions = [];

            foreach ($this->children as $child) {
                $this->functions = \array_merge(
                    $this->functions,
                    $child->getFunctions()
                );
            }
        }

        return $this->functions;
    }

    /**
     * Returns the LOC/CLOC/NCLOC of this node.
     */
    public function getLinesOfCode(): array
    {
        if ($this->linesOfCode === null) {
            $this->linesOfCode = ['loc' => 0, 'cloc' => 0, 'ncloc' => 0];

            foreach ($this->children as $child) {
                $linesOfCode = $child->getLinesOfCode();

                $this->linesOfCode['loc'] += $linesOfCode['loc'];
                $this->linesOfCode['cloc'] += $linesOfCode['cloc'];
                $this->linesOfCode['ncloc'] += $linesOfCode['ncloc'];
            }
        }

        return $this->linesOfCode;
    }

    /**
     * Returns the number of executable lines.
     */
    public function getNumExecutableLines(): int
    {
        if ($this->numExecutableLines === -1) {
            $this->numExecutableLines = 0;

            foreach ($this->children as $child) {
                $this->numExecutableLines += $child->getNumExecutableLines();
            }
        }

        return $this->numExecutableLines;
    }

    /**
     * Returns the number of executed lines.
     */
    public function getNumExecutedLines(): int
    {
        if ($this->numExecutedLines === -1) {
            $this->numExecutedLines = 0;

            foreach ($this->children as $child) {
                $this->numExecutedLines += $child->getNumExecutedLines();
            }
        }

        return $this->numExecutedLines;
    }

    /**
     * Returns the number of classes.
     */
    public function getNumClasses(): int
    {
        if ($this->numClasses === -1) {
            $this->numClasses = 0;

            foreach ($this->children as $child) {
                $this->numClasses += $child->getNumClasses();
            }
        }

        return $this->numClasses;
    }

    /**
     * Returns the number of tested classes.
     */
    public function getNumTestedClasses(): int
    {
        if ($this->numTestedClasses === -1) {
            $this->numTestedClasses = 0;

            foreach ($this->children as $child) {
                $this->numTestedClasses += $child->getNumTestedClasses();
            }
        }

        return $this->numTestedClasses;
    }

    /**
     * Returns the number of traits.
     */
    public function getNumTraits(): int
    {
        if ($this->numTraits === -1) {
            $this->numTraits = 0;

            foreach ($this->children as $child) {
                $this->numTraits += $child->getNumTraits();
            }
        }

        return $this->numTraits;
    }

    /**
     * Returns the number of tested traits.
     */
    public function getNumTestedTraits(): int
    {
        if ($this->numTestedTraits === -1) {
            $this->numTestedTraits = 0;

            foreach ($this->children as $child) {
                $this->numTestedTraits += $child->getNumTestedTraits();
            }
        }

        return $this->numTestedTraits;
    }

    /**
     * Returns the number of methods.
     */
    public function getNumMethods(): int
    {
        if ($this->numMethods === -1) {
            $this->numMethods = 0;

            foreach ($this->children as $child) {
                $this->numMethods += $child->getNumMethods();
            }
        }

        return $this->numMethods;
    }

    /**
     * Returns the number of tested methods.
     */
    public function getNumTestedMethods(): int
    {
        if ($this->numTestedMethods === -1) {
            $this->numTestedMethods = 0;

            foreach ($this->children as $child) {
                $this->numTestedMethods += $child->getNumTestedMethods();
            }
        }

        return $this->numTestedMethods;
    }

    /**
     * Returns the number of functions.
     */
    public function getNumFunctions(): int
    {
        if ($this->numFunctions === -1) {
            $this->numFunctions = 0;

            foreach ($this->children as $child) {
                $this->numFunctions += $child->getNumFunctions();
            }
        }

        return $this->numFunctions;
    }

    /**
     * Returns the number of tested functions.
     */
    public function getNumTestedFunctions(): int
    {
        if ($this->numTestedFunctions === -1) {
            $this->numTestedFunctions = 0;

            foreach ($this->children as $child) {
                $this->numTestedFunctions += $child->getNumTestedFunctions();
            }
        }

        return $this->numTestedFunctions;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage\Node;

/**
 * Recursive iterator for node object graphs.
 */
final class Iterator implements \RecursiveIterator
{
    /**
     * @var int
     */
    private $position;

    /**
     * @var AbstractNode[]
     */
    private $nodes;

    public function __construct(Directory $node)
    {
        $this->nodes = $node->getChildNodes();
    }

    /**
     * Rewinds the Iterator to the first element.
     */
    public function rewind(): void
    {
        $this->position = 0;
    }

    /**
     * Checks if there is a current element after calls to rewind() or next().
     */
    public function valid(): bool
    {
        return $this->position < \count($this->nodes);
    }

    /**
     * Returns the key of the current element.
     */
    public function key(): int
    {
        return $this->position;
    }

    /**
     * Returns the current element.
     */
    public function current(): AbstractNode
    {
        return $this->valid() ? $this->nodes[$this->position] : null;
    }

    /**
     * Moves forward to next element.
     */
    public function next(): void
    {
        $this->position++;
    }

    /**
     * Returns the sub iterator for the current element.
     *
     * @return Iterator
     */
    public function getChildren(): self
    {
        return new self($this->nodes[$this->position]);
    }

    /**
     * Checks whether the current element has children.
     */
    public function hasChildren(): bool
    {
        return $this->nodes[$this->position] instanceof Directory;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

/**
 * Exception that is raised when code is unintentionally covered.
 */
final class UnintentionallyCoveredCodeException extends RuntimeException
{
    /**
     * @var array
     */
    private $unintentionallyCoveredUnits = [];

    public function __construct(array $unintentionallyCoveredUnits)
    {
        $this->unintentionallyCoveredUnits = $unintentionallyCoveredUnits;

        parent::__construct($this->toString());
    }

    public function getUnintentionallyCoveredUnits(): array
    {
        return $this->unintentionallyCoveredUnits;
    }

    private function toString(): string
    {
        $message = '';

        foreach ($this->unintentionallyCoveredUnits as $unit) {
            $message .= '- ' . $unit . "\n";
        }

        return $message;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

class RuntimeException extends \RuntimeException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

/**
 * Exception that is raised when covered code is not executed.
 */
final class CoveredCodeNotExecutedException extends RuntimeException
{
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

final class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
    /**
     * @param int        $argument
     * @param string     $type
     * @param null|mixed $value
     *
     * @return InvalidArgumentException
     */
    public static function create($argument, $type, $value = null): self
    {
        $stack = \debug_backtrace(0);

        return new self(
            \sprintf(
                'Argument #%d%sof %s::%s() must be a %s',
                $argument,
                $value !== null ? ' (' . \gettype($value) . '#' . $value . ')' : ' (No Value) ',
                $stack[1]['class'],
                $stack[1]['function'],
                $type
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

/**
 * Exception that is raised when @covers must be used but is not.
 */
final class MissingCoversAnnotationException extends RuntimeException
{
}
<?php declare(strict_types=1);
/*
 * This file is part of the php-code-coverage package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\CodeCoverage;

/**
 * Exception interface for php-code-coverage component.
 */
interface Exception
{
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.2/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
php-file-iterator

Copyright (c) 2009-2018, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Change Log

All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).

## [2.0.5] - 2021-12-02

### Changed

* [#73](https://github.com/sebastianbergmann/php-file-iterator/pull/73): Micro performance improvements on parsing paths

### Fixed

* [#74](https://github.com/sebastianbergmann/php-file-iterator/pull/74): Document return type of `SebastianBergmann\FileIterator\Iterator::accept()` so that Symfony's `DebugClassLoader` does not trigger a deprecation warning

## [2.0.4] - 2021-07-19

### Changed

* Added `ReturnTypeWillChange` attribute to `SebastianBergmann\FileIterator\Iterator::accept()` because the return type of `\FilterIterator::accept()` will change in PHP 8.1

## [2.0.3] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [2.0.2] - 2018-09-13

### Fixed

* [#48](https://github.com/sebastianbergmann/php-file-iterator/issues/48): Excluding an array that contains false ends up excluding the current working directory

## [2.0.1] - 2018-06-11

### Fixed

* [#46](https://github.com/sebastianbergmann/php-file-iterator/issues/46): Regression with hidden parent directory

## [2.0.0] - 2018-05-28

### Fixed

* [#30](https://github.com/sebastianbergmann/php-file-iterator/issues/30): Exclude is not considered if it is a parent of the base path

### Changed

* This component now uses namespaces

### Removed

* This component is no longer supported on PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6, and PHP 7.0

## [1.4.5] - 2017-11-27

### Fixed

* [#37](https://github.com/sebastianbergmann/php-file-iterator/issues/37): Regression caused by fix for [#30](https://github.com/sebastianbergmann/php-file-iterator/issues/30)

## [1.4.4] - 2017-11-27

### Fixed

* [#30](https://github.com/sebastianbergmann/php-file-iterator/issues/30): Exclude is not considered if it is a parent of the base path

## [1.4.3] - 2017-11-25

### Fixed

* [#34](https://github.com/sebastianbergmann/php-file-iterator/issues/34): Factory should use canonical directory names

## [1.4.2] - 2016-11-26

No changes

## [1.4.1] - 2015-07-26

No changes

## 1.4.0 - 2015-04-02

### Added

* [Added support for wildcards (glob) in exclude](https://github.com/sebastianbergmann/php-file-iterator/pull/23)

[2.0.5]: https://github.com/sebastianbergmann/php-file-iterator/compare/2.0.4...2.0.5
[2.0.4]: https://github.com/sebastianbergmann/php-file-iterator/compare/2.0.3...2.0.4
[2.0.3]: https://github.com/sebastianbergmann/php-file-iterator/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/sebastianbergmann/php-file-iterator/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/sebastianbergmann/php-file-iterator/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4...2.0.0
[1.4.5]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4.4...1.4.5
[1.4.4]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4.3...1.4.4
[1.4.3]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4.2...1.4.3
[1.4.2]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4.1...1.4.2
[1.4.1]: https://github.com/sebastianbergmann/php-file-iterator/compare/1.4.0...1.4.1
<?php
/*
 * This file is part of php-file-iterator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\FileIterator;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\FileIterator\Factory
 */
class FactoryTest extends TestCase
{
    /**
     * @var string
     */
    private $root;

    /**
     * @var Factory
     */
    private $factory;

    protected function setUp(): void
    {
        $this->root    = __DIR__;
        $this->factory = new Factory;
    }

    public function testFindFilesInTestDirectory(): void
    {
        $iterator = $this->factory->getFileIterator($this->root, 'Test.php');
        $files    = \iterator_to_array($iterator);

        $this->assertGreaterThanOrEqual(1, \count($files));
    }

    public function testFindFilesWithExcludedNonExistingSubdirectory(): void
    {
        $iterator = $this->factory->getFileIterator($this->root, 'Test.php', '', [$this->root . '/nonExistingDir']);
        $files    = \iterator_to_array($iterator);

        $this->assertGreaterThanOrEqual(1, \count($files));
    }
}
[![Build Status](https://travis-ci.org/sebastianbergmann/php-file-iterator.svg?branch=master)](https://travis-ci.org/sebastianbergmann/php-file-iterator)

# php-file-iterator

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require phpunit/php-file-iterator

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev phpunit/php-file-iterator

/.idea
/vendor/
/.php_cs
/.php_cs.cache
/composer.lock
# Configuration for probot-stale - https://github.com/probot/stale

# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale Issue or Pull Request is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 7

# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
  - enhancement

# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false

# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false

# Label to use when marking as stale
staleLabel: stale

# Comment to post when marking as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.

# Comment to post when removing the stale label.
# unmarkComment: >
#   Your comment here.

# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
  This issue has been automatically closed because it has not had activity since it was marked as stale. Thank you for your contributions.

# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

# Limit to only `issues` or `pulls`
only: issues

*.php diff=php
language: php

sudo: false

php:
  - 7.1
  - 7.2
  - master

env:
  matrix:
    - DEPENDENCIES="high"
    - DEPENDENCIES="low"
  global:
    - DEFAULT_COMPOSER_FLAGS="--no-interaction --no-ansi --no-progress --no-suggest"

before_install:
  - composer self-update
  - composer clear-cache

install:
  - if [[ "$DEPENDENCIES" = 'high' ]]; then travis_retry composer update $DEFAULT_COMPOSER_FLAGS; fi
  - if [[ "$DEPENDENCIES" = 'low' ]]; then travis_retry composer update $DEFAULT_COMPOSER_FLAGS --prefer-lowest; fi

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "phpunit/php-file-iterator",
    "description": "FilterIterator implementation that filters files based on a list of suffixes.",
    "type": "library",
    "keywords": [
        "iterator",
        "filesystem"
    ],
    "homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues"
    },
    "require": {
        "php": ">=7.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.5"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "2.0.x-dev"
        }
    }
}
<?php
$header = <<<'EOF'
This file is part of php-file-iterator.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['method']],
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'no_alias_functions' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_null_property_initialization' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_types' => true,
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => true,
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
        ->notName('*.phpt')
    );
<?php
/*
 * This file is part of php-file-iterator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\FileIterator;

class Factory
{
    /**
     * @param array|string $paths
     * @param array|string $suffixes
     * @param array|string $prefixes
     * @param array        $exclude
     *
     * @return \AppendIterator
     */
    public function getFileIterator($paths, $suffixes = '', $prefixes = '', array $exclude = []): \AppendIterator
    {
        if (\is_string($paths)) {
            $paths = [$paths];
        }

        $paths   = $this->getPathsAfterResolvingWildcards($paths);
        $exclude = $this->getPathsAfterResolvingWildcards($exclude);

        if (\is_string($prefixes)) {
            if ($prefixes !== '') {
                $prefixes = [$prefixes];
            } else {
                $prefixes = [];
            }
        }

        if (\is_string($suffixes)) {
            if ($suffixes !== '') {
                $suffixes = [$suffixes];
            } else {
                $suffixes = [];
            }
        }

        $iterator = new \AppendIterator;

        foreach ($paths as $path) {
            if (\is_dir($path)) {
                $iterator->append(
                    new Iterator(
                        $path,
                        new \RecursiveIteratorIterator(
                            new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS | \RecursiveDirectoryIterator::SKIP_DOTS)
                        ),
                        $suffixes,
                        $prefixes,
                        $exclude
                    )
                );
            }
        }

        return $iterator;
    }

    protected function getPathsAfterResolvingWildcards(array $paths): array
    {
        $_paths = [[]];

        foreach ($paths as $path) {
            if ($locals = \glob($path, GLOB_ONLYDIR)) {
                $_paths[] = \array_map('\realpath', $locals);
            } else {
                $_paths[] = [\realpath($path)];
            }
        }

        return \array_filter(\array_merge(...$_paths));
    }
}
<?php
/*
 * This file is part of php-file-iterator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\FileIterator;

class Iterator extends \FilterIterator
{
    const PREFIX = 0;
    const SUFFIX = 1;

    /**
     * @var string
     */
    private $basePath;

    /**
     * @var array
     */
    private $suffixes = [];

    /**
     * @var array
     */
    private $prefixes = [];

    /**
     * @var array
     */
    private $exclude = [];

    /**
     * @param string    $basePath
     * @param \Iterator $iterator
     * @param array     $suffixes
     * @param array     $prefixes
     * @param array     $exclude
     */
    public function __construct(string $basePath, \Iterator $iterator, array $suffixes = [], array $prefixes = [], array $exclude = [])
    {
        $this->basePath = \realpath($basePath);
        $this->prefixes = $prefixes;
        $this->suffixes = $suffixes;
        $this->exclude  = \array_filter(\array_map('realpath', $exclude));

        parent::__construct($iterator);
    }

    /**
     * @return bool
     */
    #[\ReturnTypeWillChange]
    public function accept()
    {
        $current  = $this->getInnerIterator()->current();
        $filename = $current->getFilename();
        $realPath = $current->getRealPath();

        return $this->acceptPath($realPath) &&
               $this->acceptPrefix($filename) &&
               $this->acceptSuffix($filename);
    }

    private function acceptPath(string $path): bool
    {
        // Filter files in hidden directories by checking path that is relative to the base path.
        if (\preg_match('=/\.[^/]*/=', \str_replace($this->basePath, '', $path))) {
            return false;
        }

        foreach ($this->exclude as $exclude) {
            if (\strpos($path, $exclude) === 0) {
                return false;
            }
        }

        return true;
    }

    private function acceptPrefix(string $filename): bool
    {
        return $this->acceptSubString($filename, $this->prefixes, self::PREFIX);
    }

    private function acceptSuffix(string $filename): bool
    {
        return $this->acceptSubString($filename, $this->suffixes, self::SUFFIX);
    }

    private function acceptSubString(string $filename, array $subStrings, int $type): bool
    {
        if (empty($subStrings)) {
            return true;
        }

        $matched = false;

        foreach ($subStrings as $string) {
            if (($type === self::PREFIX && \strpos($filename, $string) === 0) ||
                ($type === self::SUFFIX &&
                 \substr($filename, -1 * \strlen($string)) === $string)) {
                $matched = true;

                break;
            }
        }

        return $matched;
    }
}
<?php
/*
 * This file is part of php-file-iterator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\FileIterator;

class Facade
{
    /**
     * @param array|string $paths
     * @param array|string $suffixes
     * @param array|string $prefixes
     * @param array        $exclude
     * @param bool         $commonPath
     *
     * @return array
     */
    public function getFilesAsArray($paths, $suffixes = '', $prefixes = '', array $exclude = [], bool $commonPath = false): array
    {
        if (\is_string($paths)) {
            $paths = [$paths];
        }

        $factory = new Factory;

        $iterator = $factory->getFileIterator($paths, $suffixes, $prefixes, $exclude);

        $files = [];

        foreach ($iterator as $file) {
            $file = $file->getRealPath();

            if ($file) {
                $files[] = $file;
            }
        }

        foreach ($paths as $path) {
            if (\is_file($path)) {
                $files[] = \realpath($path);
            }
        }

        $files = \array_unique($files);
        \sort($files);

        if ($commonPath) {
            return [
              'commonPath' => $this->getCommonPath($files),
              'files'      => $files
            ];
        }

        return $files;
    }

    protected function getCommonPath(array $files): string
    {
        $count = \count($files);

        if ($count === 0) {
            return '';
        }

        if ($count === 1) {
            return \dirname($files[0]) . DIRECTORY_SEPARATOR;
        }

        $_files = [];

        foreach ($files as $file) {
            $_files[] = $_fileParts = \explode(DIRECTORY_SEPARATOR, $file);

            if (empty($_fileParts[0])) {
                $_fileParts[0] = DIRECTORY_SEPARATOR;
            }
        }

        $common = '';
        $done   = false;
        $j      = 0;
        $count--;

        while (!$done) {
            for ($i = 0; $i < $count; $i++) {
                if ($_files[$i][$j] != $_files[$i + 1][$j]) {
                    $done = true;

                    break;
                }
            }

            if (!$done) {
                $common .= $_files[0][$j];

                if ($j > 0) {
                    $common .= DIRECTORY_SEPARATOR;
                }
            }

            $j++;
        }

        return DIRECTORY_SEPARATOR . $common;
    }
}
{
    "_readme": [
        "This file locks the dependencies of your project to a known state",
        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
        "This file is @generated automatically"
    ],
    "content-hash": "f2ac4614ce4f7273fd54a64b65fd047a",
    "packages": [
        {
            "name": "phar-io/version",
            "version": "3.0.1",
            "source": {
                "type": "git",
                "url": "https://github.com/phar-io/version.git",
                "reference": "d06a5000ac1a258a7d035295f0bd4ae7c859bc4f"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/phar-io/version/zipball/d06a5000ac1a258a7d035295f0bd4ae7c859bc4f",
                "reference": "d06a5000ac1a258a7d035295f0bd4ae7c859bc4f",
                "shasum": ""
            },
            "require": {
                "php": "^7.2"
            },
            "type": "library",
            "autoload": {
                "classmap": [
                    "src/"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "BSD-3-Clause"
            ],
            "authors": [
                {
                    "name": "Arne Blankerts",
                    "email": "arne@blankerts.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Heuer",
                    "email": "sebastian@phpeople.de",
                    "role": "Developer"
                },
                {
                    "name": "Sebastian Bergmann",
                    "email": "sebastian@phpunit.de",
                    "role": "Developer"
                }
            ],
            "description": "Library for handling version information and constraints",
            "time": "2020-05-09T21:27:55+00:00"
        }
    ],
    "packages-dev": [],
    "aliases": [],
    "minimum-stability": "stable",
    "stability-flags": [],
    "prefer-stable": false,
    "prefer-lowest": false,
    "platform": {
        "php": "^7.2",
        "ext-dom": "*",
        "ext-phar": "*",
        "ext-xmlwriter": "*"
    },
    "platform-dev": []
}
Phar.io - Manifest

Copyright (c) 2016-2019 Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>, and contributors
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 Arne Blankerts nor the names of 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 HOLDER OR 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.

# Changelog

All notable changes to phar-io/manifest are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [2.0.3] - 20.07.2021

- Fixed PHP 7.2 / PHP 7.3 incompatibility introduced in previous release

## [2.0.2] - 20.07.2021

- Fixed PHP 8.1 deprecation notice

## [2.0.1] - 27.06.2020

This release now supports the use of PHP 7.2+ and ^8.0

## [2.0.0] - 10.05.2020

This release now requires PHP 7.2+

### Changed

- Upgraded to phar-io/version 3.0
    - Version strings `v1.2.3` will now be converted to valid semantic version strings `1.2.3`
    - Abreviated strings like `1.0` will get expaneded to `1.0.0`  

### Unreleased

[Unreleased]: https://github.com/phar-io/manifest/compare/2.0.3...HEAD
[2.0.3]: https://github.com/phar-io/manifest/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/phar-io/manifest/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/phar-io/manifest/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/phar-io/manifest/compare/1.0.1...2.0.0
[1.0.3]: https://github.com/phar-io/manifest/compare/1.0.2...1.0.3
[1.0.2]: https://github.com/phar-io/manifest/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/phar-io/manifest/compare/1.0.0...1.0.1
# Manifest

Component for reading [phar.io](https://phar.io/) manifest information from a [PHP Archive (PHAR)](http://php.net/phar).

[![Build Status](https://travis-ci.org/phar-io/manifest.svg?branch=master)](https://travis-ci.org/phar-io/manifest)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phar-io/manifest/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phar-io/manifest/?branch=master)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/d8cc6035-69ad-477d-bd1a-ccc605480fd7/mini.png)](https://insight.sensiolabs.com/projects/d8cc6035-69ad-477d-bd1a-ccc605480fd7)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require phar-io/manifest

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev phar-io/manifest

## Usage

```php
use PharIo\Manifest\ManifestLoader;
use PharIo\Manifest\ManifestSerializer;

$manifest = ManifestLoader::fromFile('manifest.xml');

var_dump($manifest);

echo (new ManifestSerializer)->serializeToString($manifest);
```
{
  "name": "phar-io/manifest",
  "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
  "license": "BSD-3-Clause",
  "authors": [
    {
      "name": "Arne Blankerts",
      "email": "arne@blankerts.de",
      "role": "Developer"
    },
    {
      "name": "Sebastian Heuer",
      "email": "sebastian@phpeople.de",
      "role": "Developer"
    },
    {
      "name": "Sebastian Bergmann",
      "email": "sebastian@phpunit.de",
      "role": "Developer"
    }
  ],
  "support": {
    "issues": "https://github.com/phar-io/manifest/issues"
  },
  "require": {
    "php": "^7.2 || ^8.0",
    "ext-dom": "*",
    "ext-phar": "*",
    "ext-xmlwriter": "*",
    "phar-io/version": "^3.0.1"
  },
  "autoload": {
    "classmap": [
      "src/"
    ]
  },
  "extra": {
    "branch-alias": {
        "dev-master": "2.0.x-dev"
    }
  }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class Email {
    /** @var string */
    private $email;

    public function __construct(string $email) {
        $this->ensureEmailIsValid($email);

        $this->email = $email;
    }

    public function asString(): string {
        return $this->email;
    }

    private function ensureEmailIsValid(string $url): void {
        if (\filter_var($url, \FILTER_VALIDATE_EMAIL) === false) {
            throw new InvalidEmailException;
        }
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\VersionConstraint;

class PhpVersionRequirement implements Requirement {
    /** @var VersionConstraint */
    private $versionConstraint;

    public function __construct(VersionConstraint $versionConstraint) {
        $this->versionConstraint = $versionConstraint;
    }

    public function getVersionConstraint(): VersionConstraint {
        return $this->versionConstraint;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class Application extends Type {
    public function isApplication(): bool {
        return true;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class RequirementCollectionIterator implements \Iterator {
    /** @var Requirement[] */
    private $requirements;

    /** @var int */
    private $position = 0;

    public function __construct(RequirementCollection $requirements) {
        $this->requirements = $requirements->getRequirements();
    }

    public function rewind(): void {
        $this->position = 0;
    }

    public function valid(): bool {
        return $this->position < \count($this->requirements);
    }

    public function key(): int {
        return $this->position;
    }

    public function current(): Requirement {
        return $this->requirements[$this->position];
    }

    public function next(): void {
        $this->position++;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class AuthorCollectionIterator implements \Iterator {
    /** @var Author[] */
    private $authors;

    /** @var int */
    private $position = 0;

    public function __construct(AuthorCollection $authors) {
        $this->authors = $authors->getAuthors();
    }

    public function rewind(): void {
        $this->position = 0;
    }

    public function valid(): bool {
        return $this->position < \count($this->authors);
    }

    public function key(): int {
        return $this->position;
    }

    public function current(): Author {
        return $this->authors[$this->position];
    }

    public function next(): void {
        $this->position++;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\VersionConstraint;

abstract class Type {
    public static function application(): Application {
        return new Application;
    }

    public static function library(): Library {
        return new Library;
    }

    public static function extension(ApplicationName $application, VersionConstraint $versionConstraint): Extension {
        return new Extension($application, $versionConstraint);
    }

    /** @psalm-assert-if-true Application $this */
    public function isApplication(): bool {
        return false;
    }

    /** @psalm-assert-if-true Library $this */
    public function isLibrary(): bool {
        return false;
    }

    /** @psalm-assert-if-true Extension $this */
    public function isExtension(): bool {
        return false;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class Library extends Type {
    public function isLibrary(): bool {
        return true;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ApplicationName {
    /** @var string */
    private $name;

    public function __construct(string $name) {
        $this->ensureValidFormat($name);
        $this->name = $name;
    }

    public function asString(): string {
        return $this->name;
    }

    public function isEqual(ApplicationName $name): bool {
        return $this->name === $name->name;
    }

    private function ensureValidFormat(string $name): void {
        if (!\preg_match('#\w/\w#', $name)) {
            throw new InvalidApplicationNameException(
                \sprintf('Format of name "%s" is not valid - expected: vendor/packagename', $name),
                InvalidApplicationNameException::InvalidFormat
            );
        }
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class PhpExtensionRequirement implements Requirement {
    /** @var string */
    private $extension;

    public function __construct(string $extension) {
        $this->extension = $extension;
    }

    public function asString(): string {
        return $this->extension;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\Version;

class Manifest {
    /** @var ApplicationName */
    private $name;

    /** @var Version */
    private $version;

    /** @var Type */
    private $type;

    /** @var CopyrightInformation */
    private $copyrightInformation;

    /** @var RequirementCollection */
    private $requirements;

    /** @var BundledComponentCollection */
    private $bundledComponents;

    public function __construct(ApplicationName $name, Version $version, Type $type, CopyrightInformation $copyrightInformation, RequirementCollection $requirements, BundledComponentCollection $bundledComponents) {
        $this->name                 = $name;
        $this->version              = $version;
        $this->type                 = $type;
        $this->copyrightInformation = $copyrightInformation;
        $this->requirements         = $requirements;
        $this->bundledComponents    = $bundledComponents;
    }

    public function getName(): ApplicationName {
        return $this->name;
    }

    public function getVersion(): Version {
        return $this->version;
    }

    public function getType(): Type {
        return $this->type;
    }

    public function getCopyrightInformation(): CopyrightInformation {
        return $this->copyrightInformation;
    }

    public function getRequirements(): RequirementCollection {
        return $this->requirements;
    }

    public function getBundledComponents(): BundledComponentCollection {
        return $this->bundledComponents;
    }

    public function isApplication(): bool {
        return $this->type->isApplication();
    }

    public function isLibrary(): bool {
        return $this->type->isLibrary();
    }

    public function isExtension(): bool {
        return $this->type->isExtension();
    }

    public function isExtensionFor(ApplicationName $application, Version $version = null): bool {
        if (!$this->isExtension()) {
            return false;
        }

        /** @var Extension $type */
        $type = $this->type;

        if ($version !== null) {
            return $type->isCompatibleWith($application, $version);
        }

        return $type->isExtensionFor($application);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class Url {
    /** @var string */
    private $url;

    public function __construct(string $url) {
        $this->ensureUrlIsValid($url);

        $this->url = $url;
    }

    public function asString(): string {
        return $this->url;
    }

    /**
     * @param string $url
     *
     * @throws InvalidUrlException
     */
    private function ensureUrlIsValid($url): void {
        if (\filter_var($url, \FILTER_VALIDATE_URL) === false) {
            throw new InvalidUrlException;
        }
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class RequirementCollection implements \Countable, \IteratorAggregate {
    /** @var Requirement[] */
    private $requirements = [];

    public function add(Requirement $requirement): void {
        $this->requirements[] = $requirement;
    }

    /**
     * @return Requirement[]
     */
    public function getRequirements(): array {
        return $this->requirements;
    }

    public function count(): int {
        return \count($this->requirements);
    }

    public function getIterator(): RequirementCollectionIterator {
        return new RequirementCollectionIterator($this);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class License {
    /** @var string */
    private $name;

    /** @var Url */
    private $url;

    public function __construct(string $name, Url $url) {
        $this->name = $name;
        $this->url  = $url;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getUrl(): Url {
        return $this->url;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class AuthorCollection implements \Countable, \IteratorAggregate {
    /** @var Author[] */
    private $authors = [];

    public function add(Author $author): void {
        $this->authors[] = $author;
    }

    /**
     * @return Author[]
     */
    public function getAuthors(): array {
        return $this->authors;
    }

    public function count(): int {
        return \count($this->authors);
    }

    public function getIterator(): AuthorCollectionIterator {
        return new AuthorCollectionIterator($this);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\Version;

class BundledComponent {
    /** @var string */
    private $name;

    /** @var Version */
    private $version;

    public function __construct(string $name, Version $version) {
        $this->name    = $name;
        $this->version = $version;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getVersion(): Version {
        return $this->version;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\Version;
use PharIo\Version\VersionConstraint;

class Extension extends Type {
    /** @var ApplicationName */
    private $application;

    /** @var VersionConstraint */
    private $versionConstraint;

    public function __construct(ApplicationName $application, VersionConstraint $versionConstraint) {
        $this->application       = $application;
        $this->versionConstraint = $versionConstraint;
    }

    public function getApplicationName(): ApplicationName {
        return $this->application;
    }

    public function getVersionConstraint(): VersionConstraint {
        return $this->versionConstraint;
    }

    public function isExtension(): bool {
        return true;
    }

    public function isExtensionFor(ApplicationName $name): bool {
        return $this->application->isEqual($name);
    }

    public function isCompatibleWith(ApplicationName $name, Version $version): bool {
        return $this->isExtensionFor($name) && $this->versionConstraint->complies($version);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class BundledComponentCollectionIterator implements \Iterator {
    /** @var BundledComponent[] */
    private $bundledComponents;

    /** @var int */
    private $position = 0;

    public function __construct(BundledComponentCollection $bundledComponents) {
        $this->bundledComponents = $bundledComponents->getBundledComponents();
    }

    public function rewind(): void {
        $this->position = 0;
    }

    public function valid(): bool {
        return $this->position < \count($this->bundledComponents);
    }

    public function key(): int {
        return $this->position;
    }

    public function current(): BundledComponent {
        return $this->bundledComponents[$this->position];
    }

    public function next(): void {
        $this->position++;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class CopyrightInformation {
    /** @var AuthorCollection */
    private $authors;

    /** @var License */
    private $license;

    public function __construct(AuthorCollection $authors, License $license) {
        $this->authors = $authors;
        $this->license = $license;
    }

    public function getAuthors(): AuthorCollection {
        return $this->authors;
    }

    public function getLicense(): License {
        return $this->license;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class Author {
    /** @var string */
    private $name;

    /** @var Email */
    private $email;

    public function __construct(string $name, Email $email) {
        $this->name  = $name;
        $this->email = $email;
    }

    public function asString(): string {
        return \sprintf(
            '%s <%s>',
            $this->name,
            $this->email->asString()
        );
    }

    public function getName(): string {
        return $this->name;
    }

    public function getEmail(): Email {
        return $this->email;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

interface Requirement {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class BundledComponentCollection implements \Countable, \IteratorAggregate {
    /** @var BundledComponent[] */
    private $bundledComponents = [];

    public function add(BundledComponent $bundledComponent): void {
        $this->bundledComponents[] = $bundledComponent;
    }

    /**
     * @return BundledComponent[]
     */
    public function getBundledComponents(): array {
        return $this->bundledComponents;
    }

    public function count(): int {
        return \count($this->bundledComponents);
    }

    public function getIterator(): BundledComponentCollectionIterator {
        return new BundledComponentCollectionIterator($this);
    }
}
<?php declare(strict_types = 1);
namespace PharIo\Manifest;

class ManifestLoaderException extends \Exception implements Exception {
}
<?php declare(strict_types = 1);
namespace PharIo\Manifest;

class ManifestDocumentException extends \RuntimeException implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class InvalidApplicationNameException extends \InvalidArgumentException implements Exception {
    public const InvalidFormat = 2;
}
<?php declare(strict_types = 1);
namespace PharIo\Manifest;

class ManifestDocumentMapperException extends \RuntimeException implements Exception {
}
<?php declare(strict_types = 1);
namespace PharIo\Manifest;

class ManifestElementException extends \RuntimeException implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class InvalidEmailException extends \InvalidArgumentException implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class InvalidUrlException extends \InvalidArgumentException implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use LibXMLError;

class ManifestDocumentLoadingException extends \Exception implements Exception {
    /** @var LibXMLError[] */
    private $libxmlErrors;

    /**
     * ManifestDocumentLoadingException constructor.
     *
     * @param LibXMLError[] $libxmlErrors
     */
    public function __construct(array $libxmlErrors) {
        $this->libxmlErrors = $libxmlErrors;
        $first              = $this->libxmlErrors[0];

        parent::__construct(
            \sprintf(
                '%s (Line: %d / Column: %d / File: %s)',
                $first->message,
                $first->line,
                $first->column,
                $first->file
            ),
            $first->code
        );
    }

    /**
     * @return LibXMLError[]
     */
    public function getLibxmlErrors(): array {
        return $this->libxmlErrors;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

interface Exception extends \Throwable {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ElementCollectionException extends \InvalidArgumentException implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ContainsElement extends ManifestElement {
    public function getName(): string {
        return $this->getAttributeValue('name');
    }

    public function getVersion(): string {
        return $this->getAttributeValue('version');
    }

    public function getType(): string {
        return $this->getAttributeValue('type');
    }

    public function getExtensionElement(): ExtensionElement {
        return new ExtensionElement(
            $this->getChildByName('extension')
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class LicenseElement extends ManifestElement {
    public function getType(): string {
        return $this->getAttributeValue('type');
    }

    public function getUrl(): string {
        return $this->getAttributeValue('url');
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ComponentElement extends ManifestElement {
    public function getName(): string {
        return $this->getAttributeValue('name');
    }

    public function getVersion(): string {
        return $this->getAttributeValue('version');
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class PhpElement extends ManifestElement {
    public function getVersion(): string {
        return $this->getAttributeValue('version');
    }

    public function hasExtElements(): bool {
        return $this->hasChild('ext');
    }

    public function getExtElements(): ExtElementCollection {
        return new ExtElementCollection(
            $this->getChildrenByName('ext')
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ExtElementCollection extends ElementCollection {
    public function current(): ExtElement {
        return new ExtElement(
            $this->getCurrentElement()
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class AuthorElement extends ManifestElement {
    public function getName(): string {
        return $this->getAttributeValue('name');
    }

    public function getEmail(): string {
        return $this->getAttributeValue('email');
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use DOMElement;
use DOMNodeList;

abstract class ElementCollection implements \Iterator {
    /** @var DOMElement[] */
    private $nodes = [];

    /** @var int */
    private $position;

    public function __construct(DOMNodeList $nodeList) {
        $this->position = 0;
        $this->importNodes($nodeList);
    }

    #[\ReturnTypeWillChange]
    abstract public function current();

    public function next(): void {
        $this->position++;
    }

    public function key(): int {
        return $this->position;
    }

    public function valid(): bool {
        return $this->position < \count($this->nodes);
    }

    public function rewind(): void {
        $this->position = 0;
    }

    protected function getCurrentElement(): DOMElement {
        return $this->nodes[$this->position];
    }

    private function importNodes(DOMNodeList $nodeList): void {
        foreach ($nodeList as $node) {
            if (!$node instanceof DOMElement) {
                throw new ElementCollectionException(
                    \sprintf('\DOMElement expected, got \%s', \get_class($node))
                );
            }

            $this->nodes[] = $node;
        }
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use DOMDocument;
use DOMElement;

class ManifestDocument {
    public const XMLNS = 'https://phar.io/xml/manifest/1.0';

    /** @var DOMDocument */
    private $dom;

    public static function fromFile(string $filename): ManifestDocument {
        if (!\file_exists($filename)) {
            throw new ManifestDocumentException(
                \sprintf('File "%s" not found', $filename)
            );
        }

        return self::fromString(
            \file_get_contents($filename)
        );
    }

    public static function fromString(string $xmlString): ManifestDocument {
        $prev = \libxml_use_internal_errors(true);
        \libxml_clear_errors();

        $dom = new DOMDocument();
        $dom->loadXML($xmlString);

        $errors = \libxml_get_errors();
        \libxml_use_internal_errors($prev);

        if (\count($errors) !== 0) {
            throw new ManifestDocumentLoadingException($errors);
        }

        return new self($dom);
    }

    private function __construct(DOMDocument $dom) {
        $this->ensureCorrectDocumentType($dom);

        $this->dom = $dom;
    }

    public function getContainsElement(): ContainsElement {
        return new ContainsElement(
            $this->fetchElementByName('contains')
        );
    }

    public function getCopyrightElement(): CopyrightElement {
        return new CopyrightElement(
            $this->fetchElementByName('copyright')
        );
    }

    public function getRequiresElement(): RequiresElement {
        return new RequiresElement(
            $this->fetchElementByName('requires')
        );
    }

    public function hasBundlesElement(): bool {
        return $this->dom->getElementsByTagNameNS(self::XMLNS, 'bundles')->length === 1;
    }

    public function getBundlesElement(): BundlesElement {
        return new BundlesElement(
            $this->fetchElementByName('bundles')
        );
    }

    private function ensureCorrectDocumentType(DOMDocument $dom): void {
        $root = $dom->documentElement;

        if ($root->localName !== 'phar' || $root->namespaceURI !== self::XMLNS) {
            throw new ManifestDocumentException('Not a phar.io manifest document');
        }
    }

    private function fetchElementByName(string $elementName): DOMElement {
        $element = $this->dom->getElementsByTagNameNS(self::XMLNS, $elementName)->item(0);

        if (!$element instanceof DOMElement) {
            throw new ManifestDocumentException(
                \sprintf('Element %s missing', $elementName)
            );
        }

        return $element;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class BundlesElement extends ManifestElement {
    public function getComponentElements(): ComponentElementCollection {
        return new ComponentElementCollection(
            $this->getChildrenByName('component')
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class AuthorElementCollection extends ElementCollection {
    public function current(): AuthorElement {
        return new AuthorElement(
            $this->getCurrentElement()
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ComponentElementCollection extends ElementCollection {
    public function current(): ComponentElement {
        return new ComponentElement(
            $this->getCurrentElement()
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class CopyrightElement extends ManifestElement {
    public function getAuthorElements(): AuthorElementCollection {
        return new AuthorElementCollection(
            $this->getChildrenByName('author')
        );
    }

    public function getLicenseElement(): LicenseElement {
        return new LicenseElement(
            $this->getChildByName('license')
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ExtElement extends ManifestElement {
    public function getName(): string {
        return $this->getAttributeValue('name');
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class RequiresElement extends ManifestElement {
    public function getPHPElement(): PhpElement {
        return new PhpElement(
            $this->getChildByName('php')
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ExtensionElement extends ManifestElement {
    public function getFor(): string {
        return $this->getAttributeValue('for');
    }

    public function getCompatible(): string {
        return $this->getAttributeValue('compatible');
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use DOMElement;
use DOMNodeList;

class ManifestElement {
    public const XMLNS = 'https://phar.io/xml/manifest/1.0';

    /** @var DOMElement */
    private $element;

    public function __construct(DOMElement $element) {
        $this->element = $element;
    }

    protected function getAttributeValue(string $name): string {
        if (!$this->element->hasAttribute($name)) {
            throw new ManifestElementException(
                \sprintf(
                    'Attribute %s not set on element %s',
                    $name,
                    $this->element->localName
                )
            );
        }

        return $this->element->getAttribute($name);
    }

    protected function getChildByName(string $elementName): DOMElement {
        $element = $this->element->getElementsByTagNameNS(self::XMLNS, $elementName)->item(0);

        if (!$element instanceof DOMElement) {
            throw new ManifestElementException(
                \sprintf('Element %s missing', $elementName)
            );
        }

        return $element;
    }

    protected function getChildrenByName(string $elementName): DOMNodeList {
        $elementList = $this->element->getElementsByTagNameNS(self::XMLNS, $elementName);

        if ($elementList->length === 0) {
            throw new ManifestElementException(
                \sprintf('Element(s) %s missing', $elementName)
            );
        }

        return $elementList;
    }

    protected function hasChild(string $elementName): bool {
        return $this->element->getElementsByTagNameNS(self::XMLNS, $elementName)->length !== 0;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\AnyVersionConstraint;
use PharIo\Version\Version;
use PharIo\Version\VersionConstraint;
use XMLWriter;

/** @psalm-suppress MissingConstructor */
class ManifestSerializer {
    /** @var XMLWriter */
    private $xmlWriter;

    public function serializeToFile(Manifest $manifest, string $filename): void {
        \file_put_contents(
            $filename,
            $this->serializeToString($manifest)
        );
    }

    public function serializeToString(Manifest $manifest): string {
        $this->startDocument();

        $this->addContains($manifest->getName(), $manifest->getVersion(), $manifest->getType());
        $this->addCopyright($manifest->getCopyrightInformation());
        $this->addRequirements($manifest->getRequirements());
        $this->addBundles($manifest->getBundledComponents());

        return $this->finishDocument();
    }

    private function startDocument(): void {
        $xmlWriter = new XMLWriter();
        $xmlWriter->openMemory();
        $xmlWriter->setIndent(true);
        $xmlWriter->setIndentString(\str_repeat(' ', 4));
        $xmlWriter->startDocument('1.0', 'UTF-8');
        $xmlWriter->startElement('phar');
        $xmlWriter->writeAttribute('xmlns', 'https://phar.io/xml/manifest/1.0');

        $this->xmlWriter = $xmlWriter;
    }

    private function finishDocument(): string {
        $this->xmlWriter->endElement();
        $this->xmlWriter->endDocument();

        return $this->xmlWriter->outputMemory();
    }

    private function addContains(ApplicationName $name, Version $version, Type $type): void {
        $this->xmlWriter->startElement('contains');
        $this->xmlWriter->writeAttribute('name', $name->asString());
        $this->xmlWriter->writeAttribute('version', $version->getVersionString());

        switch (true) {
            case $type->isApplication(): {
                $this->xmlWriter->writeAttribute('type', 'application');

                break;
            }

            case $type->isLibrary(): {
                $this->xmlWriter->writeAttribute('type', 'library');

                break;
            }

            case $type->isExtension(): {
                $this->xmlWriter->writeAttribute('type', 'extension');
                /* @var $type Extension */
                $this->addExtension(
                    $type->getApplicationName(),
                    $type->getVersionConstraint()
                );

                break;
            }

            default: {
                $this->xmlWriter->writeAttribute('type', 'custom');
            }
        }

        $this->xmlWriter->endElement();
    }

    private function addCopyright(CopyrightInformation $copyrightInformation): void {
        $this->xmlWriter->startElement('copyright');

        foreach ($copyrightInformation->getAuthors() as $author) {
            $this->xmlWriter->startElement('author');
            $this->xmlWriter->writeAttribute('name', $author->getName());
            $this->xmlWriter->writeAttribute('email', $author->getEmail()->asString());
            $this->xmlWriter->endElement();
        }

        $license = $copyrightInformation->getLicense();

        $this->xmlWriter->startElement('license');
        $this->xmlWriter->writeAttribute('type', $license->getName());
        $this->xmlWriter->writeAttribute('url', $license->getUrl()->asString());
        $this->xmlWriter->endElement();

        $this->xmlWriter->endElement();
    }

    private function addRequirements(RequirementCollection $requirementCollection): void {
        $phpRequirement = new AnyVersionConstraint();
        $extensions     = [];

        foreach ($requirementCollection as $requirement) {
            if ($requirement instanceof PhpVersionRequirement) {
                $phpRequirement = $requirement->getVersionConstraint();

                continue;
            }

            if ($requirement instanceof PhpExtensionRequirement) {
                $extensions[] = $requirement->asString();
            }
        }

        $this->xmlWriter->startElement('requires');
        $this->xmlWriter->startElement('php');
        $this->xmlWriter->writeAttribute('version', $phpRequirement->asString());

        foreach ($extensions as $extension) {
            $this->xmlWriter->startElement('ext');
            $this->xmlWriter->writeAttribute('name', $extension);
            $this->xmlWriter->endElement();
        }

        $this->xmlWriter->endElement();
        $this->xmlWriter->endElement();
    }

    private function addBundles(BundledComponentCollection $bundledComponentCollection): void {
        if (\count($bundledComponentCollection) === 0) {
            return;
        }
        $this->xmlWriter->startElement('bundles');

        foreach ($bundledComponentCollection as $bundledComponent) {
            $this->xmlWriter->startElement('component');
            $this->xmlWriter->writeAttribute('name', $bundledComponent->getName());
            $this->xmlWriter->writeAttribute('version', $bundledComponent->getVersion()->getVersionString());
            $this->xmlWriter->endElement();
        }

        $this->xmlWriter->endElement();
    }

    private function addExtension(ApplicationName $applicationName, VersionConstraint $versionConstraint): void {
        $this->xmlWriter->startElement('extension');
        $this->xmlWriter->writeAttribute('for', $applicationName->asString());
        $this->xmlWriter->writeAttribute('compatible', $versionConstraint->asString());
        $this->xmlWriter->endElement();
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

class ManifestLoader {
    public static function fromFile(string $filename): Manifest {
        try {
            return (new ManifestDocumentMapper())->map(
                ManifestDocument::fromFile($filename)
            );
        } catch (Exception $e) {
            throw new ManifestLoaderException(
                \sprintf('Loading %s failed.', $filename),
                (int)$e->getCode(),
                $e
            );
        }
    }

    public static function fromPhar(string $filename): Manifest {
        return self::fromFile('phar://' . $filename . '/manifest.xml');
    }

    public static function fromString(string $manifest): Manifest {
        try {
            return (new ManifestDocumentMapper())->map(
                ManifestDocument::fromString($manifest)
            );
        } catch (Exception $e) {
            throw new ManifestLoaderException(
                'Processing string failed',
                (int)$e->getCode(),
                $e
            );
        }
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Manifest.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Manifest;

use PharIo\Version\Exception as VersionException;
use PharIo\Version\Version;
use PharIo\Version\VersionConstraintParser;

class ManifestDocumentMapper {
    public function map(ManifestDocument $document): Manifest {
        try {
            $contains          = $document->getContainsElement();
            $type              = $this->mapType($contains);
            $copyright         = $this->mapCopyright($document->getCopyrightElement());
            $requirements      = $this->mapRequirements($document->getRequiresElement());
            $bundledComponents = $this->mapBundledComponents($document);

            return new Manifest(
                new ApplicationName($contains->getName()),
                new Version($contains->getVersion()),
                $type,
                $copyright,
                $requirements,
                $bundledComponents
            );
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException($e->getMessage(), (int)$e->getCode(), $e);
        } catch (Exception $e) {
            throw new ManifestDocumentMapperException($e->getMessage(), (int)$e->getCode(), $e);
        }
    }

    private function mapType(ContainsElement $contains): Type {
        switch ($contains->getType()) {
            case 'application':
                return Type::application();
            case 'library':
                return Type::library();
            case 'extension':
                return $this->mapExtension($contains->getExtensionElement());
        }

        throw new ManifestDocumentMapperException(
            \sprintf('Unsupported type %s', $contains->getType())
        );
    }

    private function mapCopyright(CopyrightElement $copyright): CopyrightInformation {
        $authors = new AuthorCollection();

        foreach ($copyright->getAuthorElements() as $authorElement) {
            $authors->add(
                new Author(
                    $authorElement->getName(),
                    new Email($authorElement->getEmail())
                )
            );
        }

        $licenseElement = $copyright->getLicenseElement();
        $license        = new License(
            $licenseElement->getType(),
            new Url($licenseElement->getUrl())
        );

        return new CopyrightInformation(
            $authors,
            $license
        );
    }

    private function mapRequirements(RequiresElement $requires): RequirementCollection {
        $collection = new RequirementCollection();
        $phpElement = $requires->getPHPElement();
        $parser     = new VersionConstraintParser;

        try {
            $versionConstraint = $parser->parse($phpElement->getVersion());
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException(
                \sprintf('Unsupported version constraint - %s', $e->getMessage()),
                (int)$e->getCode(),
                $e
            );
        }

        $collection->add(
            new PhpVersionRequirement(
                $versionConstraint
            )
        );

        if (!$phpElement->hasExtElements()) {
            return $collection;
        }

        foreach ($phpElement->getExtElements() as $extElement) {
            $collection->add(
                new PhpExtensionRequirement($extElement->getName())
            );
        }

        return $collection;
    }

    private function mapBundledComponents(ManifestDocument $document): BundledComponentCollection {
        $collection = new BundledComponentCollection();

        if (!$document->hasBundlesElement()) {
            return $collection;
        }

        foreach ($document->getBundlesElement()->getComponentElements() as $componentElement) {
            $collection->add(
                new BundledComponent(
                    $componentElement->getName(),
                    new Version(
                        $componentElement->getVersion()
                    )
                )
            );
        }

        return $collection;
    }

    private function mapExtension(ExtensionElement $extension): Extension {
        try {
            $versionConstraint = (new VersionConstraintParser)->parse($extension->getCompatible());

            return Type::extension(
                new ApplicationName($extension->getFor()),
                $versionConstraint
            );
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException(
                \sprintf('Unsupported version constraint - %s', $e->getMessage()),
                (int)$e->getCode(),
                $e
            );
        }
    }
}
Copyright (c) 2016-2017 Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de> and contributors
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 copyright holder nor the names of 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 HOLDER OR 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.

# Changelog

All notable changes to phar-io/version are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [3.2.1] - 2022-02-21

### Fixed

- Have ExactVersionConstraint honor build metadata (added in 3.2.0)


## [3.2.0] - 2022-02-21

### Added

- Build metadata is now supported and considered for equality checks only


## [3.1.1] - 2022-02-07

### Fixed

- [#28](https://github.com/phar-io/version/issues/28): `VersionConstraintParser` does not support logical OR represented by single pipe (|) (Thanks @llaville)


## [3.1.0] - 2021-02-23

### Changed

- Internal Refactoring
- More scalar types

### Added

- [#24](https://github.com/phar-io/version/issues/24): `Version::getOriginalString()` added (Thanks @addshore)
- Version constraints using the caret operator (`^`) now honor pre-1.0 releases, e.g. `^0.3` translates to `0.3.*`)
- Various integration tests for version constraint processing

### Fixed

- [#23](https://github.com/phar-io/version/pull/23): Tilde operator without patch level



## [3.0.4] - 14.12.2020

### Fixed 

- [#22](https://github.com/phar-io/version/pull/22): make dev suffix rank works for uppercase too

## [3.0.3] - 30.11.2020

### Added

- Comparator method `Version::equals()` added


## [3.0.2] - 27.06.2020

This release now supports PHP 7.2+ and PHP ^8.0. No other changes included.


## [3.0.1] - 09.05.2020

__Potential BC Break Notice:__
`Version::getVersionString()` no longer returns `v` prefixes in case the "input"
string contained one. These are not part of the semver specs
(see https://semver.org/#is-v123-a-semantic-version) and get stripped out.
As of Version 3.1.0 `Version::getOriginalString()` can be used to still
retrieve it as given.

### Changed

- Internal Refactoring
- More scalar types

### Fixed

- Fixed Constraint processing Regression for ^1.2  and ~1.2


## [3.0.0] - 05.05.2020

### Changed

- Require PHP 7.2+
- All code now uses strict mode
- Scalar types have been added as needed

### Added

- The technically invalid format using 'v' prefix ("v1.2.3") is now properly supported 


## [2.0.1] - 08.07.2018

### Fixed

- Versions without a pre-release suffix are now always considered greater 
than versions with a pre-release suffix. Example: `3.0.0 > 3.0.0-alpha.1`  


## [2.0.0] - 23.06.2018

Changes to public API:

- `PreReleaseSuffix::construct()`: optional parameter `$number` removed
- `PreReleaseSuffix::isGreaterThan()`: introduced
- `Version::hasPreReleaseSuffix()`: introduced

### Added

- [#11](https://github.com/phar-io/version/issues/11): Added support for pre-release version suffixes. Supported values are:
  - `dev`
  - `beta` (also abbreviated form `b`)
  - `rc`
  - `alpha` (also abbreviated form `a`)
  - `patch` (also abbreviated form `p`)

  All values can be followed by a number, e.g. `beta3`. 

  When comparing versions, the pre-release suffix is taken into account. Example:
`1.5.0 > 1.5.0-beta1 > 1.5.0-alpha3 > 1.5.0-alpha2 > 1.5.0-dev11`

### Changed

- reorganized the source directories

### Fixed

- [#10](https://github.com/phar-io/version/issues/10): Version numbers containing 
a numeric suffix as seen in Debian packages are now supported.  


[3.1.0]: https://github.com/phar-io/version/compare/3.0.4...3.1.0
[3.0.4]: https://github.com/phar-io/version/compare/3.0.3...3.0.4
[3.0.3]: https://github.com/phar-io/version/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/phar-io/version/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/phar-io/version/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/phar-io/version/compare/2.0.1...3.0.0
[2.0.1]: https://github.com/phar-io/version/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/phar-io/version/compare/1.0.1...2.0.0
# Version

Library for handling version information and constraints

[![Build Status](https://travis-ci.org/phar-io/version.svg?branch=master)](https://travis-ci.org/phar-io/version)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require phar-io/version

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev phar-io/version

## Version constraints

A Version constraint describes a range of versions or a discrete version number. The format of version numbers follows the schema of [semantic versioning](http://semver.org): `<major>.<minor>.<patch>`. A constraint might contain an operator that describes the range.

Beside the typical mathematical operators like `<=`, `>=`, there are two special operators:

*Caret operator*: `^1.0`
can be written as `>=1.0.0 <2.0.0` and read as »every Version within major version `1`«.

*Tilde operator*: `~1.0.0`
can be written as `>=1.0.0 <1.1.0` and read as »every version within minor version `1.1`. The behavior of tilde operator depends on whether a patch level version is provided or not. If no patch level is provided, tilde operator behaves like the caret operator: `~1.0` is identical to `^1.0`.

## Usage examples

Parsing version constraints and check discrete versions for compliance:

```php

use PharIo\Version\Version;
use PharIo\Version\VersionConstraintParser;

$parser = new VersionConstraintParser();
$caret_constraint = $parser->parse( '^7.0' );

$caret_constraint->complies( new Version( '7.0.17' ) ); // true
$caret_constraint->complies( new Version( '7.1.0' ) ); // true
$caret_constraint->complies( new Version( '6.4.34' ) ); // false

$tilde_constraint = $parser->parse( '~1.1.0' );

$tilde_constraint->complies( new Version( '1.1.4' ) ); // true
$tilde_constraint->complies( new Version( '1.2.0' ) ); // false
```

As of version 2.0.0, pre-release labels are supported and taken into account when comparing versions:

```php

$leftVersion = new PharIo\Version\Version('3.0.0-alpha.1');
$rightVersion = new PharIo\Version\Version('3.0.0-alpha.2');

$leftVersion->isGreaterThan($rightVersion); // false
$rightVersion->isGreaterThan($leftVersion); // true

``` 
{
  "name": "phar-io/version",
  "description": "Library for handling version information and constraints",
  "license": "BSD-3-Clause",
  "authors": [
    {
      "name": "Arne Blankerts",
      "email": "arne@blankerts.de",
      "role": "Developer"
    },
    {
      "name": "Sebastian Heuer",
      "email": "sebastian@phpeople.de",
      "role": "Developer"
    },
    {
      "name": "Sebastian Bergmann",
      "email": "sebastian@phpunit.de",
      "role": "Developer"
    }
  ],
  "support": {
    "issues": "https://github.com/phar-io/version/issues"
  },
  "require": {
    "php": "^7.2 || ^8.0"
  },
  "autoload": {
    "classmap": [
      "src/"
    ]
  }
}

<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class VersionConstraintParser {
    /**
     * @throws UnsupportedVersionConstraintException
     */
    public function parse(string $value): VersionConstraint {
        if (\strpos($value, '|') !== false) {
            return $this->handleOrGroup($value);
        }

        if (!\preg_match('/^[\^~*]?v?[\d.*]+(?:-.*)?$/i', $value)) {
            throw new UnsupportedVersionConstraintException(
                \sprintf('Version constraint %s is not supported.', $value)
            );
        }

        switch ($value[0]) {
            case '~':
                return $this->handleTildeOperator($value);
            case '^':
                return $this->handleCaretOperator($value);
        }

        $constraint = new VersionConstraintValue($value);

        if ($constraint->getMajor()->isAny()) {
            return new AnyVersionConstraint();
        }

        if ($constraint->getMinor()->isAny()) {
            return new SpecificMajorVersionConstraint(
                $constraint->getVersionString(),
                $constraint->getMajor()->getValue() ?? 0
            );
        }

        if ($constraint->getPatch()->isAny()) {
            return new SpecificMajorAndMinorVersionConstraint(
                $constraint->getVersionString(),
                $constraint->getMajor()->getValue() ?? 0,
                $constraint->getMinor()->getValue() ?? 0
            );
        }

        return new ExactVersionConstraint($constraint->getVersionString());
    }

    private function handleOrGroup(string $value): OrVersionConstraintGroup {
        $constraints = [];

        foreach (\preg_split('{\s*\|\|?\s*}', \trim($value)) as $groupSegment) {
            $constraints[] = $this->parse(\trim($groupSegment));
        }

        return new OrVersionConstraintGroup($value, $constraints);
    }

    private function handleTildeOperator(string $value): AndVersionConstraintGroup {
        $constraintValue = new VersionConstraintValue(\substr($value, 1));

        if ($constraintValue->getPatch()->isAny()) {
            return $this->handleCaretOperator($value);
        }

        $constraints = [
            new GreaterThanOrEqualToVersionConstraint(
                $value,
                new Version(\substr($value, 1))
            ),
            new SpecificMajorAndMinorVersionConstraint(
                $value,
                $constraintValue->getMajor()->getValue() ?? 0,
                $constraintValue->getMinor()->getValue() ?? 0
            )
        ];

        return new AndVersionConstraintGroup($value, $constraints);
    }

    private function handleCaretOperator(string $value): AndVersionConstraintGroup {
        $constraintValue = new VersionConstraintValue(\substr($value, 1));

        $constraints = [
            new GreaterThanOrEqualToVersionConstraint($value, new Version(\substr($value, 1)))
        ];

        if ($constraintValue->getMajor()->getValue() === 0) {
            $constraints[] = new SpecificMajorAndMinorVersionConstraint(
                $value,
                $constraintValue->getMajor()->getValue() ?? 0,
                $constraintValue->getMinor()->getValue() ?? 0
            );
        } else {
            $constraints[] = new SpecificMajorVersionConstraint(
                $value,
                $constraintValue->getMajor()->getValue() ?? 0
            );
        }

        return new AndVersionConstraintGroup(
            $value,
            $constraints
        );
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class AnyVersionConstraint implements VersionConstraint {
    public function complies(Version $version): bool {
        return true;
    }

    public function asString(): string {
        return '*';
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

abstract class AbstractVersionConstraint implements VersionConstraint {
    /** @var string */
    private $originalValue;

    public function __construct(string $originalValue) {
        $this->originalValue = $originalValue;
    }

    public function asString(): string {
        return $this->originalValue;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

interface VersionConstraint {
    public function complies(Version $version): bool;

    public function asString(): string;
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class GreaterThanOrEqualToVersionConstraint extends AbstractVersionConstraint {
    /** @var Version */
    private $minimalVersion;

    public function __construct(string $originalValue, Version $minimalVersion) {
        parent::__construct($originalValue);

        $this->minimalVersion = $minimalVersion;
    }

    public function complies(Version $version): bool {
        return $version->getVersionString() === $this->minimalVersion->getVersionString()
            || $version->isGreaterThan($this->minimalVersion);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class OrVersionConstraintGroup extends AbstractVersionConstraint {
    /** @var VersionConstraint[] */
    private $constraints = [];

    /**
     * @param string              $originalValue
     * @param VersionConstraint[] $constraints
     */
    public function __construct($originalValue, array $constraints) {
        parent::__construct($originalValue);

        $this->constraints = $constraints;
    }

    public function complies(Version $version): bool {
        foreach ($this->constraints as $constraint) {
            if ($constraint->complies($version)) {
                return true;
            }
        }

        return false;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class AndVersionConstraintGroup extends AbstractVersionConstraint {
    /** @var VersionConstraint[] */
    private $constraints = [];

    /**
     * @param VersionConstraint[] $constraints
     */
    public function __construct(string $originalValue, array $constraints) {
        parent::__construct($originalValue);

        $this->constraints = $constraints;
    }

    public function complies(Version $version): bool {
        foreach ($this->constraints as $constraint) {
            if (!$constraint->complies($version)) {
                return false;
            }
        }

        return true;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class ExactVersionConstraint extends AbstractVersionConstraint {
    public function complies(Version $version): bool {
        $other = $version->getVersionString();

        if ($version->hasBuildMetaData()) {
            $other .= '+' . $version->getBuildMetaData()->asString();
        }

        return $this->asString() === $other;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class SpecificMajorVersionConstraint extends AbstractVersionConstraint {
    /** @var int */
    private $major;

    public function __construct(string $originalValue, int $major) {
        parent::__construct($originalValue);

        $this->major = $major;
    }

    public function complies(Version $version): bool {
        return $version->getMajor()->getValue() === $this->major;
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class SpecificMajorAndMinorVersionConstraint extends AbstractVersionConstraint {
    /** @var int */
    private $major;

    /** @var int */
    private $minor;

    public function __construct(string $originalValue, int $major, int $minor) {
        parent::__construct($originalValue);

        $this->major = $major;
        $this->minor = $minor;
    }

    public function complies(Version $version): bool {
        if ($version->getMajor()->getValue() !== $this->major) {
            return false;
        }

        return $version->getMinor()->getValue() === $this->minor;
    }
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class VersionConstraintValue {
    /** @var VersionNumber */
    private $major;

    /** @var VersionNumber */
    private $minor;

    /** @var VersionNumber */
    private $patch;

    /** @var string */
    private $label = '';

    /** @var string */
    private $buildMetaData = '';

    /** @var string */
    private $versionString = '';

    public function __construct(string $versionString) {
        $this->versionString = $versionString;

        $this->parseVersion($versionString);
    }

    public function getLabel(): string {
        return $this->label;
    }

    public function getBuildMetaData(): string {
        return $this->buildMetaData;
    }

    public function getVersionString(): string {
        return $this->versionString;
    }

    public function getMajor(): VersionNumber {
        return $this->major;
    }

    public function getMinor(): VersionNumber {
        return $this->minor;
    }

    public function getPatch(): VersionNumber {
        return $this->patch;
    }

    private function parseVersion(string $versionString): void {
        $this->extractBuildMetaData($versionString);
        $this->extractLabel($versionString);
        $this->stripPotentialVPrefix($versionString);

        $versionSegments = \explode('.', $versionString);
        $this->major     = new VersionNumber(\is_numeric($versionSegments[0]) ? (int)$versionSegments[0] : null);

        $minorValue = isset($versionSegments[1]) && \is_numeric($versionSegments[1]) ? (int)$versionSegments[1] : null;
        $patchValue = isset($versionSegments[2]) && \is_numeric($versionSegments[2]) ? (int)$versionSegments[2] : null;

        $this->minor = new VersionNumber($minorValue);
        $this->patch = new VersionNumber($patchValue);
    }

    private function extractBuildMetaData(string &$versionString): void {
        if (\preg_match('/\+(.*)/', $versionString, $matches) === 1) {
            $this->buildMetaData = $matches[1];
            $versionString       = \str_replace($matches[0], '', $versionString);
        }
    }

    private function extractLabel(string &$versionString): void {
        if (\preg_match('/-(.*)/', $versionString, $matches) === 1) {
            $this->label   = $matches[1];
            $versionString = \str_replace($matches[0], '', $versionString);
        }
    }

    private function stripPotentialVPrefix(string &$versionString): void {
        if ($versionString[0] !== 'v') {
            return;
        }
        $versionString = \substr($versionString, 1);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class BuildMetaData {

    /** @var string */
    private $value;

    public function __construct(string $value) {
        $this->value = $value;
    }

    public function asString(): string {
        return $this->value;
    }

    public function equals(BuildMetaData $other): bool {
        return $this->asString() === $other->asString();
    }
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class InvalidVersionException extends \InvalidArgumentException implements Exception {
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class InvalidPreReleaseSuffixException extends \Exception implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

final class UnsupportedVersionConstraintException extends \RuntimeException implements Exception {
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class NoPreReleaseSuffixException extends \Exception implements Exception {
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class NoBuildMetaDataException extends \Exception implements Exception {
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

use Throwable;

interface Exception extends Throwable {
}
<?php declare(strict_types = 1);
namespace PharIo\Version;

class PreReleaseSuffix {
    private const valueScoreMap = [
        'dev'   => 0,
        'a'     => 1,
        'alpha' => 1,
        'b'     => 2,
        'beta'  => 2,
        'rc'    => 3,
        'p'     => 4,
        'pl'    => 4,
        'patch' => 4,
    ];

    /** @var string */
    private $value;

    /** @var int */
    private $valueScore;

    /** @var int */
    private $number = 0;

    /** @var string */
    private $full;

    /**
     * @throws InvalidPreReleaseSuffixException
     */
    public function __construct(string $value) {
        $this->parseValue($value);
    }

    public function asString(): string {
        return $this->full;
    }

    public function getValue(): string {
        return $this->value;
    }

    public function getNumber(): ?int {
        return $this->number;
    }

    public function isGreaterThan(PreReleaseSuffix $suffix): bool {
        if ($this->valueScore > $suffix->valueScore) {
            return true;
        }

        if ($this->valueScore < $suffix->valueScore) {
            return false;
        }

        return $this->getNumber() > $suffix->getNumber();
    }

    private function mapValueToScore(string $value): int {
        $value = \strtolower($value);

        return self::valueScoreMap[$value];
    }

    private function parseValue(string $value): void {
        $regex = '/-?((dev|beta|b|rc|alpha|a|patch|p|pl)\.?(\d*)).*$/i';

        if (\preg_match($regex, $value, $matches) !== 1) {
            throw new InvalidPreReleaseSuffixException(\sprintf('Invalid label %s', $value));
        }

        $this->full  = $matches[1];
        $this->value = $matches[2];

        if ($matches[3] !== '') {
            $this->number = (int)$matches[3];
        }

        $this->valueScore = $this->mapValueToScore($matches[2]);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class Version {
    /** @var string */
    private $originalVersionString;

    /** @var VersionNumber */
    private $major;

    /** @var VersionNumber */
    private $minor;

    /** @var VersionNumber */
    private $patch;

    /** @var null|PreReleaseSuffix */
    private $preReleaseSuffix;

    /** @var null|BuildMetaData */
    private $buildMetadata;

    public function __construct(string $versionString) {
        $this->ensureVersionStringIsValid($versionString);
        $this->originalVersionString = $versionString;
    }

    /**
     * @throws NoPreReleaseSuffixException
     */
    public function getPreReleaseSuffix(): PreReleaseSuffix {
        if ($this->preReleaseSuffix === null) {
            throw new NoPreReleaseSuffixException('No pre-release suffix set');
        }

        return $this->preReleaseSuffix;
    }

    public function getOriginalString(): string {
        return $this->originalVersionString;
    }

    public function getVersionString(): string {
        $str = \sprintf(
            '%d.%d.%d',
            $this->getMajor()->getValue() ?? 0,
            $this->getMinor()->getValue() ?? 0,
            $this->getPatch()->getValue() ?? 0
        );

        if (!$this->hasPreReleaseSuffix()) {
            return $str;
        }

        return $str . '-' . $this->getPreReleaseSuffix()->asString();
    }

    public function hasPreReleaseSuffix(): bool {
        return $this->preReleaseSuffix !== null;
    }

    public function equals(Version $other): bool {
        if ($this->getVersionString() !== $other->getVersionString()) {
            return false;
        }

        if ($this->hasBuildMetaData() !== $other->hasBuildMetaData()) {
            return false;
        }

        if ($this->hasBuildMetaData() && $other->hasBuildMetaData() &&
            !$this->getBuildMetaData()->equals($other->getBuildMetaData())) {
            return false;
        }

        return true;
    }

    public function isGreaterThan(Version $version): bool {
        if ($version->getMajor()->getValue() > $this->getMajor()->getValue()) {
            return false;
        }

        if ($version->getMajor()->getValue() < $this->getMajor()->getValue()) {
            return true;
        }

        if ($version->getMinor()->getValue() > $this->getMinor()->getValue()) {
            return false;
        }

        if ($version->getMinor()->getValue() < $this->getMinor()->getValue()) {
            return true;
        }

        if ($version->getPatch()->getValue() > $this->getPatch()->getValue()) {
            return false;
        }

        if ($version->getPatch()->getValue() < $this->getPatch()->getValue()) {
            return true;
        }

        if (!$version->hasPreReleaseSuffix() && !$this->hasPreReleaseSuffix()) {
            return false;
        }

        if ($version->hasPreReleaseSuffix() && !$this->hasPreReleaseSuffix()) {
            return true;
        }

        if (!$version->hasPreReleaseSuffix() && $this->hasPreReleaseSuffix()) {
            return false;
        }

        return $this->getPreReleaseSuffix()->isGreaterThan($version->getPreReleaseSuffix());
    }

    public function getMajor(): VersionNumber {
        return $this->major;
    }

    public function getMinor(): VersionNumber {
        return $this->minor;
    }

    public function getPatch(): VersionNumber {
        return $this->patch;
    }

    /**
     * @psalm-assert-if-true BuildMetaData $this->buildMetadata
     * @psalm-assert-if-true BuildMetaData $this->getBuildMetaData()
     */
    public function hasBuildMetaData(): bool {
        return $this->buildMetadata !== null;
    }

    /**
     * @throws NoBuildMetaDataException
     */
    public function getBuildMetaData(): BuildMetaData {
        if (!$this->hasBuildMetaData()) {
            throw new NoBuildMetaDataException('No build metadata set');
        }

        return $this->buildMetadata;
    }

    /**
     * @param string[] $matches
     *
     * @throws InvalidPreReleaseSuffixException
     */
    private function parseVersion(array $matches): void {
        $this->major = new VersionNumber((int)$matches['Major']);
        $this->minor = new VersionNumber((int)$matches['Minor']);
        $this->patch = isset($matches['Patch']) ? new VersionNumber((int)$matches['Patch']) : new VersionNumber(0);

        if (isset($matches['PreReleaseSuffix']) && $matches['PreReleaseSuffix'] !== '') {
            $this->preReleaseSuffix = new PreReleaseSuffix($matches['PreReleaseSuffix']);
        }

        if (isset($matches['BuildMetadata'])) {
            $this->buildMetadata = new BuildMetaData($matches['BuildMetadata']);
        }
    }

    /**
     * @param string $version
     *
     * @throws InvalidVersionException
     */
    private function ensureVersionStringIsValid($version): void {
        $regex = '/^v?
            (?P<Major>0|[1-9]\d*)
            \\.
            (?P<Minor>0|[1-9]\d*)
            (\\.
                (?P<Patch>0|[1-9]\d*)
            )?
            (?:
                -
                (?<PreReleaseSuffix>(?:(dev|beta|b|rc|alpha|a|patch|p|pl)\.?\d*))
            )?
            (?:
                \\+
                (?P<BuildMetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-@]+)*)
            )?
        $/xi';

        if (\preg_match($regex, $version, $matches) !== 1) {
            throw new InvalidVersionException(
                \sprintf("Version string '%s' does not follow SemVer semantics", $version)
            );
        }

        $this->parseVersion($matches);
    }
}
<?php declare(strict_types = 1);
/*
 * This file is part of PharIo\Version.
 *
 * (c) Arne Blankerts <arne@blankerts.de>, Sebastian Heuer <sebastian@phpeople.de>, Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PharIo\Version;

class VersionNumber {

    /** @var ?int */
    private $value;

    public function __construct(?int $value) {
        $this->value = $value;
    }

    public function isAny(): bool {
        return $this->value === null;
    }

    public function getValue(): ?int {
        return $this->value;
    }
}
Copyright (c) 2012 PHP Framework Interoperability Group

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
PSR Log
=======

This repository holds all interfaces/classes/traits related to
[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md).

Note that this is not a logger of its own. It is merely an interface that
describes a logger. See the specification for more details.

Installation
------------

```bash
composer require psr/log
```

Usage
-----

If you need a logger, you can use the interface like this:

```php
<?php

use Psr\Log\LoggerInterface;

class Foo
{
    private $logger;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    public function doSomething()
    {
        if ($this->logger) {
            $this->logger->info('Doing work');
        }
           
        try {
            $this->doSomethingElse();
        } catch (Exception $exception) {
            $this->logger->error('Oh no!', array('exception' => $exception));
        }

        // do something useful
    }
}
```

You can then pick one of the implementations of the interface to get a logger.

If you want to implement the interface, you can require this package and
implement `Psr\Log\LoggerInterface` in your code. Please read the
[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
for details.
vendor
<?php

namespace Psr\Log;

/**
 * Describes a logger-aware instance.
 */
interface LoggerAwareInterface
{
    /**
     * Sets a logger instance on the object.
     *
     * @param LoggerInterface $logger
     *
     * @return void
     */
    public function setLogger(LoggerInterface $logger);
}
<?php

namespace Psr\Log;

/**
 * Describes log levels.
 */
class LogLevel
{
    const EMERGENCY = 'emergency';
    const ALERT     = 'alert';
    const CRITICAL  = 'critical';
    const ERROR     = 'error';
    const WARNING   = 'warning';
    const NOTICE    = 'notice';
    const INFO      = 'info';
    const DEBUG     = 'debug';
}
<?php

namespace Psr\Log\Test;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use PHPUnit\Framework\TestCase;

/**
 * Provides a base test class for ensuring compliance with the LoggerInterface.
 *
 * Implementors can extend the class and implement abstract methods to run this
 * as part of their test suite.
 */
abstract class LoggerInterfaceTest extends TestCase
{
    /**
     * @return LoggerInterface
     */
    abstract public function getLogger();

    /**
     * This must return the log messages in order.
     *
     * The simple formatting of the messages is: "<LOG LEVEL> <MESSAGE>".
     *
     * Example ->error('Foo') would yield "error Foo".
     *
     * @return string[]
     */
    abstract public function getLogs();

    public function testImplements()
    {
        $this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger());
    }

    /**
     * @dataProvider provideLevelsAndMessages
     */
    public function testLogsAtAllLevels($level, $message)
    {
        $logger = $this->getLogger();
        $logger->{$level}($message, array('user' => 'Bob'));
        $logger->log($level, $message, array('user' => 'Bob'));

        $expected = array(
            $level.' message of level '.$level.' with context: Bob',
            $level.' message of level '.$level.' with context: Bob',
        );
        $this->assertEquals($expected, $this->getLogs());
    }

    public function provideLevelsAndMessages()
    {
        return array(
            LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
            LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
            LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
            LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
            LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
            LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
            LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
            LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
        );
    }

    /**
     * @expectedException \Psr\Log\InvalidArgumentException
     */
    public function testThrowsOnInvalidLevel()
    {
        $logger = $this->getLogger();
        $logger->log('invalid level', 'Foo');
    }

    public function testContextReplacement()
    {
        $logger = $this->getLogger();
        $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));

        $expected = array('info {Message {nothing} Bob Bar a}');
        $this->assertEquals($expected, $this->getLogs());
    }

    public function testObjectCastToString()
    {
        if (method_exists($this, 'createPartialMock')) {
            $dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString'));
        } else {
            $dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString'));
        }
        $dummy->expects($this->once())
            ->method('__toString')
            ->will($this->returnValue('DUMMY'));

        $this->getLogger()->warning($dummy);

        $expected = array('warning DUMMY');
        $this->assertEquals($expected, $this->getLogs());
    }

    public function testContextCanContainAnything()
    {
        $closed = fopen('php://memory', 'r');
        fclose($closed);

        $context = array(
            'bool' => true,
            'null' => null,
            'string' => 'Foo',
            'int' => 0,
            'float' => 0.5,
            'nested' => array('with object' => new DummyTest),
            'object' => new \DateTime,
            'resource' => fopen('php://memory', 'r'),
            'closed' => $closed,
        );

        $this->getLogger()->warning('Crazy context data', $context);

        $expected = array('warning Crazy context data');
        $this->assertEquals($expected, $this->getLogs());
    }

    public function testContextExceptionKeyCanBeExceptionOrOtherValues()
    {
        $logger = $this->getLogger();
        $logger->warning('Random message', array('exception' => 'oops'));
        $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));

        $expected = array(
            'warning Random message',
            'critical Uncaught Exception!'
        );
        $this->assertEquals($expected, $this->getLogs());
    }
}
<?php

namespace Psr\Log\Test;

use Psr\Log\AbstractLogger;

/**
 * Used for testing purposes.
 *
 * It records all records and gives you access to them for verification.
 *
 * @method bool hasEmergency($record)
 * @method bool hasAlert($record)
 * @method bool hasCritical($record)
 * @method bool hasError($record)
 * @method bool hasWarning($record)
 * @method bool hasNotice($record)
 * @method bool hasInfo($record)
 * @method bool hasDebug($record)
 *
 * @method bool hasEmergencyRecords()
 * @method bool hasAlertRecords()
 * @method bool hasCriticalRecords()
 * @method bool hasErrorRecords()
 * @method bool hasWarningRecords()
 * @method bool hasNoticeRecords()
 * @method bool hasInfoRecords()
 * @method bool hasDebugRecords()
 *
 * @method bool hasEmergencyThatContains($message)
 * @method bool hasAlertThatContains($message)
 * @method bool hasCriticalThatContains($message)
 * @method bool hasErrorThatContains($message)
 * @method bool hasWarningThatContains($message)
 * @method bool hasNoticeThatContains($message)
 * @method bool hasInfoThatContains($message)
 * @method bool hasDebugThatContains($message)
 *
 * @method bool hasEmergencyThatMatches($message)
 * @method bool hasAlertThatMatches($message)
 * @method bool hasCriticalThatMatches($message)
 * @method bool hasErrorThatMatches($message)
 * @method bool hasWarningThatMatches($message)
 * @method bool hasNoticeThatMatches($message)
 * @method bool hasInfoThatMatches($message)
 * @method bool hasDebugThatMatches($message)
 *
 * @method bool hasEmergencyThatPasses($message)
 * @method bool hasAlertThatPasses($message)
 * @method bool hasCriticalThatPasses($message)
 * @method bool hasErrorThatPasses($message)
 * @method bool hasWarningThatPasses($message)
 * @method bool hasNoticeThatPasses($message)
 * @method bool hasInfoThatPasses($message)
 * @method bool hasDebugThatPasses($message)
 */
class TestLogger extends AbstractLogger
{
    /**
     * @var array
     */
    public $records = [];

    public $recordsByLevel = [];

    /**
     * @inheritdoc
     */
    public function log($level, $message, array $context = [])
    {
        $record = [
            'level' => $level,
            'message' => $message,
            'context' => $context,
        ];

        $this->recordsByLevel[$record['level']][] = $record;
        $this->records[] = $record;
    }

    public function hasRecords($level)
    {
        return isset($this->recordsByLevel[$level]);
    }

    public function hasRecord($record, $level)
    {
        if (is_string($record)) {
            $record = ['message' => $record];
        }
        return $this->hasRecordThatPasses(function ($rec) use ($record) {
            if ($rec['message'] !== $record['message']) {
                return false;
            }
            if (isset($record['context']) && $rec['context'] !== $record['context']) {
                return false;
            }
            return true;
        }, $level);
    }

    public function hasRecordThatContains($message, $level)
    {
        return $this->hasRecordThatPasses(function ($rec) use ($message) {
            return strpos($rec['message'], $message) !== false;
        }, $level);
    }

    public function hasRecordThatMatches($regex, $level)
    {
        return $this->hasRecordThatPasses(function ($rec) use ($regex) {
            return preg_match($regex, $rec['message']) > 0;
        }, $level);
    }

    public function hasRecordThatPasses(callable $predicate, $level)
    {
        if (!isset($this->recordsByLevel[$level])) {
            return false;
        }
        foreach ($this->recordsByLevel[$level] as $i => $rec) {
            if (call_user_func($predicate, $rec, $i)) {
                return true;
            }
        }
        return false;
    }

    public function __call($method, $args)
    {
        if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
            $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3];
            $level = strtolower($matches[2]);
            if (method_exists($this, $genericMethod)) {
                $args[] = $level;
                return call_user_func_array([$this, $genericMethod], $args);
            }
        }
        throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()');
    }

    public function reset()
    {
        $this->records = [];
        $this->recordsByLevel = [];
    }
}
<?php

namespace Psr\Log\Test;

/**
 * This class is internal and does not follow the BC promise.
 *
 * Do NOT use this class in any way.
 *
 * @internal
 */
class DummyTest
{
    public function __toString()
    {
        return 'DummyTest';
    }
}
<?php

namespace Psr\Log;

/**
 * Basic Implementation of LoggerAwareInterface.
 */
trait LoggerAwareTrait
{
    /**
     * The logger instance.
     *
     * @var LoggerInterface|null
     */
    protected $logger;

    /**
     * Sets a logger.
     *
     * @param LoggerInterface $logger
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}
<?php

namespace Psr\Log;

class InvalidArgumentException extends \InvalidArgumentException
{
}
<?php

namespace Psr\Log;

/**
 * This Logger can be used to avoid conditional log calls.
 *
 * Logging should always be optional, and if no logger is provided to your
 * library creating a NullLogger instance to have something to throw logs at
 * is a good way to avoid littering your code with `if ($this->logger) { }`
 * blocks.
 */
class NullLogger extends AbstractLogger
{
    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string $message
     * @param array  $context
     *
     * @return void
     *
     * @throws \Psr\Log\InvalidArgumentException
     */
    public function log($level, $message, array $context = array())
    {
        // noop
    }
}
<?php

namespace Psr\Log;

/**
 * Describes a logger instance.
 *
 * The message MUST be a string or object implementing __toString().
 *
 * The message MAY contain placeholders in the form: {foo} where foo
 * will be replaced by the context data in key "foo".
 *
 * The context array can contain arbitrary data. The only assumption that
 * can be made by implementors is that if an Exception instance is given
 * to produce a stack trace, it MUST be in a key named "exception".
 *
 * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
 * for the full interface specification.
 */
interface LoggerInterface
{
    /**
     * System is unusable.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function emergency($message, array $context = array());

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function alert($message, array $context = array());

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function critical($message, array $context = array());

    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function error($message, array $context = array());

    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function warning($message, array $context = array());

    /**
     * Normal but significant events.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function notice($message, array $context = array());

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function info($message, array $context = array());

    /**
     * Detailed debug information.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function debug($message, array $context = array());

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed   $level
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     *
     * @throws \Psr\Log\InvalidArgumentException
     */
    public function log($level, $message, array $context = array());
}
<?php

namespace Psr\Log;

/**
 * This is a simple Logger trait that classes unable to extend AbstractLogger
 * (because they extend another class, etc) can include.
 *
 * It simply delegates all log-level-specific methods to the `log` method to
 * reduce boilerplate code that a simple Logger that does the same thing with
 * messages regardless of the error level has to implement.
 */
trait LoggerTrait
{
    /**
     * System is unusable.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function emergency($message, array $context = array())
    {
        $this->log(LogLevel::EMERGENCY, $message, $context);
    }

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function alert($message, array $context = array())
    {
        $this->log(LogLevel::ALERT, $message, $context);
    }

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function critical($message, array $context = array())
    {
        $this->log(LogLevel::CRITICAL, $message, $context);
    }

    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function error($message, array $context = array())
    {
        $this->log(LogLevel::ERROR, $message, $context);
    }

    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function warning($message, array $context = array())
    {
        $this->log(LogLevel::WARNING, $message, $context);
    }

    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function notice($message, array $context = array())
    {
        $this->log(LogLevel::NOTICE, $message, $context);
    }

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function info($message, array $context = array())
    {
        $this->log(LogLevel::INFO, $message, $context);
    }

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function debug($message, array $context = array())
    {
        $this->log(LogLevel::DEBUG, $message, $context);
    }

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string $message
     * @param array  $context
     *
     * @return void
     *
     * @throws \Psr\Log\InvalidArgumentException
     */
    abstract public function log($level, $message, array $context = array());
}
<?php

namespace Psr\Log;

/**
 * This is a simple Logger implementation that other Loggers can inherit from.
 *
 * It simply delegates all log-level-specific methods to the `log` method to
 * reduce boilerplate code that a simple Logger that does the same thing with
 * messages regardless of the error level has to implement.
 */
abstract class AbstractLogger implements LoggerInterface
{
    /**
     * System is unusable.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function emergency($message, array $context = array())
    {
        $this->log(LogLevel::EMERGENCY, $message, $context);
    }

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function alert($message, array $context = array())
    {
        $this->log(LogLevel::ALERT, $message, $context);
    }

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function critical($message, array $context = array())
    {
        $this->log(LogLevel::CRITICAL, $message, $context);
    }

    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function error($message, array $context = array())
    {
        $this->log(LogLevel::ERROR, $message, $context);
    }

    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function warning($message, array $context = array())
    {
        $this->log(LogLevel::WARNING, $message, $context);
    }

    /**
     * Normal but significant events.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function notice($message, array $context = array())
    {
        $this->log(LogLevel::NOTICE, $message, $context);
    }

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function info($message, array $context = array())
    {
        $this->log(LogLevel::INFO, $message, $context);
    }

    /**
     * Detailed debug information.
     *
     * @param string  $message
     * @param mixed[] $context
     *
     * @return void
     */
    public function debug($message, array $context = array())
    {
        $this->log(LogLevel::DEBUG, $message, $context);
    }
}
{
    "name": "psr/log",
    "description": "Common interface for logging libraries",
    "keywords": ["psr", "psr-3", "log"],
    "homepage": "https://github.com/php-fig/log",
    "license": "MIT",
    "authors": [
        {
            "name": "PHP-FIG",
            "homepage": "https://www.php-fig.org/"
        }
    ],
    "require": {
        "php": ">=5.3.0"
    },
    "autoload": {
        "psr-4": {
            "Psr\\Log\\": "Psr/Log/"
        }
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.1.x-dev"
        }
    }
}
<?php

$header = <<<EOF
This file is part of the Monolog package.

(c) Jordi Boggiano <j.boggiano@seld.be>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

$finder = Symfony\CS\Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Fixtures')
    ->in(__DIR__.'/src')
    ->in(__DIR__.'/tests')
;

return Symfony\CS\Config::create()
    ->setUsingCache(true)
    //->setUsingLinter(false)
    ->setRiskyAllowed(true)
    ->setRules(array(
        '@PSR2' => true,
        'binary_operator_spaces' => true,
        'blank_line_before_return' => true,
        'header_comment' => array('header' => $header),
        'include' => true,
        'long_array_syntax' => true,
        'method_separation' => true,
        'no_blank_lines_after_class_opening' => true,
        'no_blank_lines_after_phpdoc' => true,
        'no_blank_lines_between_uses' => true,
        'no_duplicate_semicolons' => true,
        'no_extra_consecutive_blank_lines' => true,
        'no_leading_import_slash' => true,
        'no_leading_namespace_whitespace' => true,
        'no_trailing_comma_in_singleline_array' => true,
        'no_unused_imports' => true,
        'object_operator_without_whitespace' => true,
        'phpdoc_align' => true,
        'phpdoc_indent' => true,
        'phpdoc_no_access' => true,
        'phpdoc_no_package' => true,
        'phpdoc_order' => true,
        'phpdoc_scalar' => true,
        'phpdoc_trim' => true,
        'phpdoc_type_to_var' => true,
        'psr0' => true,
        'single_blank_line_before_namespace' => true,
        'spaces_cast' => true,
        'standardize_not_equals' => true,
        'ternary_operator_spaces' => true,
        'trailing_comma_in_multiline_array' => true,
        'whitespacy_lines' => true,
    ))
    ->finder($finder)
;
### 1.18.2 (2016-04-02)

  * Fixed ElasticaFormatter to use more precise dates
  * Fixed GelfMessageFormatter sending too long messages

### 1.18.1 (2016-03-13)

  * Fixed SlackHandler bug where slack dropped messages randomly
  * Fixed RedisHandler issue when using with the PHPRedis extension
  * Fixed AmqpHandler content-type being incorrectly set when using with the AMQP extension
  * Fixed BrowserConsoleHandler regression

### 1.18.0 (2016-03-01)

  * Added optional reduction of timestamp precision via `Logger->useMicrosecondTimestamps(false)`, disabling it gets you a bit of performance boost but reduces the precision to the second instead of microsecond
  * Added possibility to skip some extra stack frames in IntrospectionProcessor if you have some library wrapping Monolog that is always adding frames
  * Added `Logger->withName` to clone a logger (keeping all handlers) with a new name
  * Added FluentdFormatter for the Fluentd unix socket protocol
  * Added HandlerWrapper base class to ease the creation of handler wrappers, just extend it and override as needed
  * Added support for replacing context sub-keys using `%context.*%` in LineFormatter
  * Added support for `payload` context value in RollbarHandler
  * Added setRelease to RavenHandler to describe the application version, sent with every log
  * Added support for `fingerprint` context value in RavenHandler
  * Fixed JSON encoding errors that would gobble up the whole log record, we now handle those more gracefully by dropping chars as needed
  * Fixed write timeouts in SocketHandler and derivatives, set to 10sec by default, lower it with `setWritingTimeout()`
  * Fixed PHP7 compatibility with regard to Exception/Throwable handling in a few places

### 1.17.2 (2015-10-14)

  * Fixed ErrorHandler compatibility with non-Monolog PSR-3 loggers
  * Fixed SlackHandler handling to use slack functionalities better
  * Fixed SwiftMailerHandler bug when sending multiple emails they all had the same id
  * Fixed 5.3 compatibility regression

### 1.17.1 (2015-08-31)

  * Fixed RollbarHandler triggering PHP notices

### 1.17.0 (2015-08-30)

  * Added support for `checksum` and `release` context/extra values in RavenHandler
  * Added better support for exceptions in RollbarHandler
  * Added UidProcessor::getUid
  * Added support for showing the resource type in NormalizedFormatter
  * Fixed IntrospectionProcessor triggering PHP notices

### 1.16.0 (2015-08-09)

  * Added IFTTTHandler to notify ifttt.com triggers
  * Added Logger::setHandlers() to allow setting/replacing all handlers
  * Added $capSize in RedisHandler to cap the log size
  * Fixed StreamHandler creation of directory to only trigger when the first log write happens
  * Fixed bug in the handling of curl failures
  * Fixed duplicate logging of fatal errors when both error and fatal error handlers are registered in monolog's ErrorHandler
  * Fixed missing fatal errors records with handlers that need to be closed to flush log records
  * Fixed TagProcessor::addTags support for associative arrays

### 1.15.0 (2015-07-12)

  * Added addTags and setTags methods to change a TagProcessor
  * Added automatic creation of directories if they are missing for a StreamHandler to open a log file
  * Added retry functionality to Loggly, Cube and Mandrill handlers so they retry up to 5 times in case of network failure
  * Fixed process exit code being incorrectly reset to 0 if ErrorHandler::registerExceptionHandler was used
  * Fixed HTML/JS escaping in BrowserConsoleHandler
  * Fixed JSON encoding errors being silently suppressed (PHP 5.5+ only)

### 1.14.0 (2015-06-19)

  * Added PHPConsoleHandler to send record to Chrome's PHP Console extension and library
  * Added support for objects implementing __toString in the NormalizerFormatter
  * Added support for HipChat's v2 API in HipChatHandler
  * Added Logger::setTimezone() to initialize the timezone monolog should use in case date.timezone isn't correct for your app
  * Added an option to send formatted message instead of the raw record on PushoverHandler via ->useFormattedMessage(true)
  * Fixed curl errors being silently suppressed

### 1.13.1 (2015-03-09)

  * Fixed regression in HipChat requiring a new token to be created

### 1.13.0 (2015-03-05)

  * Added Registry::hasLogger to check for the presence of a logger instance
  * Added context.user support to RavenHandler
  * Added HipChat API v2 support in the HipChatHandler
  * Added NativeMailerHandler::addParameter to pass params to the mail() process
  * Added context data to SlackHandler when $includeContextAndExtra is true
  * Added ability to customize the Swift_Message per-email in SwiftMailerHandler
  * Fixed SwiftMailerHandler to lazily create message instances if a callback is provided
  * Fixed serialization of INF and NaN values in Normalizer and LineFormatter

### 1.12.0 (2014-12-29)

  * Break: HandlerInterface::isHandling now receives a partial record containing only a level key. This was always the intent and does not break any Monolog handler but is strictly speaking a BC break and you should check if you relied on any other field in your own handlers.
  * Added PsrHandler to forward records to another PSR-3 logger
  * Added SamplingHandler to wrap around a handler and include only every Nth record
  * Added MongoDBFormatter to support better storage with MongoDBHandler (it must be enabled manually for now)
  * Added exception codes in the output of most formatters
  * Added LineFormatter::includeStacktraces to enable exception stack traces in logs (uses more than one line)
  * Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data
  * Added $host to HipChatHandler for users of private instances
  * Added $transactionName to NewRelicHandler and support for a transaction_name context value
  * Fixed MandrillHandler to avoid outputing API call responses
  * Fixed some non-standard behaviors in SyslogUdpHandler

### 1.11.0 (2014-09-30)

  * Break: The NewRelicHandler extra and context data are now prefixed with extra_ and context_ to avoid clashes. Watch out if you have scripts reading those from the API and rely on names
  * Added WhatFailureGroupHandler to suppress any exception coming from the wrapped handlers and avoid chain failures if a logging service fails
  * Added MandrillHandler to send emails via the Mandrillapp.com API
  * Added SlackHandler to log records to a Slack.com account
  * Added FleepHookHandler to log records to a Fleep.io account
  * Added LogglyHandler::addTag to allow adding tags to an existing handler
  * Added $ignoreEmptyContextAndExtra to LineFormatter to avoid empty [] at the end
  * Added $useLocking to StreamHandler and RotatingFileHandler to enable flock() while writing
  * Added support for PhpAmqpLib in the AmqpHandler
  * Added FingersCrossedHandler::clear and BufferHandler::clear to reset them between batches in long running jobs
  * Added support for adding extra fields from $_SERVER in the WebProcessor
  * Fixed support for non-string values in PrsLogMessageProcessor
  * Fixed SwiftMailer messages being sent with the wrong date in long running scripts
  * Fixed minor PHP 5.6 compatibility issues
  * Fixed BufferHandler::close being called twice

### 1.10.0 (2014-06-04)

  * Added Logger::getHandlers() and Logger::getProcessors() methods
  * Added $passthruLevel argument to FingersCrossedHandler to let it always pass some records through even if the trigger level is not reached
  * Added support for extra data in NewRelicHandler
  * Added $expandNewlines flag to the ErrorLogHandler to create multiple log entries when a message has multiple lines

### 1.9.1 (2014-04-24)

  * Fixed regression in RotatingFileHandler file permissions
  * Fixed initialization of the BufferHandler to make sure it gets flushed after receiving records
  * Fixed ChromePHPHandler and FirePHPHandler's activation strategies to be more conservative

### 1.9.0 (2014-04-20)

  * Added LogEntriesHandler to send logs to a LogEntries account
  * Added $filePermissions to tweak file mode on StreamHandler and RotatingFileHandler
  * Added $useFormatting flag to MemoryProcessor to make it send raw data in bytes
  * Added support for table formatting in FirePHPHandler via the table context key
  * Added a TagProcessor to add tags to records, and support for tags in RavenHandler
  * Added $appendNewline flag to the JsonFormatter to enable using it when logging to files
  * Added sound support to the PushoverHandler
  * Fixed multi-threading support in StreamHandler
  * Fixed empty headers issue when ChromePHPHandler received no records
  * Fixed default format of the ErrorLogHandler

### 1.8.0 (2014-03-23)

  * Break: the LineFormatter now strips newlines by default because this was a bug, set $allowInlineLineBreaks to true if you need them
  * Added BrowserConsoleHandler to send logs to any browser's console via console.log() injection in the output
  * Added FilterHandler to filter records and only allow those of a given list of levels through to the wrapped handler
  * Added FlowdockHandler to send logs to a Flowdock account
  * Added RollbarHandler to send logs to a Rollbar account
  * Added HtmlFormatter to send prettier log emails with colors for each log level
  * Added GitProcessor to add the current branch/commit to extra record data
  * Added a Monolog\Registry class to allow easier global access to pre-configured loggers
  * Added support for the new official graylog2/gelf-php lib for GelfHandler, upgrade if you can by replacing the mlehner/gelf-php requirement
  * Added support for HHVM
  * Added support for Loggly batch uploads
  * Added support for tweaking the content type and encoding in NativeMailerHandler
  * Added $skipClassesPartials to tweak the ignored classes in the IntrospectionProcessor
  * Fixed batch request support in GelfHandler

### 1.7.0 (2013-11-14)

  * Added ElasticSearchHandler to send logs to an Elastic Search server
  * Added DynamoDbHandler and ScalarFormatter to send logs to Amazon's Dynamo DB
  * Added SyslogUdpHandler to send logs to a remote syslogd server
  * Added LogglyHandler to send logs to a Loggly account
  * Added $level to IntrospectionProcessor so it only adds backtraces when needed
  * Added $version to LogstashFormatter to allow using the new v1 Logstash format
  * Added $appName to NewRelicHandler
  * Added configuration of Pushover notification retries/expiry
  * Added $maxColumnWidth to NativeMailerHandler to change the 70 chars default
  * Added chainability to most setters for all handlers
  * Fixed RavenHandler batch processing so it takes the message from the record with highest priority
  * Fixed HipChatHandler batch processing so it sends all messages at once
  * Fixed issues with eAccelerator
  * Fixed and improved many small things

### 1.6.0 (2013-07-29)

  * Added HipChatHandler to send logs to a HipChat chat room
  * Added ErrorLogHandler to send logs to PHP's error_log function
  * Added NewRelicHandler to send logs to NewRelic's service
  * Added Monolog\ErrorHandler helper class to register a Logger as exception/error/fatal handler
  * Added ChannelLevelActivationStrategy for the FingersCrossedHandler to customize levels by channel
  * Added stack traces output when normalizing exceptions (json output & co)
  * Added Monolog\Logger::API constant (currently 1)
  * Added support for ChromePHP's v4.0 extension
  * Added support for message priorities in PushoverHandler, see $highPriorityLevel and $emergencyLevel
  * Added support for sending messages to multiple users at once with the PushoverHandler
  * Fixed RavenHandler's support for batch sending of messages (when behind a Buffer or FingersCrossedHandler)
  * Fixed normalization of Traversables with very large data sets, only the first 1000 items are shown now
  * Fixed issue in RotatingFileHandler when an open_basedir restriction is active
  * Fixed minor issues in RavenHandler and bumped the API to Raven 0.5.0
  * Fixed SyslogHandler issue when many were used concurrently with different facilities

### 1.5.0 (2013-04-23)

  * Added ProcessIdProcessor to inject the PID in log records
  * Added UidProcessor to inject a unique identifier to all log records of one request/run
  * Added support for previous exceptions in the LineFormatter exception serialization
  * Added Monolog\Logger::getLevels() to get all available levels
  * Fixed ChromePHPHandler so it avoids sending headers larger than Chrome can handle

### 1.4.1 (2013-04-01)

  * Fixed exception formatting in the LineFormatter to be more minimalistic
  * Fixed RavenHandler's handling of context/extra data, requires Raven client >0.1.0
  * Fixed log rotation in RotatingFileHandler to work with long running scripts spanning multiple days
  * Fixed WebProcessor array access so it checks for data presence
  * Fixed Buffer, Group and FingersCrossed handlers to make use of their processors

### 1.4.0 (2013-02-13)

  * Added RedisHandler to log to Redis via the Predis library or the phpredis extension
  * Added ZendMonitorHandler to log to the Zend Server monitor
  * Added the possibility to pass arrays of handlers and processors directly in the Logger constructor
  * Added `$useSSL` option to the PushoverHandler which is enabled by default
  * Fixed ChromePHPHandler and FirePHPHandler issue when multiple instances are used simultaneously
  * Fixed header injection capability in the NativeMailHandler

### 1.3.1 (2013-01-11)

  * Fixed LogstashFormatter to be usable with stream handlers
  * Fixed GelfMessageFormatter levels on Windows

### 1.3.0 (2013-01-08)

  * Added PSR-3 compliance, the `Monolog\Logger` class is now an instance of `Psr\Log\LoggerInterface`
  * Added PsrLogMessageProcessor that you can selectively enable for full PSR-3 compliance
  * Added LogstashFormatter (combine with SocketHandler or StreamHandler to send logs to Logstash)
  * Added PushoverHandler to send mobile notifications
  * Added CouchDBHandler and DoctrineCouchDBHandler
  * Added RavenHandler to send data to Sentry servers
  * Added support for the new MongoClient class in MongoDBHandler
  * Added microsecond precision to log records' timestamps
  * Added `$flushOnOverflow` param to BufferHandler to flush by batches instead of losing
    the oldest entries
  * Fixed normalization of objects with cyclic references

### 1.2.1 (2012-08-29)

  * Added new $logopts arg to SyslogHandler to provide custom openlog options
  * Fixed fatal error in SyslogHandler

### 1.2.0 (2012-08-18)

  * Added AmqpHandler (for use with AMQP servers)
  * Added CubeHandler
  * Added NativeMailerHandler::addHeader() to send custom headers in mails
  * Added the possibility to specify more than one recipient in NativeMailerHandler
  * Added the possibility to specify float timeouts in SocketHandler
  * Added NOTICE and EMERGENCY levels to conform with RFC 5424
  * Fixed the log records to use the php default timezone instead of UTC
  * Fixed BufferHandler not being flushed properly on PHP fatal errors
  * Fixed normalization of exotic resource types
  * Fixed the default format of the SyslogHandler to avoid duplicating datetimes in syslog

### 1.1.0 (2012-04-23)

  * Added Monolog\Logger::isHandling() to check if a handler will
    handle the given log level
  * Added ChromePHPHandler
  * Added MongoDBHandler
  * Added GelfHandler (for use with Graylog2 servers)
  * Added SocketHandler (for use with syslog-ng for example)
  * Added NormalizerFormatter
  * Added the possibility to change the activation strategy of the FingersCrossedHandler
  * Added possibility to show microseconds in logs
  * Added `server` and `referer` to WebProcessor output

### 1.0.2 (2011-10-24)

  * Fixed bug in IE with large response headers and FirePHPHandler

### 1.0.1 (2011-08-25)

  * Added MemoryPeakUsageProcessor and MemoryUsageProcessor
  * Added Monolog\Logger::getName() to get a logger's channel name

### 1.0.0 (2011-07-06)

  * Added IntrospectionProcessor to get info from where the logger was called
  * Fixed WebProcessor in CLI

### 1.0.0-RC1 (2011-07-01)

  * Initial release
Copyright (c) 2011-2016 Jordi Boggiano

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
### 1.27.1 (2022-06-09)

  * Fixed MandrillHandler support for SwiftMailer 6 (#1676)
  * Fixed StreamHandler chunk size (backport from #1552)

### 1.27.0 (2022-03-13)

  * Added $maxDepth / setMaxDepth to NormalizerFormatter / JsonFormatter to configure the maximum depth if the default of 9 does not work for you (#1633)

### 1.26.1 (2021-05-28)

  * Fixed PHP 8.1 deprecation warning

### 1.26.0 (2020-12-14)

  * Added $dateFormat and $removeUsedContextFields arguments to PsrLogMessageProcessor (backport from 2.x)

### 1.25.5 (2020-07-23)

  * Fixed array access on null in RavenHandler
  * Fixed unique_id in WebProcessor not being disableable

### 1.25.4 (2020-05-22)

  * Fixed GitProcessor type error when there is no git repo present
  * Fixed normalization of SoapFault objects containing deeply nested objects as "detail"
  * Fixed support for relative paths in RotatingFileHandler

### 1.25.3 (2019-12-20)

  * Fixed formatting of resources in JsonFormatter
  * Fixed RedisHandler failing to use MULTI properly when passed a proxied Redis instance (e.g. in Symfony with lazy services)
  * Fixed FilterHandler triggering a notice when handleBatch was filtering all records passed to it
  * Fixed Turkish locale messing up the conversion of level names to their constant values

### 1.25.2 (2019-11-13)

  * Fixed normalization of Traversables to avoid traversing them as not all of them are rewindable
  * Fixed setFormatter/getFormatter to forward to the nested handler in FilterHandler, FingersCrossedHandler, BufferHandler and SamplingHandler
  * Fixed BrowserConsoleHandler formatting when using multiple styles
  * Fixed normalization of exception codes to be always integers even for PDOException which have them as numeric strings
  * Fixed normalization of SoapFault objects containing non-strings as "detail"
  * Fixed json encoding across all handlers to always attempt recovery of non-UTF-8 strings instead of failing the whole encoding

### 1.25.1 (2019-09-06)

  * Fixed forward-compatible interfaces to be compatible with Monolog 1.x too.

### 1.25.0 (2019-09-06)

  * Deprecated SlackbotHandler, use SlackWebhookHandler or SlackHandler instead
  * Deprecated RavenHandler, use sentry/sentry 2.x and their Sentry\Monolog\Handler instead
  * Deprecated HipChatHandler, migrate to Slack and use SlackWebhookHandler or SlackHandler instead
  * Added forward-compatible interfaces and traits FormattableHandlerInterface, FormattableHandlerTrait, ProcessableHandlerInterface, ProcessableHandlerTrait. If you use modern PHP and want to make code compatible with Monolog 1 and 2 this can help. You will have to require at least Monolog 1.25 though.
  * Added support for RFC3164 (outdated BSD syslog protocol) to SyslogUdpHandler
  * Fixed issue in GroupHandler and WhatFailureGroupHandler where setting multiple processors would duplicate records
  * Fixed issue in SignalHandler restarting syscalls functionality
  * Fixed normalizers handling of exception backtraces to avoid serializing arguments in some cases
  * Fixed ZendMonitorHandler to work with the latest Zend Server versions
  * Fixed ChromePHPHandler to avoid sending more data than latest Chrome versions allow in headers (4KB down from 256KB).

### 1.24.0 (2018-11-05)

  * BC Notice: If you are extending any of the Monolog's Formatters' `normalize` method, make sure you add the new `$depth = 0` argument to your function signature to avoid strict PHP warnings.
  * Added a `ResettableInterface` in order to reset/reset/clear/flush handlers and processors
  * Added a `ProcessorInterface` as an optional way to label a class as being a processor (mostly useful for autowiring dependency containers)
  * Added a way to log signals being received using Monolog\SignalHandler
  * Added ability to customize error handling at the Logger level using Logger::setExceptionHandler
  * Added InsightOpsHandler to migrate users of the LogEntriesHandler
  * Added protection to NormalizerHandler against circular and very deep structures, it now stops normalizing at a depth of 9
  * Added capture of stack traces to ErrorHandler when logging PHP errors
  * Added RavenHandler support for a `contexts` context or extra key to forward that to Sentry's contexts
  * Added forwarding of context info to FluentdFormatter
  * Added SocketHandler::setChunkSize to override the default chunk size in case you must send large log lines to rsyslog for example
  * Added ability to extend/override BrowserConsoleHandler
  * Added SlackWebhookHandler::getWebhookUrl and SlackHandler::getToken to enable class extensibility
  * Added SwiftMailerHandler::getSubjectFormatter to enable class extensibility
  * Dropped official support for HHVM in test builds
  * Fixed normalization of exception traces when call_user_func is used to avoid serializing objects and the data they contain
  * Fixed naming of fields in Slack handler, all field names are now capitalized in all cases
  * Fixed HipChatHandler bug where slack dropped messages randomly
  * Fixed normalization of objects in Slack handlers
  * Fixed support for PHP7's Throwable in NewRelicHandler
  * Fixed race bug when StreamHandler sometimes incorrectly reported it failed to create a directory
  * Fixed table row styling issues in HtmlFormatter
  * Fixed RavenHandler dropping the message when logging exception
  * Fixed WhatFailureGroupHandler skipping processors when using handleBatch
    and implement it where possible
  * Fixed display of anonymous class names

### 1.23.0 (2017-06-19)

  * Improved SyslogUdpHandler's support for RFC5424 and added optional `$ident` argument
  * Fixed GelfHandler truncation to be per field and not per message
  * Fixed compatibility issue with PHP <5.3.6
  * Fixed support for headless Chrome in ChromePHPHandler
  * Fixed support for latest Aws SDK in DynamoDbHandler
  * Fixed support for SwiftMailer 6.0+ in SwiftMailerHandler

### 1.22.1 (2017-03-13)

  * Fixed lots of minor issues in the new Slack integrations
  * Fixed support for allowInlineLineBreaks in LineFormatter when formatting exception backtraces

### 1.22.0 (2016-11-26)

  * Added SlackbotHandler and SlackWebhookHandler to set up Slack integration more easily
  * Added MercurialProcessor to add mercurial revision and branch names to log records
  * Added support for AWS SDK v3 in DynamoDbHandler
  * Fixed fatal errors occuring when normalizing generators that have been fully consumed
  * Fixed RollbarHandler to include a level (rollbar level), monolog_level (original name), channel and datetime (unix)
  * Fixed RollbarHandler not flushing records automatically, calling close() explicitly is not necessary anymore
  * Fixed SyslogUdpHandler to avoid sending empty frames
  * Fixed a few PHP 7.0 and 7.1 compatibility issues

### 1.21.0 (2016-07-29)

  * Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues
  * Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order
  * Added ability to format the main line of text the SlackHandler sends by explictly setting a formatter on the handler
  * Added information about SoapFault instances in NormalizerFormatter
  * Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level

### 1.20.0 (2016-07-02)

  * Added FingersCrossedHandler::activate() to manually trigger the handler regardless of the activation policy
  * Added StreamHandler::getUrl to retrieve the stream's URL
  * Added ability to override addRow/addTitle in HtmlFormatter
  * Added the $context to context information when the ErrorHandler handles a regular php error
  * Deprecated RotatingFileHandler::setFilenameFormat to only support 3 formats: Y, Y-m and Y-m-d
  * Fixed WhatFailureGroupHandler to work with PHP7 throwables
  * Fixed a few minor bugs

### 1.19.0 (2016-04-12)

  * Break: StreamHandler will not close streams automatically that it does not own. If you pass in a stream (not a path/url), then it will not close it for you. You can retrieve those using getStream() if needed
  * Added DeduplicationHandler to remove duplicate records from notifications across multiple requests, useful for email or other notifications on errors
  * Added ability to use `%message%` and other LineFormatter replacements in the subject line of emails sent with NativeMailHandler and SwiftMailerHandler
  * Fixed HipChatHandler handling of long messages

### 1.18.2 (2016-04-02)

  * Fixed ElasticaFormatter to use more precise dates
  * Fixed GelfMessageFormatter sending too long messages

### 1.18.1 (2016-03-13)

  * Fixed SlackHandler bug where slack dropped messages randomly
  * Fixed RedisHandler issue when using with the PHPRedis extension
  * Fixed AmqpHandler content-type being incorrectly set when using with the AMQP extension
  * Fixed BrowserConsoleHandler regression

### 1.18.0 (2016-03-01)

  * Added optional reduction of timestamp precision via `Logger->useMicrosecondTimestamps(false)`, disabling it gets you a bit of performance boost but reduces the precision to the second instead of microsecond
  * Added possibility to skip some extra stack frames in IntrospectionProcessor if you have some library wrapping Monolog that is always adding frames
  * Added `Logger->withName` to clone a logger (keeping all handlers) with a new name
  * Added FluentdFormatter for the Fluentd unix socket protocol
  * Added HandlerWrapper base class to ease the creation of handler wrappers, just extend it and override as needed
  * Added support for replacing context sub-keys using `%context.*%` in LineFormatter
  * Added support for `payload` context value in RollbarHandler
  * Added setRelease to RavenHandler to describe the application version, sent with every log
  * Added support for `fingerprint` context value in RavenHandler
  * Fixed JSON encoding errors that would gobble up the whole log record, we now handle those more gracefully by dropping chars as needed
  * Fixed write timeouts in SocketHandler and derivatives, set to 10sec by default, lower it with `setWritingTimeout()`
  * Fixed PHP7 compatibility with regard to Exception/Throwable handling in a few places

### 1.17.2 (2015-10-14)

  * Fixed ErrorHandler compatibility with non-Monolog PSR-3 loggers
  * Fixed SlackHandler handling to use slack functionalities better
  * Fixed SwiftMailerHandler bug when sending multiple emails they all had the same id
  * Fixed 5.3 compatibility regression

### 1.17.1 (2015-08-31)

  * Fixed RollbarHandler triggering PHP notices

### 1.17.0 (2015-08-30)

  * Added support for `checksum` and `release` context/extra values in RavenHandler
  * Added better support for exceptions in RollbarHandler
  * Added UidProcessor::getUid
  * Added support for showing the resource type in NormalizedFormatter
  * Fixed IntrospectionProcessor triggering PHP notices

### 1.16.0 (2015-08-09)

  * Added IFTTTHandler to notify ifttt.com triggers
  * Added Logger::setHandlers() to allow setting/replacing all handlers
  * Added $capSize in RedisHandler to cap the log size
  * Fixed StreamHandler creation of directory to only trigger when the first log write happens
  * Fixed bug in the handling of curl failures
  * Fixed duplicate logging of fatal errors when both error and fatal error handlers are registered in monolog's ErrorHandler
  * Fixed missing fatal errors records with handlers that need to be closed to flush log records
  * Fixed TagProcessor::addTags support for associative arrays

### 1.15.0 (2015-07-12)

  * Added addTags and setTags methods to change a TagProcessor
  * Added automatic creation of directories if they are missing for a StreamHandler to open a log file
  * Added retry functionality to Loggly, Cube and Mandrill handlers so they retry up to 5 times in case of network failure
  * Fixed process exit code being incorrectly reset to 0 if ErrorHandler::registerExceptionHandler was used
  * Fixed HTML/JS escaping in BrowserConsoleHandler
  * Fixed JSON encoding errors being silently suppressed (PHP 5.5+ only)

### 1.14.0 (2015-06-19)

  * Added PHPConsoleHandler to send record to Chrome's PHP Console extension and library
  * Added support for objects implementing __toString in the NormalizerFormatter
  * Added support for HipChat's v2 API in HipChatHandler
  * Added Logger::setTimezone() to initialize the timezone monolog should use in case date.timezone isn't correct for your app
  * Added an option to send formatted message instead of the raw record on PushoverHandler via ->useFormattedMessage(true)
  * Fixed curl errors being silently suppressed

### 1.13.1 (2015-03-09)

  * Fixed regression in HipChat requiring a new token to be created

### 1.13.0 (2015-03-05)

  * Added Registry::hasLogger to check for the presence of a logger instance
  * Added context.user support to RavenHandler
  * Added HipChat API v2 support in the HipChatHandler
  * Added NativeMailerHandler::addParameter to pass params to the mail() process
  * Added context data to SlackHandler when $includeContextAndExtra is true
  * Added ability to customize the Swift_Message per-email in SwiftMailerHandler
  * Fixed SwiftMailerHandler to lazily create message instances if a callback is provided
  * Fixed serialization of INF and NaN values in Normalizer and LineFormatter

### 1.12.0 (2014-12-29)

  * Break: HandlerInterface::isHandling now receives a partial record containing only a level key. This was always the intent and does not break any Monolog handler but is strictly speaking a BC break and you should check if you relied on any other field in your own handlers.
  * Added PsrHandler to forward records to another PSR-3 logger
  * Added SamplingHandler to wrap around a handler and include only every Nth record
  * Added MongoDBFormatter to support better storage with MongoDBHandler (it must be enabled manually for now)
  * Added exception codes in the output of most formatters
  * Added LineFormatter::includeStacktraces to enable exception stack traces in logs (uses more than one line)
  * Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data
  * Added $host to HipChatHandler for users of private instances
  * Added $transactionName to NewRelicHandler and support for a transaction_name context value
  * Fixed MandrillHandler to avoid outputing API call responses
  * Fixed some non-standard behaviors in SyslogUdpHandler

### 1.11.0 (2014-09-30)

  * Break: The NewRelicHandler extra and context data are now prefixed with extra_ and context_ to avoid clashes. Watch out if you have scripts reading those from the API and rely on names
  * Added WhatFailureGroupHandler to suppress any exception coming from the wrapped handlers and avoid chain failures if a logging service fails
  * Added MandrillHandler to send emails via the Mandrillapp.com API
  * Added SlackHandler to log records to a Slack.com account
  * Added FleepHookHandler to log records to a Fleep.io account
  * Added LogglyHandler::addTag to allow adding tags to an existing handler
  * Added $ignoreEmptyContextAndExtra to LineFormatter to avoid empty [] at the end
  * Added $useLocking to StreamHandler and RotatingFileHandler to enable flock() while writing
  * Added support for PhpAmqpLib in the AmqpHandler
  * Added FingersCrossedHandler::clear and BufferHandler::clear to reset them between batches in long running jobs
  * Added support for adding extra fields from $_SERVER in the WebProcessor
  * Fixed support for non-string values in PrsLogMessageProcessor
  * Fixed SwiftMailer messages being sent with the wrong date in long running scripts
  * Fixed minor PHP 5.6 compatibility issues
  * Fixed BufferHandler::close being called twice

### 1.10.0 (2014-06-04)

  * Added Logger::getHandlers() and Logger::getProcessors() methods
  * Added $passthruLevel argument to FingersCrossedHandler to let it always pass some records through even if the trigger level is not reached
  * Added support for extra data in NewRelicHandler
  * Added $expandNewlines flag to the ErrorLogHandler to create multiple log entries when a message has multiple lines

### 1.9.1 (2014-04-24)

  * Fixed regression in RotatingFileHandler file permissions
  * Fixed initialization of the BufferHandler to make sure it gets flushed after receiving records
  * Fixed ChromePHPHandler and FirePHPHandler's activation strategies to be more conservative

### 1.9.0 (2014-04-20)

  * Added LogEntriesHandler to send logs to a LogEntries account
  * Added $filePermissions to tweak file mode on StreamHandler and RotatingFileHandler
  * Added $useFormatting flag to MemoryProcessor to make it send raw data in bytes
  * Added support for table formatting in FirePHPHandler via the table context key
  * Added a TagProcessor to add tags to records, and support for tags in RavenHandler
  * Added $appendNewline flag to the JsonFormatter to enable using it when logging to files
  * Added sound support to the PushoverHandler
  * Fixed multi-threading support in StreamHandler
  * Fixed empty headers issue when ChromePHPHandler received no records
  * Fixed default format of the ErrorLogHandler

### 1.8.0 (2014-03-23)

  * Break: the LineFormatter now strips newlines by default because this was a bug, set $allowInlineLineBreaks to true if you need them
  * Added BrowserConsoleHandler to send logs to any browser's console via console.log() injection in the output
  * Added FilterHandler to filter records and only allow those of a given list of levels through to the wrapped handler
  * Added FlowdockHandler to send logs to a Flowdock account
  * Added RollbarHandler to send logs to a Rollbar account
  * Added HtmlFormatter to send prettier log emails with colors for each log level
  * Added GitProcessor to add the current branch/commit to extra record data
  * Added a Monolog\Registry class to allow easier global access to pre-configured loggers
  * Added support for the new official graylog2/gelf-php lib for GelfHandler, upgrade if you can by replacing the mlehner/gelf-php requirement
  * Added support for HHVM
  * Added support for Loggly batch uploads
  * Added support for tweaking the content type and encoding in NativeMailerHandler
  * Added $skipClassesPartials to tweak the ignored classes in the IntrospectionProcessor
  * Fixed batch request support in GelfHandler

### 1.7.0 (2013-11-14)

  * Added ElasticSearchHandler to send logs to an Elastic Search server
  * Added DynamoDbHandler and ScalarFormatter to send logs to Amazon's Dynamo DB
  * Added SyslogUdpHandler to send logs to a remote syslogd server
  * Added LogglyHandler to send logs to a Loggly account
  * Added $level to IntrospectionProcessor so it only adds backtraces when needed
  * Added $version to LogstashFormatter to allow using the new v1 Logstash format
  * Added $appName to NewRelicHandler
  * Added configuration of Pushover notification retries/expiry
  * Added $maxColumnWidth to NativeMailerHandler to change the 70 chars default
  * Added chainability to most setters for all handlers
  * Fixed RavenHandler batch processing so it takes the message from the record with highest priority
  * Fixed HipChatHandler batch processing so it sends all messages at once
  * Fixed issues with eAccelerator
  * Fixed and improved many small things

### 1.6.0 (2013-07-29)

  * Added HipChatHandler to send logs to a HipChat chat room
  * Added ErrorLogHandler to send logs to PHP's error_log function
  * Added NewRelicHandler to send logs to NewRelic's service
  * Added Monolog\ErrorHandler helper class to register a Logger as exception/error/fatal handler
  * Added ChannelLevelActivationStrategy for the FingersCrossedHandler to customize levels by channel
  * Added stack traces output when normalizing exceptions (json output & co)
  * Added Monolog\Logger::API constant (currently 1)
  * Added support for ChromePHP's v4.0 extension
  * Added support for message priorities in PushoverHandler, see $highPriorityLevel and $emergencyLevel
  * Added support for sending messages to multiple users at once with the PushoverHandler
  * Fixed RavenHandler's support for batch sending of messages (when behind a Buffer or FingersCrossedHandler)
  * Fixed normalization of Traversables with very large data sets, only the first 1000 items are shown now
  * Fixed issue in RotatingFileHandler when an open_basedir restriction is active
  * Fixed minor issues in RavenHandler and bumped the API to Raven 0.5.0
  * Fixed SyslogHandler issue when many were used concurrently with different facilities

### 1.5.0 (2013-04-23)

  * Added ProcessIdProcessor to inject the PID in log records
  * Added UidProcessor to inject a unique identifier to all log records of one request/run
  * Added support for previous exceptions in the LineFormatter exception serialization
  * Added Monolog\Logger::getLevels() to get all available levels
  * Fixed ChromePHPHandler so it avoids sending headers larger than Chrome can handle

### 1.4.1 (2013-04-01)

  * Fixed exception formatting in the LineFormatter to be more minimalistic
  * Fixed RavenHandler's handling of context/extra data, requires Raven client >0.1.0
  * Fixed log rotation in RotatingFileHandler to work with long running scripts spanning multiple days
  * Fixed WebProcessor array access so it checks for data presence
  * Fixed Buffer, Group and FingersCrossed handlers to make use of their processors

### 1.4.0 (2013-02-13)

  * Added RedisHandler to log to Redis via the Predis library or the phpredis extension
  * Added ZendMonitorHandler to log to the Zend Server monitor
  * Added the possibility to pass arrays of handlers and processors directly in the Logger constructor
  * Added `$useSSL` option to the PushoverHandler which is enabled by default
  * Fixed ChromePHPHandler and FirePHPHandler issue when multiple instances are used simultaneously
  * Fixed header injection capability in the NativeMailHandler

### 1.3.1 (2013-01-11)

  * Fixed LogstashFormatter to be usable with stream handlers
  * Fixed GelfMessageFormatter levels on Windows

### 1.3.0 (2013-01-08)

  * Added PSR-3 compliance, the `Monolog\Logger` class is now an instance of `Psr\Log\LoggerInterface`
  * Added PsrLogMessageProcessor that you can selectively enable for full PSR-3 compliance
  * Added LogstashFormatter (combine with SocketHandler or StreamHandler to send logs to Logstash)
  * Added PushoverHandler to send mobile notifications
  * Added CouchDBHandler and DoctrineCouchDBHandler
  * Added RavenHandler to send data to Sentry servers
  * Added support for the new MongoClient class in MongoDBHandler
  * Added microsecond precision to log records' timestamps
  * Added `$flushOnOverflow` param to BufferHandler to flush by batches instead of losing
    the oldest entries
  * Fixed normalization of objects with cyclic references

### 1.2.1 (2012-08-29)

  * Added new $logopts arg to SyslogHandler to provide custom openlog options
  * Fixed fatal error in SyslogHandler

### 1.2.0 (2012-08-18)

  * Added AmqpHandler (for use with AMQP servers)
  * Added CubeHandler
  * Added NativeMailerHandler::addHeader() to send custom headers in mails
  * Added the possibility to specify more than one recipient in NativeMailerHandler
  * Added the possibility to specify float timeouts in SocketHandler
  * Added NOTICE and EMERGENCY levels to conform with RFC 5424
  * Fixed the log records to use the php default timezone instead of UTC
  * Fixed BufferHandler not being flushed properly on PHP fatal errors
  * Fixed normalization of exotic resource types
  * Fixed the default format of the SyslogHandler to avoid duplicating datetimes in syslog

### 1.1.0 (2012-04-23)

  * Added Monolog\Logger::isHandling() to check if a handler will
    handle the given log level
  * Added ChromePHPHandler
  * Added MongoDBHandler
  * Added GelfHandler (for use with Graylog2 servers)
  * Added SocketHandler (for use with syslog-ng for example)
  * Added NormalizerFormatter
  * Added the possibility to change the activation strategy of the FingersCrossedHandler
  * Added possibility to show microseconds in logs
  * Added `server` and `referer` to WebProcessor output

### 1.0.2 (2011-10-24)

  * Fixed bug in IE with large response headers and FirePHPHandler

### 1.0.1 (2011-08-25)

  * Added MemoryPeakUsageProcessor and MemoryUsageProcessor
  * Added Monolog\Logger::getName() to get a logger's channel name

### 1.0.0 (2011-07-06)

  * Added IntrospectionProcessor to get info from where the logger was called
  * Fixed WebProcessor in CLI

### 1.0.0-RC1 (2011-07-01)

  * Initial release
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class WhatFailureGroupHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::__construct
     * @expectedException InvalidArgumentException
     */
    public function testConstructorOnlyTakesHandler()
    {
        new WhatFailureGroupHandler(array(new TestHandler(), "foo"));
    }

    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::__construct
     * @covers Monolog\Handler\WhatFailureGroupHandler::handle
     */
    public function testHandle()
    {
        $testHandlers = array(new TestHandler(), new TestHandler());
        $handler = new WhatFailureGroupHandler($testHandlers);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        foreach ($testHandlers as $test) {
            $this->assertTrue($test->hasDebugRecords());
            $this->assertTrue($test->hasInfoRecords());
            $this->assertTrue(count($test->getRecords()) === 2);
        }
    }

    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::handleBatch
     */
    public function testHandleBatch()
    {
        $testHandlers = array(new TestHandler(), new TestHandler());
        $handler = new WhatFailureGroupHandler($testHandlers);
        $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
        foreach ($testHandlers as $test) {
            $this->assertTrue($test->hasDebugRecords());
            $this->assertTrue($test->hasInfoRecords());
            $this->assertTrue(count($test->getRecords()) === 2);
        }
    }

    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::isHandling
     */
    public function testIsHandling()
    {
        $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING));
        $handler = new WhatFailureGroupHandler($testHandlers);
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR)));
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::handle
     */
    public function testHandleUsesProcessors()
    {
        $test = new TestHandler();
        $handler = new WhatFailureGroupHandler(array($test));
        $handler->pushProcessor(function ($record) {
            $record['extra']['foo'] = true;

            return $record;
        });
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }

    /**
     * @covers Monolog\Handler\WhatFailureGroupHandler::handle
     */
    public function testHandleException()
    {
        $test = new TestHandler();
        $exception = new ExceptionTestHandler();
        $handler = new WhatFailureGroupHandler(array($exception, $test, $exception));
        $handler->pushProcessor(function ($record) {
            $record['extra']['foo'] = true;

            return $record;
        });
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }
}

class ExceptionTestHandler extends TestHandler
{
    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        parent::handle($record);

        throw new \Exception("ExceptionTestHandler::handle");
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\ChromePHPHandler
 */
class ChromePHPHandlerTest extends TestCase
{
    protected function setUp()
    {
        TestChromePHPHandler::reset();
        $_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; Chrome/1.0';
    }

    public function testHeaders()
    {
        $handler = new TestChromePHPHandler();
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING));

        $expected = array(
            'X-ChromeLogger-Data'   => base64_encode(utf8_encode(json_encode(array(
                'version' => ChromePHPHandler::VERSION,
                'columns' => array('label', 'log', 'backtrace', 'type'),
                'rows' => array(
                    'test',
                    'test',
                ),
                'request_uri' => '',
            )))),
        );

        $this->assertEquals($expected, $handler->getHeaders());
    }

    public function testHeadersOverflow()
    {
        $handler = new TestChromePHPHandler();
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 150 * 1024)));

        // overflow chrome headers limit
        $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024)));

        $expected = array(
            'X-ChromeLogger-Data'   => base64_encode(utf8_encode(json_encode(array(
                'version' => ChromePHPHandler::VERSION,
                'columns' => array('label', 'log', 'backtrace', 'type'),
                'rows' => array(
                    array(
                        'test',
                        'test',
                        'unknown',
                        'log',
                    ),
                    array(
                        'test',
                        str_repeat('a', 150 * 1024),
                        'unknown',
                        'warn',
                    ),
                    array(
                        'monolog',
                        'Incomplete logs, chrome header size limit reached',
                        'unknown',
                        'warn',
                    ),
                ),
                'request_uri' => '',
            )))),
        );

        $this->assertEquals($expected, $handler->getHeaders());
    }

    public function testConcurrentHandlers()
    {
        $handler = new TestChromePHPHandler();
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING));

        $handler2 = new TestChromePHPHandler();
        $handler2->setFormatter($this->getIdentityFormatter());
        $handler2->handle($this->getRecord(Logger::DEBUG));
        $handler2->handle($this->getRecord(Logger::WARNING));

        $expected = array(
            'X-ChromeLogger-Data'   => base64_encode(utf8_encode(json_encode(array(
                'version' => ChromePHPHandler::VERSION,
                'columns' => array('label', 'log', 'backtrace', 'type'),
                'rows' => array(
                    'test',
                    'test',
                    'test',
                    'test',
                ),
                'request_uri' => '',
            )))),
        );

        $this->assertEquals($expected, $handler2->getHeaders());
    }
}

class TestChromePHPHandler extends ChromePHPHandler
{
    protected $headers = array();

    public static function reset()
    {
        self::$initialized = false;
        self::$overflowed = false;
        self::$sendHeaders = true;
        self::$json['rows'] = array();
    }

    protected function sendHeader($header, $content)
    {
        $this->headers[$header] = $content;
    }

    public function getHeaders()
    {
        return $this->headers;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Exception;
use Monolog\ErrorHandler;
use Monolog\Logger;
use Monolog\TestCase;
use PhpConsole\Connector;
use PhpConsole\Dispatcher\Debug as DebugDispatcher;
use PhpConsole\Dispatcher\Errors as ErrorDispatcher;
use PhpConsole\Handler;
use PHPUnit_Framework_MockObject_MockObject;

/**
 * @covers Monolog\Handler\PHPConsoleHandler
 * @author Sergey Barbushin https://www.linkedin.com/in/barbushin
 */
class PHPConsoleHandlerTest extends TestCase
{
    /** @var  Connector|PHPUnit_Framework_MockObject_MockObject */
    protected $connector;
    /** @var  DebugDispatcher|PHPUnit_Framework_MockObject_MockObject */
    protected $debugDispatcher;
    /** @var  ErrorDispatcher|PHPUnit_Framework_MockObject_MockObject */
    protected $errorDispatcher;

    protected function setUp()
    {
        if (!class_exists('PhpConsole\Connector')) {
            $this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
        }
        $this->connector = $this->initConnectorMock();

        $this->debugDispatcher = $this->initDebugDispatcherMock($this->connector);
        $this->connector->setDebugDispatcher($this->debugDispatcher);

        $this->errorDispatcher = $this->initErrorDispatcherMock($this->connector);
        $this->connector->setErrorsDispatcher($this->errorDispatcher);
    }

    protected function initDebugDispatcherMock(Connector $connector)
    {
        return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
            ->disableOriginalConstructor()
            ->setMethods(array('dispatchDebug'))
            ->setConstructorArgs(array($connector, $connector->getDumper()))
            ->getMock();
    }

    protected function initErrorDispatcherMock(Connector $connector)
    {
        return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
            ->disableOriginalConstructor()
            ->setMethods(array('dispatchError', 'dispatchException'))
            ->setConstructorArgs(array($connector, $connector->getDumper()))
            ->getMock();
    }

    protected function initConnectorMock()
    {
        $connector = $this->getMockBuilder('PhpConsole\Connector')
            ->disableOriginalConstructor()
            ->setMethods(array(
                'sendMessage',
                'onShutDown',
                'isActiveClient',
                'setSourcesBasePath',
                'setServerEncoding',
                'setPassword',
                'enableSslOnlyMode',
                'setAllowedIpMasks',
                'setHeadersLimit',
                'startEvalRequestsListener',
            ))
            ->getMock();

        $connector->expects($this->any())
            ->method('isActiveClient')
            ->will($this->returnValue(true));

        return $connector;
    }

    protected function getHandlerDefaultOption($name)
    {
        $handler = new PHPConsoleHandler(array(), $this->connector);
        $options = $handler->getOptions();

        return $options[$name];
    }

    protected function initLogger($handlerOptions = array(), $level = Logger::DEBUG)
    {
        return new Logger('test', array(
            new PHPConsoleHandler($handlerOptions, $this->connector, $level),
        ));
    }

    public function testInitWithDefaultConnector()
    {
        $handler = new PHPConsoleHandler();
        $this->assertEquals(spl_object_hash(Connector::getInstance()), spl_object_hash($handler->getConnector()));
    }

    public function testInitWithCustomConnector()
    {
        $handler = new PHPConsoleHandler(array(), $this->connector);
        $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
    }

    public function testDebug()
    {
        $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test'));
        $this->initLogger()->addDebug('test');
    }

    public function testDebugContextInMessage()
    {
        $message = 'test';
        $tag = 'tag';
        $context = array($tag, 'custom' => mt_rand());
        $expectedMessage = $message . ' ' . json_encode(array_slice($context, 1));
        $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
            $this->equalTo($expectedMessage),
            $this->equalTo($tag)
        );
        $this->initLogger()->addDebug($message, $context);
    }

    public function testDebugTags($tagsContextKeys = null)
    {
        $expectedTags = mt_rand();
        $logger = $this->initLogger($tagsContextKeys ? array('debugTagsKeysInContext' => $tagsContextKeys) : array());
        if (!$tagsContextKeys) {
            $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
        }
        foreach ($tagsContextKeys as $key) {
            $debugDispatcher = $this->initDebugDispatcherMock($this->connector);
            $debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
                $this->anything(),
                $this->equalTo($expectedTags)
            );
            $this->connector->setDebugDispatcher($debugDispatcher);
            $logger->addDebug('test', array($key => $expectedTags));
        }
    }

    public function testError($classesPartialsTraceIgnore = null)
    {
        $code = E_USER_NOTICE;
        $message = 'message';
        $file = __FILE__;
        $line = __LINE__;
        $this->errorDispatcher->expects($this->once())->method('dispatchError')->with(
            $this->equalTo($code),
            $this->equalTo($message),
            $this->equalTo($file),
            $this->equalTo($line),
            $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
        );
        $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? array('classesPartialsTraceIgnore' => $classesPartialsTraceIgnore) : array()), false);
        $errorHandler->registerErrorHandler(array(), false, E_USER_WARNING);
        $errorHandler->handleError($code, $message, $file, $line);
    }

    public function testException()
    {
        $e = new Exception();
        $this->errorDispatcher->expects($this->once())->method('dispatchException')->with(
            $this->equalTo($e)
        );
        $handler = $this->initLogger();
        $handler->log(
            \Psr\Log\LogLevel::ERROR,
            sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
            array('exception' => $e)
        );
    }

    /**
     * @expectedException Exception
     */
    public function testWrongOptionsThrowsException()
    {
        new PHPConsoleHandler(array('xxx' => 1));
    }

    public function testOptionEnabled()
    {
        $this->debugDispatcher->expects($this->never())->method('dispatchDebug');
        $this->initLogger(array('enabled' => false))->addDebug('test');
    }

    public function testOptionClassesPartialsTraceIgnore()
    {
        $this->testError(array('Class', 'Namespace\\'));
    }

    public function testOptionDebugTagsKeysInContext()
    {
        $this->testDebugTags(array('key1', 'key2'));
    }

    public function testOptionUseOwnErrorsAndExceptionsHandler()
    {
        $this->initLogger(array('useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true));
        $this->assertEquals(array(Handler::getInstance(), 'handleError'), set_error_handler(function () {
        }));
        $this->assertEquals(array(Handler::getInstance(), 'handleException'), set_exception_handler(function () {
        }));
    }

    public static function provideConnectorMethodsOptionsSets()
    {
        return array(
            array('sourcesBasePath', 'setSourcesBasePath', __DIR__),
            array('serverEncoding', 'setServerEncoding', 'cp1251'),
            array('password', 'setPassword', '******'),
            array('enableSslOnlyMode', 'enableSslOnlyMode', true, false),
            array('ipMasks', 'setAllowedIpMasks', array('127.0.0.*')),
            array('headersLimit', 'setHeadersLimit', 2500),
            array('enableEvalListener', 'startEvalRequestsListener', true, false),
        );
    }

    /**
     * @dataProvider provideConnectorMethodsOptionsSets
     */
    public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true)
    {
        $expectCall = $this->connector->expects($this->once())->method($method);
        if ($isArgument) {
            $expectCall->with($value);
        }
        new PHPConsoleHandler(array($option => $value), $this->connector);
    }

    public function testOptionDetectDumpTraceAndSource()
    {
        new PHPConsoleHandler(array('detectDumpTraceAndSource' => true), $this->connector);
        $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
    }

    public static function provideDumperOptionsValues()
    {
        return array(
            array('dumperLevelLimit', 'levelLimit', 1001),
            array('dumperItemsCountLimit', 'itemsCountLimit', 1002),
            array('dumperItemSizeLimit', 'itemSizeLimit', 1003),
            array('dumperDumpSizeLimit', 'dumpSizeLimit', 1004),
            array('dumperDetectCallbacks', 'detectCallbacks', true),
        );
    }

    /**
     * @dataProvider provideDumperOptionsValues
     */
    public function testDumperOptions($option, $dumperProperty, $value)
    {
        new PHPConsoleHandler(array($option => $value), $this->connector);
        $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @author Robert Kaufmann III <rok3@rok3.me>
 */
class LogEntriesHandlerTest extends TestCase
{
    /**
     * @var resource
     */
    private $res;

    /**
     * @var LogEntriesHandler
     */
    private $handler;

    public function testWriteContent()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test'));

        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] test.CRITICAL: Critical write test/', $content);
    }

    public function testWriteBatchContent()
    {
        $records = array(
            $this->getRecord(),
            $this->getRecord(),
            $this->getRecord(),
        );
        $this->createHandler();
        $this->handler->handleBatch($records);

        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] .* \[\] \[\]\n){3}/', $content);
    }

    private function createHandler()
    {
        $useSSL = extension_loaded('openssl');
        $args = array('testToken', $useSSL, Logger::DEBUG, true);
        $this->res = fopen('php://memory', 'a');
        $this->handler = $this->getMock(
            '\Monolog\Handler\LogEntriesHandler',
            array('fsockopen', 'streamSetTimeout', 'closeSocket'),
            $args
        );

        $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($this->handler, 'localhost:1234');

        $this->handler->expects($this->any())
            ->method('fsockopen')
            ->will($this->returnValue($this->res));
        $this->handler->expects($this->any())
            ->method('streamSetTimeout')
            ->will($this->returnValue(true));
        $this->handler->expects($this->any())
            ->method('closeSocket')
            ->will($this->returnValue(true));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
use Monolog\TestCase;

/**
 * @coversDefaultClass \Monolog\Handler\FleepHookHandler
 */
class FleepHookHandlerTest extends TestCase
{
    /**
     * Default token to use in tests
     */
    const TOKEN = '123abc';

    /**
     * @var FleepHookHandler
     */
    private $handler;

    public function setUp()
    {
        parent::setUp();

        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('This test requires openssl extension to run');
        }

        // Create instances of the handler and logger for convenience
        $this->handler = new FleepHookHandler(self::TOKEN);
    }

    /**
     * @covers ::__construct
     */
    public function testConstructorSetsExpectedDefaults()
    {
        $this->assertEquals(Logger::DEBUG, $this->handler->getLevel());
        $this->assertEquals(true, $this->handler->getBubble());
    }

    /**
     * @covers ::getDefaultFormatter
     */
    public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
    {
        $record = array(
            'message' => 'msg',
            'context' => array(),
            'level' => Logger::DEBUG,
            'level_name' => Logger::getLevelName(Logger::DEBUG),
            'channel' => 'channel',
            'datetime' => new \DateTime(),
            'extra' => array(),
        );

        $expectedFormatter = new LineFormatter(null, null, true, true);
        $expected = $expectedFormatter->format($record);

        $handlerFormatter = $this->handler->getFormatter();
        $actual = $handlerFormatter->format($record);

        $this->assertEquals($expected, $actual, 'Empty context and extra arrays should not be rendered');
    }

    /**
     * @covers ::__construct
     */
    public function testConnectionStringisConstructedCorrectly()
    {
        $this->assertEquals('ssl://' . FleepHookHandler::FLEEP_HOST . ':443', $this->handler->getConnectionString());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy;
use Psr\Log\LogLevel;

class FingersCrossedHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\FingersCrossedHandler::__construct
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleBuffers()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertFalse($test->hasDebugRecords());
        $this->assertFalse($test->hasInfoRecords());
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->close();
        $this->assertTrue($test->hasInfoRecords());
        $this->assertTrue(count($test->getRecords()) === 3);
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleStopsBufferingAfterTrigger()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test);
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->close();
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasDebugRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     * @covers Monolog\Handler\FingersCrossedHandler::reset
     */
    public function testHandleRestartBufferingAfterReset()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test);
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->reset();
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->close();
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasDebugRecords());
        $this->assertFalse($test->hasInfoRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleRestartBufferingAfterBeingTriggeredWhenStopBufferingIsDisabled()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, Logger::WARNING, 0, false, false);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->close();
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasDebugRecords());
        $this->assertFalse($test->hasInfoRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleBufferLimit()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, Logger::WARNING, 2);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasInfoRecords());
        $this->assertFalse($test->hasDebugRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleWithCallback()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler(function ($record, $handler) use ($test) {
                    return $test;
                });
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertFalse($test->hasDebugRecords());
        $this->assertFalse($test->hasInfoRecords());
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasInfoRecords());
        $this->assertTrue(count($test->getRecords()) === 3);
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     * @expectedException RuntimeException
     */
    public function testHandleWithBadCallbackThrowsException()
    {
        $handler = new FingersCrossedHandler(function ($record, $handler) {
                    return 'foo';
                });
        $handler->handle($this->getRecord(Logger::WARNING));
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::isHandling
     */
    public function testIsHandlingAlways()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, Logger::ERROR);
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::__construct
     * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct
     * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated
     */
    public function testErrorLevelActivationStrategy()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->assertFalse($test->hasDebugRecords());
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasDebugRecords());
        $this->assertTrue($test->hasWarningRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::__construct
     * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct
     * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated
     */
    public function testErrorLevelActivationStrategyWithPsrLevel()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning'));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->assertFalse($test->hasDebugRecords());
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasDebugRecords());
        $this->assertTrue($test->hasWarningRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct
     * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated
     */
    public function testChannelLevelActivationStrategy()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, array('othertest' => Logger::DEBUG)));
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertFalse($test->hasWarningRecords());
        $record = $this->getRecord(Logger::DEBUG);
        $record['channel'] = 'othertest';
        $handler->handle($record);
        $this->assertTrue($test->hasDebugRecords());
        $this->assertTrue($test->hasWarningRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct
     * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated
     */
    public function testChannelLevelActivationStrategyWithPsrLevels()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', array('othertest' => 'debug')));
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertFalse($test->hasWarningRecords());
        $record = $this->getRecord(Logger::DEBUG);
        $record['channel'] = 'othertest';
        $handler->handle($record);
        $this->assertTrue($test->hasDebugRecords());
        $this->assertTrue($test->hasWarningRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::handle
     */
    public function testHandleUsesProcessors()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, Logger::INFO);
        $handler->pushProcessor(function ($record) {
            $record['extra']['foo'] = true;

            return $record;
        });
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::close
     */
    public function testPassthruOnClose()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, Logger::INFO);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->close();
        $this->assertFalse($test->hasDebugRecords());
        $this->assertTrue($test->hasInfoRecords());
    }

    /**
     * @covers Monolog\Handler\FingersCrossedHandler::close
     */
    public function testPsrLevelPassthruOnClose()
    {
        $test = new TestHandler();
        $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, LogLevel::INFO);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->close();
        $this->assertFalse($test->hasDebugRecords());
        $this->assertTrue($test->hasInfoRecords());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;

/**
 * @author Alexey Karapetov <alexey@karapetov.com>
 */
class HandlerWrapperTest extends TestCase
{
    /**
     * @var HandlerWrapper
     */
    private $wrapper;

    private $handler;

    public function setUp()
    {
        parent::setUp();
        $this->handler = $this->getMock('Monolog\\Handler\\HandlerInterface');
        $this->wrapper = new HandlerWrapper($this->handler);
    }

    /**
     * @return array
     */
    public function trueFalseDataProvider()
    {
        return array(
            array(true),
            array(false),
        );
    }

    /**
     * @param $result
     * @dataProvider trueFalseDataProvider
     */
    public function testIsHandling($result)
    {
        $record = $this->getRecord();
        $this->handler->expects($this->once())
            ->method('isHandling')
            ->with($record)
            ->willReturn($result);

        $this->assertEquals($result, $this->wrapper->isHandling($record));
    }

    /**
     * @param $result
     * @dataProvider trueFalseDataProvider
     */
    public function testHandle($result)
    {
        $record = $this->getRecord();
        $this->handler->expects($this->once())
            ->method('handle')
            ->with($record)
            ->willReturn($result);

        $this->assertEquals($result, $this->wrapper->handle($record));
    }

    /**
     * @param $result
     * @dataProvider trueFalseDataProvider
     */
    public function testHandleBatch($result)
    {
        $records = $this->getMultipleRecords();
        $this->handler->expects($this->once())
            ->method('handleBatch')
            ->with($records)
            ->willReturn($result);

        $this->assertEquals($result, $this->wrapper->handleBatch($records));
    }

    public function testPushProcessor()
    {
        $processor = function () {};
        $this->handler->expects($this->once())
            ->method('pushProcessor')
            ->with($processor);

        $this->assertEquals($this->wrapper, $this->wrapper->pushProcessor($processor));
    }

    public function testPopProcessor()
    {
        $processor = function () {};
        $this->handler->expects($this->once())
            ->method('popProcessor')
            ->willReturn($processor);

        $this->assertEquals($processor, $this->wrapper->popProcessor());
    }

    public function testSetFormatter()
    {
        $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $this->handler->expects($this->once())
            ->method('setFormatter')
            ->with($formatter);

        $this->assertEquals($this->wrapper, $this->wrapper->setFormatter($formatter));
    }

    public function testGetFormatter()
    {
        $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $this->handler->expects($this->once())
            ->method('getFormatter')
            ->willReturn($formatter);

        $this->assertEquals($formatter, $this->wrapper->getFormatter());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;

/**
 * @covers Monolog\Handler\SamplingHandler::handle
 */
class SamplingHandlerTest extends TestCase
{
    public function testHandle()
    {
        $testHandler = new TestHandler();
        $handler = new SamplingHandler($testHandler, 2);
        for ($i = 0; $i < 10000; $i++) {
            $handler->handle($this->getRecord());
        }
        $count = count($testHandler->getRecords());
        // $count should be half of 10k, so between 4k and 6k
        $this->assertLessThan(6000, $count);
        $this->assertGreaterThan(4000, $count);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class StreamHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWrite()
    {
        $handle = fopen('php://memory', 'a+');
        $handler = new StreamHandler($handle);
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord(Logger::WARNING, 'test'));
        $handler->handle($this->getRecord(Logger::WARNING, 'test2'));
        $handler->handle($this->getRecord(Logger::WARNING, 'test3'));
        fseek($handle, 0);
        $this->assertEquals('testtest2test3', fread($handle, 100));
    }

    /**
     * @covers Monolog\Handler\StreamHandler::close
     */
    public function testClose()
    {
        $handle = fopen('php://memory', 'a+');
        $handler = new StreamHandler($handle);
        $this->assertTrue(is_resource($handle));
        $handler->close();
        $this->assertFalse(is_resource($handle));
    }

    /**
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteCreatesTheStreamResource()
    {
        $handler = new StreamHandler('php://memory');
        $handler->handle($this->getRecord());
    }

    /**
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteLocking()
    {
        $temp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'monolog_locked_log';
        $handler = new StreamHandler($temp, Logger::DEBUG, true, null, true);
        $handler->handle($this->getRecord());
    }

    /**
     * @expectedException LogicException
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteMissingResource()
    {
        $handler = new StreamHandler(null);
        $handler->handle($this->getRecord());
    }

    public function invalidArgumentProvider()
    {
        return array(
            array(1),
            array(array()),
            array(array('bogus://url')),
        );
    }

    /**
     * @dataProvider invalidArgumentProvider
     * @expectedException InvalidArgumentException
     * @covers Monolog\Handler\StreamHandler::__construct
     */
    public function testWriteInvalidArgument($invalidArgument)
    {
        $handler = new StreamHandler($invalidArgument);
    }

    /**
     * @expectedException UnexpectedValueException
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteInvalidResource()
    {
        $handler = new StreamHandler('bogus://url');
        $handler->handle($this->getRecord());
    }

    /**
     * @expectedException UnexpectedValueException
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteNonExistingResource()
    {
        $handler = new StreamHandler('ftp://foo/bar/baz/'.rand(0, 10000));
        $handler->handle($this->getRecord());
    }

    /**
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteNonExistingPath()
    {
        $handler = new StreamHandler(sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
        $handler->handle($this->getRecord());
    }

    /**
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteNonExistingFileResource()
    {
        $handler = new StreamHandler('file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
        $handler->handle($this->getRecord());
    }

    /**
     * @expectedException Exception
     * @expectedExceptionMessageRegExp /There is no existing directory at/
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteNonExistingAndNotCreatablePath()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Permissions checks can not run on windows');
        }
        $handler = new StreamHandler('/foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
        $handler->handle($this->getRecord());
    }

    /**
     * @expectedException Exception
     * @expectedExceptionMessageRegExp /There is no existing directory at/
     * @covers Monolog\Handler\StreamHandler::__construct
     * @covers Monolog\Handler\StreamHandler::write
     */
    public function testWriteNonExistingAndNotCreatableFileResource()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Permissions checks can not run on windows');
        }
        $handler = new StreamHandler('file:///foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
        $handler->handle($this->getRecord());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @author Pablo de Leon Belloc <pablolb@gmail.com>
 */
class SocketHandlerTest extends TestCase
{
    /**
     * @var Monolog\Handler\SocketHandler
     */
    private $handler;

    /**
     * @var resource
     */
    private $res;

    /**
     * @expectedException UnexpectedValueException
     */
    public function testInvalidHostname()
    {
        $this->createHandler('garbage://here');
        $this->writeRecord('data');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testBadConnectionTimeout()
    {
        $this->createHandler('localhost:1234');
        $this->handler->setConnectionTimeout(-1);
    }

    public function testSetConnectionTimeout()
    {
        $this->createHandler('localhost:1234');
        $this->handler->setConnectionTimeout(10.1);
        $this->assertEquals(10.1, $this->handler->getConnectionTimeout());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testBadTimeout()
    {
        $this->createHandler('localhost:1234');
        $this->handler->setTimeout(-1);
    }

    public function testSetTimeout()
    {
        $this->createHandler('localhost:1234');
        $this->handler->setTimeout(10.25);
        $this->assertEquals(10.25, $this->handler->getTimeout());
    }

    public function testSetWritingTimeout()
    {
        $this->createHandler('localhost:1234');
        $this->handler->setWritingTimeout(10.25);
        $this->assertEquals(10.25, $this->handler->getWritingTimeout());
    }

    public function testSetConnectionString()
    {
        $this->createHandler('tcp://localhost:9090');
        $this->assertEquals('tcp://localhost:9090', $this->handler->getConnectionString());
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testExceptionIsThrownOnFsockopenError()
    {
        $this->setMockHandler(array('fsockopen'));
        $this->handler->expects($this->once())
            ->method('fsockopen')
            ->will($this->returnValue(false));
        $this->writeRecord('Hello world');
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testExceptionIsThrownOnPfsockopenError()
    {
        $this->setMockHandler(array('pfsockopen'));
        $this->handler->expects($this->once())
            ->method('pfsockopen')
            ->will($this->returnValue(false));
        $this->handler->setPersistent(true);
        $this->writeRecord('Hello world');
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testExceptionIsThrownIfCannotSetTimeout()
    {
        $this->setMockHandler(array('streamSetTimeout'));
        $this->handler->expects($this->once())
            ->method('streamSetTimeout')
            ->will($this->returnValue(false));
        $this->writeRecord('Hello world');
    }

    /**
     * @expectedException RuntimeException
     */
    public function testWriteFailsOnIfFwriteReturnsFalse()
    {
        $this->setMockHandler(array('fwrite'));

        $callback = function ($arg) {
            $map = array(
                'Hello world' => 6,
                'world' => false,
            );

            return $map[$arg];
        };

        $this->handler->expects($this->exactly(2))
            ->method('fwrite')
            ->will($this->returnCallback($callback));

        $this->writeRecord('Hello world');
    }

    /**
     * @expectedException RuntimeException
     */
    public function testWriteFailsIfStreamTimesOut()
    {
        $this->setMockHandler(array('fwrite', 'streamGetMetadata'));

        $callback = function ($arg) {
            $map = array(
                'Hello world' => 6,
                'world' => 5,
            );

            return $map[$arg];
        };

        $this->handler->expects($this->exactly(1))
            ->method('fwrite')
            ->will($this->returnCallback($callback));
        $this->handler->expects($this->exactly(1))
            ->method('streamGetMetadata')
            ->will($this->returnValue(array('timed_out' => true)));

        $this->writeRecord('Hello world');
    }

    /**
     * @expectedException RuntimeException
     */
    public function testWriteFailsOnIncompleteWrite()
    {
        $this->setMockHandler(array('fwrite', 'streamGetMetadata'));

        $res = $this->res;
        $callback = function ($string) use ($res) {
            fclose($res);

            return strlen('Hello');
        };

        $this->handler->expects($this->exactly(1))
            ->method('fwrite')
            ->will($this->returnCallback($callback));
        $this->handler->expects($this->exactly(1))
            ->method('streamGetMetadata')
            ->will($this->returnValue(array('timed_out' => false)));

        $this->writeRecord('Hello world');
    }

    public function testWriteWithMemoryFile()
    {
        $this->setMockHandler();
        $this->writeRecord('test1');
        $this->writeRecord('test2');
        $this->writeRecord('test3');
        fseek($this->res, 0);
        $this->assertEquals('test1test2test3', fread($this->res, 1024));
    }

    public function testWriteWithMock()
    {
        $this->setMockHandler(array('fwrite'));

        $callback = function ($arg) {
            $map = array(
                'Hello world' => 6,
                'world' => 5,
            );

            return $map[$arg];
        };

        $this->handler->expects($this->exactly(2))
            ->method('fwrite')
            ->will($this->returnCallback($callback));

        $this->writeRecord('Hello world');
    }

    public function testClose()
    {
        $this->setMockHandler();
        $this->writeRecord('Hello world');
        $this->assertInternalType('resource', $this->res);
        $this->handler->close();
        $this->assertFalse(is_resource($this->res), "Expected resource to be closed after closing handler");
    }

    public function testCloseDoesNotClosePersistentSocket()
    {
        $this->setMockHandler();
        $this->handler->setPersistent(true);
        $this->writeRecord('Hello world');
        $this->assertTrue(is_resource($this->res));
        $this->handler->close();
        $this->assertTrue(is_resource($this->res));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds()
    {
        $this->setMockHandler(array('fwrite', 'streamGetMetadata'));

        $this->handler->expects($this->any())
            ->method('fwrite')
            ->will($this->returnValue(0));

        $this->handler->expects($this->any())
            ->method('streamGetMetadata')
            ->will($this->returnValue(array('timed_out' => false)));

        $this->handler->setWritingTimeout(1);

        $this->writeRecord('Hello world');
    }

    private function createHandler($connectionString)
    {
        $this->handler = new SocketHandler($connectionString);
        $this->handler->setFormatter($this->getIdentityFormatter());
    }

    private function writeRecord($string)
    {
        $this->handler->handle($this->getRecord(Logger::WARNING, $string));
    }

    private function setMockHandler(array $methods = array())
    {
        $this->res = fopen('php://memory', 'a');

        $defaultMethods = array('fsockopen', 'pfsockopen', 'streamSetTimeout');
        $newMethods = array_diff($methods, $defaultMethods);

        $finalMethods = array_merge($defaultMethods, $newMethods);

        $this->handler = $this->getMock(
            '\Monolog\Handler\SocketHandler', $finalMethods, array('localhost:1234')
        );

        if (!in_array('fsockopen', $methods)) {
            $this->handler->expects($this->any())
                ->method('fsockopen')
                ->will($this->returnValue($this->res));
        }

        if (!in_array('pfsockopen', $methods)) {
            $this->handler->expects($this->any())
                ->method('pfsockopen')
                ->will($this->returnValue($this->res));
        }

        if (!in_array('streamSetTimeout', $methods)) {
            $this->handler->expects($this->any())
                ->method('streamSetTimeout')
                ->will($this->returnValue(true));
        }

        $this->handler->setFormatter($this->getIdentityFormatter());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * Almost all examples (expected header, titles, messages) taken from
 * https://www.pushover.net/api
 * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
 * @see https://www.pushover.net/api
 */
class PushoverHandlerTest extends TestCase
{
    private $res;
    private $handler;

    public function testWriteHeader()
    {
        $this->createHandler();
        $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/1\/messages.json HTTP\/1.1\\r\\nHost: api.pushover.net\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    /**
     * @depends testWriteHeader
     */
    public function testWriteContent($content)
    {
        $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog&timestamp=\d{10}$/', $content);
    }

    public function testWriteWithComplexTitle()
    {
        $this->createHandler('myToken', 'myUser', 'Backup finished - SQL1');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/title=Backup\+finished\+-\+SQL1/', $content);
    }

    public function testWriteWithComplexMessage()
    {
        $this->createHandler();
        $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Backup of database "example" finished in 16 minutes.'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/message=Backup\+of\+database\+%22example%22\+finished\+in\+16\+minutes\./', $content);
    }

    public function testWriteWithTooLongMessage()
    {
        $message = str_pad('test', 520, 'a');
        $this->createHandler();
        $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications
        $this->handler->handle($this->getRecord(Logger::CRITICAL, $message));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $expectedMessage = substr($message, 0, 505);

        $this->assertRegexp('/message=' . $expectedMessage . '&title/', $content);
    }

    public function testWriteWithHighPriority()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog&timestamp=\d{10}&priority=1$/', $content);
    }

    public function testWriteWithEmergencyPriority()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog&timestamp=\d{10}&priority=2&retry=30&expire=25200$/', $content);
    }

    public function testWriteToMultipleUsers()
    {
        $this->createHandler('myToken', array('userA', 'userB'));
        $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/token=myToken&user=userA&message=test1&title=Monolog&timestamp=\d{10}&priority=2&retry=30&expire=25200POST/', $content);
        $this->assertRegexp('/token=myToken&user=userB&message=test1&title=Monolog&timestamp=\d{10}&priority=2&retry=30&expire=25200$/', $content);
    }

    private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog')
    {
        $constructorArgs = array($token, $user, $title);
        $this->res = fopen('php://memory', 'a');
        $this->handler = $this->getMock(
            '\Monolog\Handler\PushoverHandler',
            array('fsockopen', 'streamSetTimeout', 'closeSocket'),
            $constructorArgs
        );

        $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($this->handler, 'localhost:1234');

        $this->handler->expects($this->any())
            ->method('fsockopen')
            ->will($this->returnValue($this->res));
        $this->handler->expects($this->any())
            ->method('streamSetTimeout')
            ->will($this->returnValue(true));
        $this->handler->expects($this->any())
            ->method('closeSocket')
            ->will($this->returnValue(true));

        $this->handler->setFormatter($this->getIdentityFormatter());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class NewRelicHandlerTest extends TestCase
{
    public static $appname;
    public static $customParameters;
    public static $transactionName;

    public function setUp()
    {
        self::$appname = null;
        self::$customParameters = array();
        self::$transactionName = null;
    }

    /**
     * @expectedException Monolog\Handler\MissingExtensionException
     */
    public function testThehandlerThrowsAnExceptionIfTheNRExtensionIsNotLoaded()
    {
        $handler = new StubNewRelicHandlerWithoutExtension();
        $handler->handle($this->getRecord(Logger::ERROR));
    }

    public function testThehandlerCanHandleTheRecord()
    {
        $handler = new StubNewRelicHandler();
        $handler->handle($this->getRecord(Logger::ERROR));
    }

    public function testThehandlerCanAddContextParamsToTheNewRelicTrace()
    {
        $handler = new StubNewRelicHandler();
        $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('a' => 'b')));
        $this->assertEquals(array('context_a' => 'b'), self::$customParameters);
    }

    public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace()
    {
        $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true);
        $handler->handle($this->getRecord(
            Logger::ERROR,
            'log message',
            array('a' => array('key1' => 'value1', 'key2' => 'value2'))
        ));
        $this->assertEquals(
            array('context_a_key1' => 'value1', 'context_a_key2' => 'value2'),
            self::$customParameters
        );
    }

    public function testThehandlerCanAddExtraParamsToTheNewRelicTrace()
    {
        $record = $this->getRecord(Logger::ERROR, 'log message');
        $record['extra'] = array('c' => 'd');

        $handler = new StubNewRelicHandler();
        $handler->handle($record);

        $this->assertEquals(array('extra_c' => 'd'), self::$customParameters);
    }

    public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace()
    {
        $record = $this->getRecord(Logger::ERROR, 'log message');
        $record['extra'] = array('c' => array('key1' => 'value1', 'key2' => 'value2'));

        $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true);
        $handler->handle($record);

        $this->assertEquals(
            array('extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'),
            self::$customParameters
        );
    }

    public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace()
    {
        $record = $this->getRecord(Logger::ERROR, 'log message', array('a' => 'b'));
        $record['extra'] = array('c' => 'd');

        $handler = new StubNewRelicHandler();
        $handler->handle($record);

        $expected = array(
            'context_a' => 'b',
            'extra_c' => 'd',
        );

        $this->assertEquals($expected, self::$customParameters);
    }

    public function testTheAppNameIsNullByDefault()
    {
        $handler = new StubNewRelicHandler();
        $handler->handle($this->getRecord(Logger::ERROR, 'log message'));

        $this->assertEquals(null, self::$appname);
    }

    public function testTheAppNameCanBeInjectedFromtheConstructor()
    {
        $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName');
        $handler->handle($this->getRecord(Logger::ERROR, 'log message'));

        $this->assertEquals('myAppName', self::$appname);
    }

    public function testTheAppNameCanBeOverriddenFromEachLog()
    {
        $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName');
        $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('appname' => 'logAppName')));

        $this->assertEquals('logAppName', self::$appname);
    }

    public function testTheTransactionNameIsNullByDefault()
    {
        $handler = new StubNewRelicHandler();
        $handler->handle($this->getRecord(Logger::ERROR, 'log message'));

        $this->assertEquals(null, self::$transactionName);
    }

    public function testTheTransactionNameCanBeInjectedFromTheConstructor()
    {
        $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction');
        $handler->handle($this->getRecord(Logger::ERROR, 'log message'));

        $this->assertEquals('myTransaction', self::$transactionName);
    }

    public function testTheTransactionNameCanBeOverriddenFromEachLog()
    {
        $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction');
        $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('transaction_name' => 'logTransactName')));

        $this->assertEquals('logTransactName', self::$transactionName);
    }
}

class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
{
    protected function isNewRelicEnabled()
    {
        return false;
    }
}

class StubNewRelicHandler extends NewRelicHandler
{
    protected function isNewRelicEnabled()
    {
        return true;
    }
}

function newrelic_notice_error()
{
    return true;
}

function newrelic_set_appname($appname)
{
    return NewRelicHandlerTest::$appname = $appname;
}

function newrelic_name_transaction($transactionName)
{
    return NewRelicHandlerTest::$transactionName = $transactionName;
}

function newrelic_add_custom_parameter($key, $value)
{
    NewRelicHandlerTest::$customParameters[$key] = $value;

    return true;
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Gelf\Message;
use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter;

class GelfHandlerTest extends TestCase
{
    public function setUp()
    {
        if (!class_exists('Gelf\Publisher') || !class_exists('Gelf\Message')) {
            $this->markTestSkipped("graylog2/gelf-php not installed");
        }
    }

    /**
     * @covers Monolog\Handler\GelfHandler::__construct
     */
    public function testConstruct()
    {
        $handler = new GelfHandler($this->getMessagePublisher());
        $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler);
    }

    protected function getHandler($messagePublisher)
    {
        $handler = new GelfHandler($messagePublisher);

        return $handler;
    }

    protected function getMessagePublisher()
    {
        return $this->getMock('Gelf\Publisher', array('publish'), array(), '', false);
    }

    public function testDebug()
    {
        $record = $this->getRecord(Logger::DEBUG, "A test debug message");
        $expectedMessage = new Message();
        $expectedMessage
            ->setLevel(7)
            ->setFacility("test")
            ->setShortMessage($record['message'])
            ->setTimestamp($record['datetime'])
        ;

        $messagePublisher = $this->getMessagePublisher();
        $messagePublisher->expects($this->once())
            ->method('publish')
            ->with($expectedMessage);

        $handler = $this->getHandler($messagePublisher);

        $handler->handle($record);
    }

    public function testWarning()
    {
        $record = $this->getRecord(Logger::WARNING, "A test warning message");
        $expectedMessage = new Message();
        $expectedMessage
            ->setLevel(4)
            ->setFacility("test")
            ->setShortMessage($record['message'])
            ->setTimestamp($record['datetime'])
        ;

        $messagePublisher = $this->getMessagePublisher();
        $messagePublisher->expects($this->once())
            ->method('publish')
            ->with($expectedMessage);

        $handler = $this->getHandler($messagePublisher);

        $handler->handle($record);
    }

    public function testInjectedGelfMessageFormatter()
    {
        $record = $this->getRecord(Logger::WARNING, "A test warning message");
        $record['extra']['blarg'] = 'yep';
        $record['context']['from'] = 'logger';

        $expectedMessage = new Message();
        $expectedMessage
            ->setLevel(4)
            ->setFacility("test")
            ->setHost("mysystem")
            ->setShortMessage($record['message'])
            ->setTimestamp($record['datetime'])
            ->setAdditional("EXTblarg", 'yep')
            ->setAdditional("CTXfrom", 'logger')
        ;

        $messagePublisher = $this->getMessagePublisher();
        $messagePublisher->expects($this->once())
            ->method('publish')
            ->with($expectedMessage);

        $handler = $this->getHandler($messagePublisher);
        $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX'));
        $handler->handle($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\TestCase;
use Monolog\Logger;
use Elastica\Client;
use Elastica\Request;
use Elastica\Response;

class ElasticSearchHandlerTest extends TestCase
{
    /**
     * @var Client mock
     */
    protected $client;

    /**
     * @var array Default handler options
     */
    protected $options = array(
        'index' => 'my_index',
        'type'  => 'doc_type',
    );

    public function setUp()
    {
        // Elastica lib required
        if (!class_exists("Elastica\Client")) {
            $this->markTestSkipped("ruflin/elastica not installed");
        }

        // base mock Elastica Client object
        $this->client = $this->getMockBuilder('Elastica\Client')
            ->setMethods(array('addDocuments'))
            ->disableOriginalConstructor()
            ->getMock();
    }

    /**
     * @covers Monolog\Handler\ElasticSearchHandler::write
     * @covers Monolog\Handler\ElasticSearchHandler::handleBatch
     * @covers Monolog\Handler\ElasticSearchHandler::bulkSend
     * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter
     */
    public function testHandle()
    {
        // log message
        $msg = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        // format expected result
        $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
        $expected = array($formatter->format($msg));

        // setup ES client mock
        $this->client->expects($this->any())
            ->method('addDocuments')
            ->with($expected);

        // perform tests
        $handler = new ElasticSearchHandler($this->client, $this->options);
        $handler->handle($msg);
        $handler->handleBatch(array($msg));
    }

    /**
     * @covers Monolog\Handler\ElasticSearchHandler::setFormatter
     */
    public function testSetFormatter()
    {
        $handler = new ElasticSearchHandler($this->client);
        $formatter = new ElasticaFormatter('index_new', 'type_new');
        $handler->setFormatter($formatter);
        $this->assertInstanceOf('Monolog\Formatter\ElasticaFormatter', $handler->getFormatter());
        $this->assertEquals('index_new', $handler->getFormatter()->getIndex());
        $this->assertEquals('type_new', $handler->getFormatter()->getType());
    }

    /**
     * @covers                   Monolog\Handler\ElasticSearchHandler::setFormatter
     * @expectedException        InvalidArgumentException
     * @expectedExceptionMessage ElasticSearchHandler is only compatible with ElasticaFormatter
     */
    public function testSetFormatterInvalid()
    {
        $handler = new ElasticSearchHandler($this->client);
        $formatter = new NormalizerFormatter();
        $handler->setFormatter($formatter);
    }

    /**
     * @covers Monolog\Handler\ElasticSearchHandler::__construct
     * @covers Monolog\Handler\ElasticSearchHandler::getOptions
     */
    public function testOptions()
    {
        $expected = array(
            'index' => $this->options['index'],
            'type' => $this->options['type'],
            'ignore_error' => false,
        );
        $handler = new ElasticSearchHandler($this->client, $this->options);
        $this->assertEquals($expected, $handler->getOptions());
    }

    /**
     * @covers       Monolog\Handler\ElasticSearchHandler::bulkSend
     * @dataProvider providerTestConnectionErrors
     */
    public function testConnectionErrors($ignore, $expectedError)
    {
        $clientOpts = array('host' => '127.0.0.1', 'port' => 1);
        $client = new Client($clientOpts);
        $handlerOpts = array('ignore_error' => $ignore);
        $handler = new ElasticSearchHandler($client, $handlerOpts);

        if ($expectedError) {
            $this->setExpectedException($expectedError[0], $expectedError[1]);
            $handler->handle($this->getRecord());
        } else {
            $this->assertFalse($handler->handle($this->getRecord()));
        }
    }

    /**
     * @return array
     */
    public function providerTestConnectionErrors()
    {
        return array(
            array(false, array('RuntimeException', 'Error sending messages to Elasticsearch')),
            array(true, false),
        );
    }

    /**
     * Integration test using localhost Elastic Search server
     *
     * @covers Monolog\Handler\ElasticSearchHandler::__construct
     * @covers Monolog\Handler\ElasticSearchHandler::handleBatch
     * @covers Monolog\Handler\ElasticSearchHandler::bulkSend
     * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter
     */
    public function testHandleIntegration()
    {
        $msg = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $expected = $msg;
        $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
        $expected['context'] = array(
            'class' => '[object] (stdClass: {})',
            'foo' => 7,
            0 => 'bar',
        );

        $client = new Client();
        $handler = new ElasticSearchHandler($client, $this->options);
        try {
            $handler->handleBatch(array($msg));
        } catch (\RuntimeException $e) {
            $this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
        }

        // check document id from ES server response
        $documentId = $this->getCreatedDocId($client->getLastResponse());
        $this->assertNotEmpty($documentId, 'No elastic document id received');

        // retrieve document source from ES and validate
        $document = $this->getDocSourceFromElastic(
            $client,
            $this->options['index'],
            $this->options['type'],
            $documentId
        );
        $this->assertEquals($expected, $document);

        // remove test index from ES
        $client->request("/{$this->options['index']}", Request::DELETE);
    }

    /**
     * Return last created document id from ES response
     * @param  Response    $response Elastica Response object
     * @return string|null
     */
    protected function getCreatedDocId(Response $response)
    {
        $data = $response->getData();
        if (!empty($data['items'][0]['create']['_id'])) {
            return $data['items'][0]['create']['_id'];
        }
    }

    /**
     * Retrieve document by id from Elasticsearch
     * @param  Client $client     Elastica client
     * @param  string $index
     * @param  string $type
     * @param  string $documentId
     * @return array
     */
    protected function getDocSourceFromElastic(Client $client, $index, $type, $documentId)
    {
        $resp = $client->request("/{$index}/{$type}/{$documentId}", Request::GET);
        $data = $resp->getData();
        if (!empty($data['_source'])) {
            return $data['_source'];
        }

        return array();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;

class RavenHandlerTest extends TestCase
{
    public function setUp()
    {
        if (!class_exists('Raven_Client')) {
            $this->markTestSkipped('raven/raven not installed');
        }

        require_once __DIR__ . '/MockRavenClient.php';
    }

    /**
     * @covers Monolog\Handler\RavenHandler::__construct
     */
    public function testConstruct()
    {
        $handler = new RavenHandler($this->getRavenClient());
        $this->assertInstanceOf('Monolog\Handler\RavenHandler', $handler);
    }

    protected function getHandler($ravenClient)
    {
        $handler = new RavenHandler($ravenClient);

        return $handler;
    }

    protected function getRavenClient()
    {
        $dsn = 'http://43f6017361224d098402974103bfc53d:a6a0538fc2934ba2bed32e08741b2cd3@marca.python.live.cheggnet.com:9000/1';

        return new MockRavenClient($dsn);
    }

    public function testDebug()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $record = $this->getRecord(Logger::DEBUG, 'A test debug message');
        $handler->handle($record);

        $this->assertEquals($ravenClient::DEBUG, $ravenClient->lastData['level']);
        $this->assertContains($record['message'], $ravenClient->lastData['message']);
    }

    public function testWarning()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $record = $this->getRecord(Logger::WARNING, 'A test warning message');
        $handler->handle($record);

        $this->assertEquals($ravenClient::WARNING, $ravenClient->lastData['level']);
        $this->assertContains($record['message'], $ravenClient->lastData['message']);
    }

    public function testTag()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $tags = array(1, 2, 'foo');
        $record = $this->getRecord(Logger::INFO, 'test', array('tags' => $tags));
        $handler->handle($record);

        $this->assertEquals($tags, $ravenClient->lastData['tags']);
    }

    public function testExtraParameters()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $checksum = '098f6bcd4621d373cade4e832627b4f6';
        $release = '05a671c66aefea124cc08b76ea6d30bb';
        $record = $this->getRecord(Logger::INFO, 'test', array('checksum' => $checksum, 'release' => $release));
        $handler->handle($record);

        $this->assertEquals($checksum, $ravenClient->lastData['checksum']);
        $this->assertEquals($release, $ravenClient->lastData['release']);
    }

    public function testFingerprint()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $fingerprint = array('{{ default }}', 'other value');
        $record = $this->getRecord(Logger::INFO, 'test', array('fingerprint' => $fingerprint));
        $handler->handle($record);

        $this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']);
    }

    public function testUserContext()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context');
        // set user context 'externally'

        $user = array(
            'id' => '123',
            'email' => 'test@test.com',
        );

        $recordWithContext = $this->getRecord(Logger::INFO, 'test', array('user' => $user));

        $ravenClient->user_context(array('id' => 'test_user_id'));
        // handle context
        $handler->handle($recordWithContext);
        $this->assertEquals($user, $ravenClient->lastData['user']);

        // check to see if its reset
        $handler->handle($recordWithNoContext);
        $this->assertInternalType('array', $ravenClient->context->user);
        $this->assertSame('test_user_id', $ravenClient->context->user['id']);

        // handle with null context
        $ravenClient->user_context(null);
        $handler->handle($recordWithContext);
        $this->assertEquals($user, $ravenClient->lastData['user']);

        // check to see if its reset
        $handler->handle($recordWithNoContext);
        $this->assertNull($ravenClient->context->user);
    }

    public function testException()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        try {
            $this->methodThatThrowsAnException();
        } catch (\Exception $e) {
            $record = $this->getRecord(Logger::ERROR, $e->getMessage(), array('exception' => $e));
            $handler->handle($record);
        }

        $this->assertEquals($record['message'], $ravenClient->lastData['message']);
    }

    public function testHandleBatch()
    {
        $records = $this->getMultipleRecords();
        $records[] = $this->getRecord(Logger::WARNING, 'warning');
        $records[] = $this->getRecord(Logger::WARNING, 'warning');

        $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $logFormatter->expects($this->once())->method('formatBatch');

        $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $formatter->expects($this->once())->method('format')->with($this->callback(function ($record) {
            return $record['level'] == 400;
        }));

        $handler = $this->getHandler($this->getRavenClient());
        $handler->setBatchFormatter($logFormatter);
        $handler->setFormatter($formatter);
        $handler->handleBatch($records);
    }

    public function testHandleBatchDoNothingIfRecordsAreBelowLevel()
    {
        $records = array(
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
            $this->getRecord(Logger::INFO, 'information'),
        );

        $handler = $this->getMock('Monolog\Handler\RavenHandler', null, array($this->getRavenClient()));
        $handler->expects($this->never())->method('handle');
        $handler->setLevel(Logger::ERROR);
        $handler->handleBatch($records);
    }

    public function testGetSetBatchFormatter()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);

        $handler->setBatchFormatter($formatter = new LineFormatter());
        $this->assertSame($formatter, $handler->getBatchFormatter());
    }

    public function testRelease()
    {
        $ravenClient = $this->getRavenClient();
        $handler = $this->getHandler($ravenClient);
        $release = 'v42.42.42';
        $handler->setRelease($release);
        $record = $this->getRecord(Logger::INFO, 'test');
        $handler->handle($record);
        $this->assertEquals($release, $ravenClient->lastData['release']);

        $localRelease = 'v41.41.41';
        $record = $this->getRecord(Logger::INFO, 'test', array('release' => $localRelease));
        $handler->handle($record);
        $this->assertEquals($localRelease, $ravenClient->lastData['release']);
    }

    private function methodThatThrowsAnException()
    {
        throw new \Exception('This is an exception');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Processor\WebProcessor;

class AbstractHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\AbstractHandler::__construct
     * @covers Monolog\Handler\AbstractHandler::getLevel
     * @covers Monolog\Handler\AbstractHandler::setLevel
     * @covers Monolog\Handler\AbstractHandler::getBubble
     * @covers Monolog\Handler\AbstractHandler::setBubble
     * @covers Monolog\Handler\AbstractHandler::getFormatter
     * @covers Monolog\Handler\AbstractHandler::setFormatter
     */
    public function testConstructAndGetSet()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false));
        $this->assertEquals(Logger::WARNING, $handler->getLevel());
        $this->assertEquals(false, $handler->getBubble());

        $handler->setLevel(Logger::ERROR);
        $handler->setBubble(true);
        $handler->setFormatter($formatter = new LineFormatter);
        $this->assertEquals(Logger::ERROR, $handler->getLevel());
        $this->assertEquals(true, $handler->getBubble());
        $this->assertSame($formatter, $handler->getFormatter());
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::handleBatch
     */
    public function testHandleBatch()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
        $handler->expects($this->exactly(2))
            ->method('handle');
        $handler->handleBatch(array($this->getRecord(), $this->getRecord()));
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::isHandling
     */
    public function testIsHandling()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false));
        $this->assertTrue($handler->isHandling($this->getRecord()));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::__construct
     */
    public function testHandlesPsrStyleLevels()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array('warning', false));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
        $handler->setLevel('debug');
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::getFormatter
     * @covers Monolog\Handler\AbstractHandler::getDefaultFormatter
     */
    public function testGetFormatterInitializesDefault()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
        $this->assertInstanceOf('Monolog\Formatter\LineFormatter', $handler->getFormatter());
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::pushProcessor
     * @covers Monolog\Handler\AbstractHandler::popProcessor
     * @expectedException LogicException
     */
    public function testPushPopProcessor()
    {
        $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
        $processor1 = new WebProcessor;
        $processor2 = new WebProcessor;

        $logger->pushProcessor($processor1);
        $logger->pushProcessor($processor2);

        $this->assertEquals($processor2, $logger->popProcessor());
        $this->assertEquals($processor1, $logger->popProcessor());
        $logger->popProcessor();
    }

    /**
     * @covers Monolog\Handler\AbstractHandler::pushProcessor
     * @expectedException InvalidArgumentException
     */
    public function testPushProcessorWithNonCallable()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');

        $handler->pushProcessor(new \stdClass());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPConnection;

/**
 * @covers Monolog\Handler\RotatingFileHandler
 */
class AmqpHandlerTest extends TestCase
{
    public function testHandleAmqpExt()
    {
        if (!class_exists('AMQPConnection') || !class_exists('AMQPExchange')) {
            $this->markTestSkipped("amqp-php not installed");
        }

        if (!class_exists('AMQPChannel')) {
            $this->markTestSkipped("Please update AMQP to version >= 1.0");
        }

        $messages = array();

        $exchange = $this->getMock('AMQPExchange', array('publish', 'setName'), array(), '', false);
        $exchange->expects($this->once())
            ->method('setName')
            ->with('log')
        ;
        $exchange->expects($this->any())
            ->method('publish')
            ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = array()) use (&$messages) {
                $messages[] = array($message, $routing_key, $flags, $attributes);
            }))
        ;

        $handler = new AmqpHandler($exchange, 'log');

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $expected = array(
            array(
                'message' => 'test',
                'context' => array(
                    'data' => array(),
                    'foo' => 34,
                ),
                'level' => 300,
                'level_name' => 'WARNING',
                'channel' => 'test',
                'extra' => array(),
            ),
            'warn.test',
            0,
            array(
                'delivery_mode' => 2,
                'content_type' => 'application/json',
            ),
        );

        $handler->handle($record);

        $this->assertCount(1, $messages);
        $messages[0][0] = json_decode($messages[0][0], true);
        unset($messages[0][0]['datetime']);
        $this->assertEquals($expected, $messages[0]);
    }

    public function testHandlePhpAmqpLib()
    {
        if (!class_exists('PhpAmqpLib\Connection\AMQPConnection')) {
            $this->markTestSkipped("php-amqplib not installed");
        }

        $messages = array();

        $exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', array('basic_publish', '__destruct'), array(), '', false);

        $exchange->expects($this->any())
            ->method('basic_publish')
            ->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) {
                $messages[] = array($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket);
            }))
        ;

        $handler = new AmqpHandler($exchange, 'log');

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $expected = array(
            array(
                'message' => 'test',
                'context' => array(
                    'data' => array(),
                    'foo' => 34,
                ),
                'level' => 300,
                'level_name' => 'WARNING',
                'channel' => 'test',
                'extra' => array(),
            ),
            'log',
            'warn.test',
            false,
            false,
            null,
            array(
                'delivery_mode' => 2,
                'content_type' => 'application/json',
            ),
        );

        $handler->handle($record);

        $this->assertCount(1, $messages);

        /* @var $msg AMQPMessage */
        $msg = $messages[0][0];
        $messages[0][0] = json_decode($msg->body, true);
        $messages[0][] = $msg->get_properties();
        unset($messages[0][0]['datetime']);

        $this->assertEquals($expected, $messages[0]);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\TestCase;

class MailHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\MailHandler::handleBatch
     */
    public function testHandleBatch()
    {
        $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $formatter->expects($this->once())
            ->method('formatBatch'); // Each record is formatted

        $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
        $handler->expects($this->once())
            ->method('send');
        $handler->expects($this->never())
            ->method('write'); // write is for individual records

        $handler->setFormatter($formatter);

        $handler->handleBatch($this->getMultipleRecords());
    }

    /**
     * @covers Monolog\Handler\MailHandler::handleBatch
     */
    public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel()
    {
        $records = array(
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
            $this->getRecord(Logger::INFO, 'information'),
        );

        $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
        $handler->expects($this->never())
            ->method('send');
        $handler->setLevel(Logger::ERROR);

        $handler->handleBatch($records);
    }

    /**
     * @covers Monolog\Handler\MailHandler::write
     */
    public function testHandle()
    {
        $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');

        $record = $this->getRecord();
        $records = array($record);
        $records[0]['formatted'] = '['.$record['datetime']->format('Y-m-d H:i:s').'] test.WARNING: test [] []'."\n";

        $handler->expects($this->once())
            ->method('send')
            ->with($records[0]['formatted'], $records);

        $handler->handle($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Gelf\Message;
use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter;

class GelfHandlerLegacyTest extends TestCase
{
    public function setUp()
    {
        if (!class_exists('Gelf\MessagePublisher') || !class_exists('Gelf\Message')) {
            $this->markTestSkipped("mlehner/gelf-php not installed");
        }

        require_once __DIR__ . '/GelfMockMessagePublisher.php';
    }

    /**
     * @covers Monolog\Handler\GelfHandler::__construct
     */
    public function testConstruct()
    {
        $handler = new GelfHandler($this->getMessagePublisher());
        $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler);
    }

    protected function getHandler($messagePublisher)
    {
        $handler = new GelfHandler($messagePublisher);

        return $handler;
    }

    protected function getMessagePublisher()
    {
        return new GelfMockMessagePublisher('localhost');
    }

    public function testDebug()
    {
        $messagePublisher = $this->getMessagePublisher();
        $handler = $this->getHandler($messagePublisher);

        $record = $this->getRecord(Logger::DEBUG, "A test debug message");
        $handler->handle($record);

        $this->assertEquals(7, $messagePublisher->lastMessage->getLevel());
        $this->assertEquals('test', $messagePublisher->lastMessage->getFacility());
        $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage());
        $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage());
    }

    public function testWarning()
    {
        $messagePublisher = $this->getMessagePublisher();
        $handler = $this->getHandler($messagePublisher);

        $record = $this->getRecord(Logger::WARNING, "A test warning message");
        $handler->handle($record);

        $this->assertEquals(4, $messagePublisher->lastMessage->getLevel());
        $this->assertEquals('test', $messagePublisher->lastMessage->getFacility());
        $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage());
        $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage());
    }

    public function testInjectedGelfMessageFormatter()
    {
        $messagePublisher = $this->getMessagePublisher();
        $handler = $this->getHandler($messagePublisher);

        $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX'));

        $record = $this->getRecord(Logger::WARNING, "A test warning message");
        $record['extra']['blarg'] = 'yep';
        $record['context']['from'] = 'logger';
        $handler->handle($record);

        $this->assertEquals('mysystem', $messagePublisher->lastMessage->getHost());
        $this->assertArrayHasKey('_EXTblarg', $messagePublisher->lastMessage->toArray());
        $this->assertArrayHasKey('_CTXfrom', $messagePublisher->lastMessage->toArray());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Processor\WebProcessor;

class AbstractProcessingHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\AbstractProcessingHandler::handle
     */
    public function testHandleLowerLevelMessage()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, true));
        $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\AbstractProcessingHandler::handle
     */
    public function testHandleBubbling()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, true));
        $this->assertFalse($handler->handle($this->getRecord()));
    }

    /**
     * @covers Monolog\Handler\AbstractProcessingHandler::handle
     */
    public function testHandleNotBubbling()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, false));
        $this->assertTrue($handler->handle($this->getRecord()));
    }

    /**
     * @covers Monolog\Handler\AbstractProcessingHandler::handle
     */
    public function testHandleIsFalseWhenNotHandled()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false));
        $this->assertTrue($handler->handle($this->getRecord()));
        $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\AbstractProcessingHandler::processRecord
     */
    public function testProcessRecord()
    {
        $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
        $handler->pushProcessor(new WebProcessor(array(
            'REQUEST_URI' => '',
            'REQUEST_METHOD' => '',
            'REMOTE_ADDR' => '',
            'SERVER_NAME' => '',
            'UNIQUE_ID' => '',
        )));
        $handledRecord = null;
        $handler->expects($this->once())
            ->method('write')
            ->will($this->returnCallback(function ($record) use (&$handledRecord) {
                $handledRecord = $record;
            }))
        ;
        $handler->handle($this->getRecord());
        $this->assertEquals(6, count($handledRecord['extra']));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;

function error_log()
{
    $GLOBALS['error_log'][] = func_get_args();
}

class ErrorLogHandlerTest extends TestCase
{
    protected function setUp()
    {
        $GLOBALS['error_log'] = array();
    }

    /**
     * @covers Monolog\Handler\ErrorLogHandler::__construct
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage The given message type "42" is not supported
     */
    public function testShouldNotAcceptAnInvalidTypeOnContructor()
    {
        new ErrorLogHandler(42);
    }

    /**
     * @covers Monolog\Handler\ErrorLogHandler::write
     */
    public function testShouldLogMessagesUsingErrorLogFuncion()
    {
        $type = ErrorLogHandler::OPERATING_SYSTEM;
        $handler = new ErrorLogHandler($type);
        $handler->setFormatter(new LineFormatter('%channel%.%level_name%: %message% %context% %extra%', null, true));
        $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz"));

        $this->assertSame("test.ERROR: Foo\nBar\r\n\r\nBaz [] []", $GLOBALS['error_log'][0][0]);
        $this->assertSame($GLOBALS['error_log'][0][1], $type);

        $handler = new ErrorLogHandler($type, Logger::DEBUG, true, true);
        $handler->setFormatter(new LineFormatter(null, null, true));
        $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz"));

        $this->assertStringMatchesFormat('[%s] test.ERROR: Foo', $GLOBALS['error_log'][1][0]);
        $this->assertSame($GLOBALS['error_log'][1][1], $type);

        $this->assertStringMatchesFormat('Bar', $GLOBALS['error_log'][2][0]);
        $this->assertSame($GLOBALS['error_log'][2][1], $type);

        $this->assertStringMatchesFormat('Baz [] []', $GLOBALS['error_log'][3][0]);
        $this->assertSame($GLOBALS['error_log'][3][1], $type);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class GroupHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\GroupHandler::__construct
     * @expectedException InvalidArgumentException
     */
    public function testConstructorOnlyTakesHandler()
    {
        new GroupHandler(array(new TestHandler(), "foo"));
    }

    /**
     * @covers Monolog\Handler\GroupHandler::__construct
     * @covers Monolog\Handler\GroupHandler::handle
     */
    public function testHandle()
    {
        $testHandlers = array(new TestHandler(), new TestHandler());
        $handler = new GroupHandler($testHandlers);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        foreach ($testHandlers as $test) {
            $this->assertTrue($test->hasDebugRecords());
            $this->assertTrue($test->hasInfoRecords());
            $this->assertTrue(count($test->getRecords()) === 2);
        }
    }

    /**
     * @covers Monolog\Handler\GroupHandler::handleBatch
     */
    public function testHandleBatch()
    {
        $testHandlers = array(new TestHandler(), new TestHandler());
        $handler = new GroupHandler($testHandlers);
        $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
        foreach ($testHandlers as $test) {
            $this->assertTrue($test->hasDebugRecords());
            $this->assertTrue($test->hasInfoRecords());
            $this->assertTrue(count($test->getRecords()) === 2);
        }
    }

    /**
     * @covers Monolog\Handler\GroupHandler::isHandling
     */
    public function testIsHandling()
    {
        $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING));
        $handler = new GroupHandler($testHandlers);
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR)));
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
    }

    /**
     * @covers Monolog\Handler\GroupHandler::handle
     */
    public function testHandleUsesProcessors()
    {
        $test = new TestHandler();
        $handler = new GroupHandler(array($test));
        $handler->pushProcessor(function ($record) {
            $record['extra']['foo'] = true;

            return $record;
        });
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\PsrHandler::handle
 */
class PsrHandlerTest extends TestCase
{
    public function logLevelProvider()
    {
        $levels = array();
        $monologLogger = new Logger('');

        foreach ($monologLogger->getLevels() as $levelName => $level) {
            $levels[] = array($levelName, $level);
        }

        return $levels;
    }

    /**
     * @dataProvider logLevelProvider
     */
    public function testHandlesAllLevels($levelName, $level)
    {
        $message = 'Hello, world! ' . $level;
        $context = array('foo' => 'bar', 'level' => $level);

        $psrLogger = $this->getMock('Psr\Log\NullLogger');
        $psrLogger->expects($this->once())
            ->method('log')
            ->with(strtolower($levelName), $message, $context);

        $handler = new PsrHandler($psrLogger);
        $handler->handle(array('level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;

/**
 * @covers Monolog\Handler\RotatingFileHandler
 */
class RotatingFileHandlerTest extends TestCase
{
    public function setUp()
    {
        $dir = __DIR__.'/Fixtures';
        chmod($dir, 0777);
        if (!is_writable($dir)) {
            $this->markTestSkipped($dir.' must be writeable to test the RotatingFileHandler.');
        }
    }

    public function testRotationCreatesNewFile()
    {
        touch(__DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot');

        $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord());

        $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
        $this->assertTrue(file_exists($log));
        $this->assertEquals('test', file_get_contents($log));
    }

    /**
     * @dataProvider rotationTests
     */
    public function testRotation($createFile)
    {
        touch($old1 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot');
        touch($old2 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 2).'.rot');
        touch($old3 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 3).'.rot');
        touch($old4 = __DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400 * 4).'.rot');

        $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';

        if ($createFile) {
            touch($log);
        }

        $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord());

        $handler->close();

        $this->assertTrue(file_exists($log));
        $this->assertTrue(file_exists($old1));
        $this->assertEquals($createFile, file_exists($old2));
        $this->assertEquals($createFile, file_exists($old3));
        $this->assertEquals($createFile, file_exists($old4));
        $this->assertEquals('test', file_get_contents($log));
    }

    public function rotationTests()
    {
        return array(
            'Rotation is triggered when the file of the current day is not present'
                => array(true),
            'Rotation is not triggered when the file is already present'
                => array(false),
        );
    }

    public function testReuseCurrentFile()
    {
        $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
        file_put_contents($log, "foo");
        $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord());
        $this->assertEquals('footest', file_get_contents($log));
    }

    public function tearDown()
    {
        foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
            unlink($file);
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use InvalidArgumentException;

function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
{
    $GLOBALS['mail'][] = func_get_args();
}

class NativeMailerHandlerTest extends TestCase
{
    protected function setUp()
    {
        $GLOBALS['mail'] = array();
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructorHeaderInjection()
    {
        $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', "receiver@example.org\r\nFrom: faked@attacker.org");
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testSetterHeaderInjection()
    {
        $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
        $mailer->addHeader("Content-Type: text/html\r\nFrom: faked@attacker.org");
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testSetterArrayHeaderInjection()
    {
        $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
        $mailer->addHeader(array("Content-Type: text/html\r\nFrom: faked@attacker.org"));
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testSetterContentTypeInjection()
    {
        $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
        $mailer->setContentType("text/html\r\nFrom: faked@attacker.org");
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testSetterEncodingInjection()
    {
        $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
        $mailer->setEncoding("utf-8\r\nFrom: faked@attacker.org");
    }

    public function testSend()
    {
        $to = 'spammer@example.org';
        $subject = 'dear victim';
        $from = 'receiver@example.org';

        $mailer = new NativeMailerHandler($to, $subject, $from);
        $mailer->handleBatch(array());

        // batch is empty, nothing sent
        $this->assertEmpty($GLOBALS['mail']);

        // non-empty batch
        $mailer->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz"));
        $this->assertNotEmpty($GLOBALS['mail']);
        $this->assertInternalType('array', $GLOBALS['mail']);
        $this->assertArrayHasKey('0', $GLOBALS['mail']);
        $params = $GLOBALS['mail'][0];
        $this->assertCount(5, $params);
        $this->assertSame($to, $params[0]);
        $this->assertSame($subject, $params[1]);
        $this->assertStringEndsWith(" test.ERROR: Foo Bar  Baz [] []\n", $params[2]);
        $this->assertSame("From: $from\r\nContent-type: text/plain; charset=utf-8\r\n", $params[3]);
        $this->assertSame('', $params[4]);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

/**
 * @requires extension sockets
 */
class SyslogUdpHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException UnexpectedValueException
     */
    public function testWeValidateFacilities()
    {
        $handler = new SyslogUdpHandler("ip", null, "invalidFacility");
    }

    public function testWeSplitIntoLines()
    {
        $handler = new SyslogUdpHandler("127.0.0.1", 514, "authpriv");
        $handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());

        $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol'));
        $socket->expects($this->at(0))
            ->method('write')
            ->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 ");
        $socket->expects($this->at(1))
            ->method('write')
            ->with("hej", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 ");

        $handler->setSocket($socket);

        $handler->handle($this->getRecordWithMessage("hej\nlol"));
    }

    protected function getRecordWithMessage($msg)
    {
        return array('message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => array(), 'channel' => 'lol');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class MongoDBHandlerTest extends TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructorShouldThrowExceptionForInvalidMongo()
    {
        new MongoDBHandler(new \stdClass(), 'DB', 'Collection');
    }

    public function testHandle()
    {
        $mongo = $this->getMock('Mongo', array('selectCollection'), array(), '', false);
        $collection = $this->getMock('stdClass', array('save'));

        $mongo->expects($this->once())
            ->method('selectCollection')
            ->with('DB', 'Collection')
            ->will($this->returnValue($collection));

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $expected = array(
            'message' => 'test',
            'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34),
            'level' => Logger::WARNING,
            'level_name' => 'WARNING',
            'channel' => 'test',
            'datetime' => $record['datetime']->format('Y-m-d H:i:s'),
            'extra' => array(),
        );

        $collection->expects($this->once())
            ->method('save')
            ->with($expected);

        $handler = new MongoDBHandler($mongo, 'DB', 'Collection');
        $handler->handle($record);
    }
}

if (!class_exists('Mongo')) {
    class Mongo
    {
        public function selectCollection()
        {
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

class SyslogHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Monolog\Handler\SyslogHandler::__construct
     */
    public function testConstruct()
    {
        $handler = new SyslogHandler('test');
        $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);

        $handler = new SyslogHandler('test', LOG_USER);
        $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);

        $handler = new SyslogHandler('test', 'user');
        $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);

        $handler = new SyslogHandler('test', LOG_USER, Logger::DEBUG, true, LOG_PERROR);
        $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);
    }

    /**
     * @covers Monolog\Handler\SyslogHandler::__construct
     */
    public function testConstructInvalidFacility()
    {
        $this->setExpectedException('UnexpectedValueException');
        $handler = new SyslogHandler('test', 'unknown');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @author Greg Kedzierski <greg@gregkedzierski.com>
 * @see    https://api.slack.com/
 */
class SlackHandlerTest extends TestCase
{
    /**
     * @var resource
     */
    private $res;

    /**
     * @var SlackHandler
     */
    private $handler;

    public function setUp()
    {
        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('This test requires openssl to run');
        }
    }

    public function testWriteHeader()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/api\/chat.postMessage HTTP\/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
    }

    public function testWriteContent()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/token=myToken&channel=channel1&username=Monolog&text=&attachments=.*$/', $content);
    }

    public function testWriteContentWithEmoji()
    {
        $this->createHandler('myToken', 'channel1', 'Monolog', true, 'alien');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/icon_emoji=%3Aalien%3A$/', $content);
    }

    /**
     * @dataProvider provideLevelColors
     */
    public function testWriteContentWithColors($level, $expectedColor)
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord($level, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/color%22%3A%22'.$expectedColor.'/', $content);
    }

    public function testWriteContentWithPlainTextMessage()
    {
        $this->createHandler('myToken', 'channel1', 'Monolog', false);
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/text=test1/', $content);
    }

    public function provideLevelColors()
    {
        return array(
            array(Logger::DEBUG,    '%23e3e4e6'),   // escaped #e3e4e6
            array(Logger::INFO,     'good'),
            array(Logger::NOTICE,   'good'),
            array(Logger::WARNING,  'warning'),
            array(Logger::ERROR,    'danger'),
            array(Logger::CRITICAL, 'danger'),
            array(Logger::ALERT,    'danger'),
            array(Logger::EMERGENCY,'danger'),
        );
    }

    private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)
    {
        $constructorArgs = array($token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra);
        $this->res = fopen('php://memory', 'a');
        $this->handler = $this->getMock(
            '\Monolog\Handler\SlackHandler',
            array('fsockopen', 'streamSetTimeout', 'closeSocket'),
            $constructorArgs
        );

        $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($this->handler, 'localhost:1234');

        $this->handler->expects($this->any())
            ->method('fsockopen')
            ->will($this->returnValue($this->res));
        $this->handler->expects($this->any())
            ->method('streamSetTimeout')
            ->will($this->returnValue(true));
        $this->handler->expects($this->any())
            ->method('closeSocket')
            ->will($this->returnValue(true));

        $this->handler->setFormatter($this->getIdentityFormatter());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @author Rafael Dohms <rafael@doh.ms>
 * @see    https://www.hipchat.com/docs/api
 */
class HipChatHandlerTest extends TestCase
{
    private $res;
    /** @var  HipChatHandler */
    private $handler;

    public function testWriteHeader()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: api.hipchat.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    public function testWriteCustomHostHeader()
    {
        $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    public function testWriteV2()
    {
        $this->createHandler('myToken', 'room1', 'Monolog', false, 'hipchat.foo.bar', 'v2');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    public function testWriteV2Notify()
    {
        $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar', 'v2');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    public function testRoomSpaces()
    {
        $this->createHandler('myToken', 'room name', 'Monolog', false, 'hipchat.foo.bar', 'v2');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v2\/room\/room%20name\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    /**
     * @depends testWriteHeader
     */
    public function testWriteContent($content)
    {
        $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content);
    }

    public function testWriteContentV1WithoutName()
    {
        $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v1');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=$/', $content);

        return $content;
    }

    /**
     * @depends testWriteCustomHostHeader
     */
    public function testWriteContentNotify($content)
    {
        $this->assertRegexp('/notify=1&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content);
    }

    /**
     * @depends testWriteV2
     */
    public function testWriteContentV2($content)
    {
        $this->assertRegexp('/notify=false&message=test1&message_format=text&color=red&from=Monolog$/', $content);
    }

    /**
     * @depends testWriteV2Notify
     */
    public function testWriteContentV2Notify($content)
    {
        $this->assertRegexp('/notify=true&message=test1&message_format=text&color=red&from=Monolog$/', $content);
    }

    public function testWriteContentV2WithoutName()
    {
        $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v2');
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/notify=false&message=test1&message_format=text&color=red$/', $content);

        return $content;
    }

    public function testWriteWithComplexMessage()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Backup of database "example" finished in 16 minutes.'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/message=Backup\+of\+database\+%22example%22\+finished\+in\+16\+minutes\./', $content);
    }

    /**
     * @dataProvider provideLevelColors
     */
    public function testWriteWithErrorLevelsAndColors($level, $expectedColor)
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord($level, 'Backup of database "example" finished in 16 minutes.'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/color='.$expectedColor.'/', $content);
    }

    public function provideLevelColors()
    {
        return array(
            array(Logger::DEBUG,    'gray'),
            array(Logger::INFO,     'green'),
            array(Logger::WARNING,  'yellow'),
            array(Logger::ERROR,    'red'),
            array(Logger::CRITICAL, 'red'),
            array(Logger::ALERT,    'red'),
            array(Logger::EMERGENCY,'red'),
            array(Logger::NOTICE,   'green'),
        );
    }

    /**
     * @dataProvider provideBatchRecords
     */
    public function testHandleBatch($records, $expectedColor)
    {
        $this->createHandler();

        $this->handler->handleBatch($records);

        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/color='.$expectedColor.'/', $content);
    }

    public function provideBatchRecords()
    {
        return array(
            array(
                array(
                    array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()),
                    array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
                    array('level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTime()),
                ),
                'red',
            ),
            array(
                array(
                    array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()),
                    array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
                ),
                'yellow',
            ),
            array(
                array(
                    array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()),
                    array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
                ),
                'green',
            ),
            array(
                array(
                    array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()),
                ),
                'gray',
            ),
        );
    }

    private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1')
    {
        $constructorArgs = array($token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version);
        $this->res = fopen('php://memory', 'a');
        $this->handler = $this->getMock(
            '\Monolog\Handler\HipChatHandler',
            array('fsockopen', 'streamSetTimeout', 'closeSocket'),
            $constructorArgs
        );

        $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($this->handler, 'localhost:1234');

        $this->handler->expects($this->any())
            ->method('fsockopen')
            ->will($this->returnValue($this->res));
        $this->handler->expects($this->any())
            ->method('streamSetTimeout')
            ->will($this->returnValue(true));
        $this->handler->expects($this->any())
            ->method('closeSocket')
            ->will($this->returnValue(true));

        $this->handler->setFormatter($this->getIdentityFormatter());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testCreateWithTooLongName()
    {
        $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere');
    }

    public function testCreateWithTooLongNameV2()
    {
        // creating a handler with too long of a name but using the v2 api doesn't matter.
        $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere', false, Logger::CRITICAL, true, true, 'test', 'api.hipchat.com', 'v2');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class DoctrineCouchDBHandlerTest extends TestCase
{
    protected function setup()
    {
        if (!class_exists('Doctrine\CouchDB\CouchDBClient')) {
            $this->markTestSkipped('The "doctrine/couchdb" package is not installed');
        }
    }

    public function testHandle()
    {
        $client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient')
            ->setMethods(array('postDocument'))
            ->disableOriginalConstructor()
            ->getMock();

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $expected = array(
            'message' => 'test',
            'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34),
            'level' => Logger::WARNING,
            'level_name' => 'WARNING',
            'channel' => 'test',
            'datetime' => $record['datetime']->format('Y-m-d H:i:s'),
            'extra' => array(),
        );

        $client->expects($this->once())
            ->method('postDocument')
            ->with($expected);

        $handler = new DoctrineCouchDBHandler($client);
        $handler->handle($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\FirePHPHandler
 */
class FirePHPHandlerTest extends TestCase
{
    public function setUp()
    {
        TestFirePHPHandler::reset();
        $_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; FirePHP/1.0';
    }

    public function testHeaders()
    {
        $handler = new TestFirePHPHandler;
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING));

        $expected = array(
            'X-Wf-Protocol-1'    => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
            'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
            'X-Wf-1-Plugin-1'    => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
            'X-Wf-1-1-1-1'       => 'test',
            'X-Wf-1-1-1-2'       => 'test',
        );

        $this->assertEquals($expected, $handler->getHeaders());
    }

    public function testConcurrentHandlers()
    {
        $handler = new TestFirePHPHandler;
        $handler->setFormatter($this->getIdentityFormatter());
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::WARNING));

        $handler2 = new TestFirePHPHandler;
        $handler2->setFormatter($this->getIdentityFormatter());
        $handler2->handle($this->getRecord(Logger::DEBUG));
        $handler2->handle($this->getRecord(Logger::WARNING));

        $expected = array(
            'X-Wf-Protocol-1'    => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
            'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
            'X-Wf-1-Plugin-1'    => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
            'X-Wf-1-1-1-1'       => 'test',
            'X-Wf-1-1-1-2'       => 'test',
        );

        $expected2 = array(
            'X-Wf-1-1-1-3'       => 'test',
            'X-Wf-1-1-1-4'       => 'test',
        );

        $this->assertEquals($expected, $handler->getHeaders());
        $this->assertEquals($expected2, $handler2->getHeaders());
    }
}

class TestFirePHPHandler extends FirePHPHandler
{
    protected $headers = array();

    public static function reset()
    {
        self::$initialized = false;
        self::$sendHeaders = true;
        self::$messageIndex = 1;
    }

    protected function sendHeader($header, $content)
    {
        $this->headers[$header] = $content;
    }

    public function getHeaders()
    {
        return $this->headers;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\TestHandler
 */
class TestHandlerTest extends TestCase
{
    /**
     * @dataProvider methodProvider
     */
    public function testHandler($method, $level)
    {
        $handler = new TestHandler;
        $record = $this->getRecord($level, 'test'.$method);
        $this->assertFalse($handler->{'has'.$method}($record), 'has'.$method);
        $this->assertFalse($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
        $this->assertFalse($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
            return true;
        }), 'has'.$method.'ThatPasses');
        $this->assertFalse($handler->{'has'.$method.'ThatMatches'}('/test\w+/'));
        $this->assertFalse($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records');
        $handler->handle($record);

        $this->assertFalse($handler->{'has'.$method}('bar'), 'has'.$method);
        $this->assertTrue($handler->{'has'.$method}($record), 'has'.$method);
        $this->assertTrue($handler->{'has'.$method}('test'.$method), 'has'.$method);
        $this->assertTrue($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
        $this->assertTrue($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
            return true;
        }), 'has'.$method.'ThatPasses');
        $this->assertTrue($handler->{'has'.$method.'ThatMatches'}('/test\w+/'));
        $this->assertTrue($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records');

        $records = $handler->getRecords();
        unset($records[0]['formatted']);
        $this->assertEquals(array($record), $records);
    }

    public function methodProvider()
    {
        return array(
            array('Emergency', Logger::EMERGENCY),
            array('Alert'    , Logger::ALERT),
            array('Critical' , Logger::CRITICAL),
            array('Error'    , Logger::ERROR),
            array('Warning'  , Logger::WARNING),
            array('Info'     , Logger::INFO),
            array('Notice'   , Logger::NOTICE),
            array('Debug'    , Logger::DEBUG),
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class BufferHandlerTest extends TestCase
{
    private $shutdownCheckHandler;

    /**
     * @covers Monolog\Handler\BufferHandler::__construct
     * @covers Monolog\Handler\BufferHandler::handle
     * @covers Monolog\Handler\BufferHandler::close
     */
    public function testHandleBuffers()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertFalse($test->hasDebugRecords());
        $this->assertFalse($test->hasInfoRecords());
        $handler->close();
        $this->assertTrue($test->hasInfoRecords());
        $this->assertTrue(count($test->getRecords()) === 2);
    }

    /**
     * @covers Monolog\Handler\BufferHandler::close
     * @covers Monolog\Handler\BufferHandler::flush
     */
    public function testPropagatesRecordsAtEndOfRequest()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test);
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->shutdownCheckHandler = $test;
        register_shutdown_function(array($this, 'checkPropagation'));
    }

    public function checkPropagation()
    {
        if (!$this->shutdownCheckHandler->hasWarningRecords() || !$this->shutdownCheckHandler->hasDebugRecords()) {
            echo '!!! BufferHandlerTest::testPropagatesRecordsAtEndOfRequest failed to verify that the messages have been propagated' . PHP_EOL;
            exit(1);
        }
    }

    /**
     * @covers Monolog\Handler\BufferHandler::handle
     */
    public function testHandleBufferLimit()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test, 2);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->close();
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasInfoRecords());
        $this->assertFalse($test->hasDebugRecords());
    }

    /**
     * @covers Monolog\Handler\BufferHandler::handle
     */
    public function testHandleBufferLimitWithFlushOnOverflow()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test, 3, Logger::DEBUG, true, true);

        // send two records
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->assertFalse($test->hasDebugRecords());
        $this->assertCount(0, $test->getRecords());

        // overflow
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertTrue($test->hasDebugRecords());
        $this->assertCount(3, $test->getRecords());

        // should buffer again
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertCount(3, $test->getRecords());

        $handler->close();
        $this->assertCount(5, $test->getRecords());
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasInfoRecords());
    }

    /**
     * @covers Monolog\Handler\BufferHandler::handle
     */
    public function testHandleLevel()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test, 0, Logger::INFO);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->close();
        $this->assertTrue($test->hasWarningRecords());
        $this->assertTrue($test->hasInfoRecords());
        $this->assertFalse($test->hasDebugRecords());
    }

    /**
     * @covers Monolog\Handler\BufferHandler::flush
     */
    public function testFlush()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test, 0);
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $handler->flush();
        $this->assertTrue($test->hasInfoRecords());
        $this->assertTrue($test->hasDebugRecords());
        $this->assertFalse($test->hasWarningRecords());
    }

    /**
     * @covers Monolog\Handler\BufferHandler::handle
     */
    public function testHandleUsesProcessors()
    {
        $test = new TestHandler();
        $handler = new BufferHandler($test);
        $handler->pushProcessor(function ($record) {
            $record['extra']['foo'] = true;

            return $record;
        });
        $handler->handle($this->getRecord(Logger::WARNING));
        $handler->flush();
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;

class RedisHandlerTest extends TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructorShouldThrowExceptionForInvalidRedis()
    {
        new RedisHandler(new \stdClass(), 'key');
    }

    public function testConstructorShouldWorkWithPredis()
    {
        $redis = $this->getMock('Predis\Client');
        $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
    }

    public function testConstructorShouldWorkWithRedis()
    {
        $redis = $this->getMock('Redis');
        $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
    }

    public function testPredisHandle()
    {
        $redis = $this->getMock('Predis\Client', array('rpush'));

        // Predis\Client uses rpush
        $redis->expects($this->once())
            ->method('rpush')
            ->with('key', 'test');

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $handler = new RedisHandler($redis, 'key');
        $handler->setFormatter(new LineFormatter("%message%"));
        $handler->handle($record);
    }

    public function testRedisHandle()
    {
        $redis = $this->getMock('Redis', array('rpush'));

        // Redis uses rPush
        $redis->expects($this->once())
            ->method('rPush')
            ->with('key', 'test');

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $handler = new RedisHandler($redis, 'key');
        $handler->setFormatter(new LineFormatter("%message%"));
        $handler->handle($record);
    }

    public function testRedisHandleCapped()
    {
        $redis = $this->getMock('Redis', array('multi', 'rpush', 'ltrim', 'exec'));

        // Redis uses multi
        $redis->expects($this->once())
            ->method('multi')
            ->will($this->returnSelf());

        $redis->expects($this->once())
            ->method('rpush')
            ->will($this->returnSelf());

        $redis->expects($this->once())
            ->method('ltrim')
            ->will($this->returnSelf());

        $redis->expects($this->once())
            ->method('exec')
            ->will($this->returnSelf());

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
        $handler->setFormatter(new LineFormatter("%message%"));
        $handler->handle($record);
    }

    public function testPredisHandleCapped()
    {
        $redis = $this->getMock('Predis\Client', array('transaction'));

        $redisTransaction = $this->getMock('Predis\Client', array('rpush', 'ltrim'));

        $redisTransaction->expects($this->once())
            ->method('rpush')
            ->will($this->returnSelf());

        $redisTransaction->expects($this->once())
            ->method('ltrim')
            ->will($this->returnSelf());

        // Redis uses multi
        $redis->expects($this->once())
            ->method('transaction')
            ->will($this->returnCallback(function ($cb) use ($redisTransaction) {
                $cb($redisTransaction);
            }));

        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
        $handler->setFormatter(new LineFormatter("%message%"));
        $handler->handle($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Gelf\MessagePublisher;
use Gelf\Message;

class GelfMockMessagePublisher extends MessagePublisher
{
    public function publish(Message $message)
    {
        $this->lastMessage = $message;
    }

    public $lastMessage = null;
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FlowdockFormatter;
use Monolog\TestCase;
use Monolog\Logger;

/**
 * @author Dominik Liebler <liebler.dominik@gmail.com>
 * @see    https://www.hipchat.com/docs/api
 */
class FlowdockHandlerTest extends TestCase
{
    /**
     * @var resource
     */
    private $res;

    /**
     * @var FlowdockHandler
     */
    private $handler;

    public function setUp()
    {
        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('This test requires openssl to run');
        }
    }

    public function testWriteHeader()
    {
        $this->createHandler();
        $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
        fseek($this->res, 0);
        $content = fread($this->res, 1024);

        $this->assertRegexp('/POST \/v1\/messages\/team_inbox\/.* HTTP\/1.1\\r\\nHost: api.flowdock.com\\r\\nContent-Type: application\/json\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);

        return $content;
    }

    /**
     * @depends testWriteHeader
     */
    public function testWriteContent($content)
    {
        $this->assertRegexp('/"source":"test_source"/', $content);
        $this->assertRegexp('/"from_address":"source@test\.com"/', $content);
    }

    private function createHandler($token = 'myToken')
    {
        $constructorArgs = array($token, Logger::DEBUG);
        $this->res = fopen('php://memory', 'a');
        $this->handler = $this->getMock(
            '\Monolog\Handler\FlowdockHandler',
            array('fsockopen', 'streamSetTimeout', 'closeSocket'),
            $constructorArgs
        );

        $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($this->handler, 'localhost:1234');

        $this->handler->expects($this->any())
            ->method('fsockopen')
            ->will($this->returnValue($this->res));
        $this->handler->expects($this->any())
            ->method('streamSetTimeout')
            ->will($this->returnValue(true));
        $this->handler->expects($this->any())
            ->method('closeSocket')
            ->will($this->returnValue(true));

        $this->handler->setFormatter(new FlowdockFormatter('test_source', 'source@test.com'));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Handler\SyslogUdp\UdpSocket;

/**
 * @requires extension sockets
 */
class UdpSocketTest extends TestCase
{
    public function testWeDoNotTruncateShortMessages()
    {
        $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol'));

        $socket->expects($this->at(0))
            ->method('send')
            ->with("HEADER: The quick brown fox jumps over the lazy dog");

        $socket->write("The quick brown fox jumps over the lazy dog", "HEADER: ");
    }

    public function testLongMessagesAreTruncated()
    {
        $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol'));

        $truncatedString = str_repeat("derp", 16254).'d';

        $socket->expects($this->exactly(1))
            ->method('send')
            ->with("HEADER" . $truncatedString);

        $longString = str_repeat("derp", 20000);

        $socket->write($longString, "HEADER");
    }

    public function testDoubleCloseDoesNotError()
    {
        $socket = new UdpSocket('127.0.0.1', 514);
        $socket->close();
        $socket->close();
    }

    /**
     * @expectedException LogicException
     */
    public function testWriteAfterCloseErrors()
    {
        $socket = new UdpSocket('127.0.0.1', 514);
        $socket->close();
        $socket->write('foo', "HEADER");
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\TestCase;

class SwiftMailerHandlerTest extends TestCase
{
    /** @var \Swift_Mailer|\PHPUnit_Framework_MockObject_MockObject */
    private $mailer;

    public function setUp()
    {
        $this->mailer = $this
            ->getMockBuilder('Swift_Mailer')
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testMessageCreationIsLazyWhenUsingCallback()
    {
        $this->mailer->expects($this->never())
            ->method('send');

        $callback = function () {
            throw new \RuntimeException('Swift_Message creation callback should not have been called in this test');
        };
        $handler = new SwiftMailerHandler($this->mailer, $callback);

        $records = array(
            $this->getRecord(Logger::DEBUG),
            $this->getRecord(Logger::INFO),
        );
        $handler->handleBatch($records);
    }

    public function testMessageCanBeCustomizedGivenLoggedData()
    {
        // Wire Mailer to expect a specific Swift_Message with a customized Subject
        $expectedMessage = new \Swift_Message();
        $this->mailer->expects($this->once())
            ->method('send')
            ->with($this->callback(function ($value) use ($expectedMessage) {
                return $value instanceof \Swift_Message
                    && $value->getSubject() === 'Emergency'
                    && $value === $expectedMessage;
            }));

        // Callback dynamically changes subject based on number of logged records
        $callback = function ($content, array $records) use ($expectedMessage) {
            $subject = count($records) > 0 ? 'Emergency' : 'Normal';
            $expectedMessage->setSubject($subject);

            return $expectedMessage;
        };
        $handler = new SwiftMailerHandler($this->mailer, $callback);

        // Logging 1 record makes this an Emergency
        $records = array(
            $this->getRecord(Logger::EMERGENCY),
        );
        $handler->handleBatch($records);
    }

    public function testMessageHaveUniqueId()
    {
        $messageTemplate = \Swift_Message::newInstance();
        $handler = new SwiftMailerHandler($this->mailer, $messageTemplate);

        $method = new \ReflectionMethod('Monolog\Handler\SwiftMailerHandler', 'buildMessage');
        $method->setAccessible(true);
        $method->invokeArgs($handler, array($messageTemplate, array()));

        $builtMessage1 = $method->invoke($handler, $messageTemplate, array());
        $builtMessage2 = $method->invoke($handler, $messageTemplate, array());

        $this->assertFalse($builtMessage1->getId() === $builtMessage2->getId(), 'Two different messages have the same id');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Raven_Client;

class MockRavenClient extends Raven_Client
{
    public function capture($data, $stack, $vars = null)
    {
        $data = array_merge($this->get_user_data(), $data);
        $this->lastData = $data;
        $this->lastStack = $stack;
    }

    public $lastData;
    public $lastStack;
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\TestCase;

class FilterHandlerTest extends TestCase
{
    /**
     * @covers Monolog\Handler\FilterHandler::isHandling
     */
    public function testIsHandling()
    {
        $test    = new TestHandler();
        $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE);
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::INFO)));
        $this->assertTrue($handler->isHandling($this->getRecord(Logger::NOTICE)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::WARNING)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::ERROR)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::CRITICAL)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::ALERT)));
        $this->assertFalse($handler->isHandling($this->getRecord(Logger::EMERGENCY)));
    }

    /**
     * @covers Monolog\Handler\FilterHandler::handle
     * @covers Monolog\Handler\FilterHandler::setAcceptedLevels
     * @covers Monolog\Handler\FilterHandler::isHandling
     */
    public function testHandleProcessOnlyNeededLevels()
    {
        $test    = new TestHandler();
        $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE);

        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->assertFalse($test->hasDebugRecords());

        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertTrue($test->hasInfoRecords());
        $handler->handle($this->getRecord(Logger::NOTICE));
        $this->assertTrue($test->hasNoticeRecords());

        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertFalse($test->hasWarningRecords());
        $handler->handle($this->getRecord(Logger::ERROR));
        $this->assertFalse($test->hasErrorRecords());
        $handler->handle($this->getRecord(Logger::CRITICAL));
        $this->assertFalse($test->hasCriticalRecords());
        $handler->handle($this->getRecord(Logger::ALERT));
        $this->assertFalse($test->hasAlertRecords());
        $handler->handle($this->getRecord(Logger::EMERGENCY));
        $this->assertFalse($test->hasEmergencyRecords());

        $test    = new TestHandler();
        $handler = new FilterHandler($test, array(Logger::INFO, Logger::ERROR));

        $handler->handle($this->getRecord(Logger::DEBUG));
        $this->assertFalse($test->hasDebugRecords());
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertTrue($test->hasInfoRecords());
        $handler->handle($this->getRecord(Logger::NOTICE));
        $this->assertFalse($test->hasNoticeRecords());
        $handler->handle($this->getRecord(Logger::ERROR));
        $this->assertTrue($test->hasErrorRecords());
        $handler->handle($this->getRecord(Logger::CRITICAL));
        $this->assertFalse($test->hasCriticalRecords());
    }

    /**
     * @covers Monolog\Handler\FilterHandler::setAcceptedLevels
     * @covers Monolog\Handler\FilterHandler::getAcceptedLevels
     */
    public function testAcceptedLevelApi()
    {
        $test    = new TestHandler();
        $handler = new FilterHandler($test);

        $levels = array(Logger::INFO, Logger::ERROR);
        $handler->setAcceptedLevels($levels);
        $this->assertSame($levels, $handler->getAcceptedLevels());

        $handler->setAcceptedLevels(array('info', 'error'));
        $this->assertSame($levels, $handler->getAcceptedLevels());

        $levels = array(Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY);
        $handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY);
        $this->assertSame($levels, $handler->getAcceptedLevels());

        $handler->setAcceptedLevels('critical', 'emergency');
        $this->assertSame($levels, $handler->getAcceptedLevels());
    }

    /**
     * @covers Monolog\Handler\FilterHandler::handle
     */
    public function testHandleUsesProcessors()
    {
        $test    = new TestHandler();
        $handler = new FilterHandler($test, Logger::DEBUG, Logger::EMERGENCY);
        $handler->pushProcessor(
            function ($record) {
                $record['extra']['foo'] = true;

                return $record;
            }
        );
        $handler->handle($this->getRecord(Logger::WARNING));
        $this->assertTrue($test->hasWarningRecords());
        $records = $test->getRecords();
        $this->assertTrue($records[0]['extra']['foo']);
    }

    /**
     * @covers Monolog\Handler\FilterHandler::handle
     */
    public function testHandleRespectsBubble()
    {
        $test = new TestHandler();

        $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, false);
        $this->assertTrue($handler->handle($this->getRecord(Logger::INFO)));
        $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING)));

        $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, true);
        $this->assertFalse($handler->handle($this->getRecord(Logger::INFO)));
        $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING)));
    }

    /**
     * @covers Monolog\Handler\FilterHandler::handle
     */
    public function testHandleWithCallback()
    {
        $test    = new TestHandler();
        $handler = new FilterHandler(
            function ($record, $handler) use ($test) {
                return $test;
            }, Logger::INFO, Logger::NOTICE, false
        );
        $handler->handle($this->getRecord(Logger::DEBUG));
        $handler->handle($this->getRecord(Logger::INFO));
        $this->assertFalse($test->hasDebugRecords());
        $this->assertTrue($test->hasInfoRecords());
    }

    /**
     * @covers Monolog\Handler\FilterHandler::handle
     * @expectedException \RuntimeException
     */
    public function testHandleWithBadCallbackThrowsException()
    {
        $handler = new FilterHandler(
            function ($record, $handler) {
                return 'foo';
            }
        );
        $handler->handle($this->getRecord(Logger::WARNING));
    }
}
<?php
/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;

class ZendMonitorHandlerTest extends TestCase
{
    protected $zendMonitorHandler;

    public function setUp()
    {
        if (!function_exists('zend_monitor_custom_event')) {
            $this->markTestSkipped('ZendServer is not installed');
        }
    }

    /**
     * @covers  Monolog\Handler\ZendMonitorHandler::write
     */
    public function testWrite()
    {
        $record = $this->getRecord();
        $formatterResult = array(
            'message' => $record['message'],
        );

        $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler')
            ->setMethods(array('writeZendMonitorCustomEvent', 'getDefaultFormatter'))
            ->getMock();

        $formatterMock = $this->getMockBuilder('Monolog\Formatter\NormalizerFormatter')
            ->disableOriginalConstructor()
            ->getMock();

        $formatterMock->expects($this->once())
            ->method('format')
            ->will($this->returnValue($formatterResult));

        $zendMonitor->expects($this->once())
            ->method('getDefaultFormatter')
            ->will($this->returnValue($formatterMock));

        $levelMap = $zendMonitor->getLevelMap();

        $zendMonitor->expects($this->once())
            ->method('writeZendMonitorCustomEvent')
            ->with($levelMap[$record['level']], $record['message'], $formatterResult);

        $zendMonitor->handle($record);
    }

    /**
     * @covers Monolog\Handler\ZendMonitorHandler::getDefaultFormatter
     */
    public function testGetDefaultFormatterReturnsNormalizerFormatter()
    {
        $zendMonitor = new ZendMonitorHandler();
        $this->assertInstanceOf('Monolog\Formatter\NormalizerFormatter', $zendMonitor->getDefaultFormatter());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\BrowserConsoleHandlerTest
 */
class BrowserConsoleHandlerTest extends TestCase
{
    protected function setUp()
    {
        BrowserConsoleHandler::reset();
    }

    protected function generateScript()
    {
        $reflMethod = new \ReflectionMethod('Monolog\Handler\BrowserConsoleHandler', 'generateScript');
        $reflMethod->setAccessible(true);

        return $reflMethod->invoke(null);
    }

    public function testStyling()
    {
        $handler = new BrowserConsoleHandler();
        $handler->setFormatter($this->getIdentityFormatter());

        $handler->handle($this->getRecord(Logger::DEBUG, 'foo[[bar]]{color: red}'));

        $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.log("%cfoo%cbar%c", "font-weight: normal", "color: red", "font-weight: normal");
}})(console);
EOF;

        $this->assertEquals($expected, $this->generateScript());
    }

    public function testEscaping()
    {
        $handler = new BrowserConsoleHandler();
        $handler->setFormatter($this->getIdentityFormatter());

        $handler->handle($this->getRecord(Logger::DEBUG, "[foo] [[\"bar\n[baz]\"]]{color: red}"));

        $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.log("%c[foo] %c\"bar\\n[baz]\"%c", "font-weight: normal", "color: red", "font-weight: normal");
}})(console);
EOF;

        $this->assertEquals($expected, $this->generateScript());
    }

    public function testAutolabel()
    {
        $handler = new BrowserConsoleHandler();
        $handler->setFormatter($this->getIdentityFormatter());

        $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}'));
        $handler->handle($this->getRecord(Logger::DEBUG, '[[bar]]{macro: autolabel}'));
        $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}'));

        $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.log("%c%cfoo%c", "font-weight: normal", "background-color: blue; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
c.log("%c%cbar%c", "font-weight: normal", "background-color: green; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
c.log("%c%cfoo%c", "font-weight: normal", "background-color: blue; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
}})(console);
EOF;

        $this->assertEquals($expected, $this->generateScript());
    }

    public function testContext()
    {
        $handler = new BrowserConsoleHandler();
        $handler->setFormatter($this->getIdentityFormatter());

        $handler->handle($this->getRecord(Logger::DEBUG, 'test', array('foo' => 'bar')));

        $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.groupCollapsed("%ctest", "font-weight: normal");
c.log("%c%s", "font-weight: bold", "Context");
c.log("%s: %o", "foo", "bar");
c.groupEnd();
}})(console);
EOF;

        $this->assertEquals($expected, $this->generateScript());
    }

    public function testConcurrentHandlers()
    {
        $handler1 = new BrowserConsoleHandler();
        $handler1->setFormatter($this->getIdentityFormatter());

        $handler2 = new BrowserConsoleHandler();
        $handler2->setFormatter($this->getIdentityFormatter());

        $handler1->handle($this->getRecord(Logger::DEBUG, 'test1'));
        $handler2->handle($this->getRecord(Logger::DEBUG, 'test2'));
        $handler1->handle($this->getRecord(Logger::DEBUG, 'test3'));
        $handler2->handle($this->getRecord(Logger::DEBUG, 'test4'));

        $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.log("%ctest1", "font-weight: normal");
c.log("%ctest2", "font-weight: normal");
c.log("%ctest3", "font-weight: normal");
c.log("%ctest4", "font-weight: normal");
}})(console);
EOF;

        $this->assertEquals($expected, $this->generateScript());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

class CouchDBHandlerTest extends TestCase
{
    public function testHandle()
    {
        $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));

        $handler = new CouchDBHandler();

        try {
            $handler->handle($record);
        } catch (\RuntimeException $e) {
            $this->markTestSkipped('Could not connect to couchdb server on http://localhost:5984');
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;

class DynamoDbHandlerTest extends TestCase
{
    private $client;

    public function setUp()
    {
        if (!class_exists('Aws\DynamoDb\DynamoDbClient')) {
            $this->markTestSkipped('aws/aws-sdk-php not installed');
        }

        $this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient')
            ->setMethods(array('formatAttributes', '__call'))
            ->disableOriginalConstructor()->getMock();
    }

    public function testConstruct()
    {
        $this->assertInstanceOf('Monolog\Handler\DynamoDbHandler', new DynamoDbHandler($this->client, 'foo'));
    }

    public function testInterface()
    {
        $this->assertInstanceOf('Monolog\Handler\HandlerInterface', new DynamoDbHandler($this->client, 'foo'));
    }

    public function testGetFormatter()
    {
        $handler = new DynamoDbHandler($this->client, 'foo');
        $this->assertInstanceOf('Monolog\Formatter\ScalarFormatter', $handler->getFormatter());
    }

    public function testHandle()
    {
        $record = $this->getRecord();
        $formatter = $this->getMock('Monolog\Formatter\FormatterInterface');
        $formatted = array('foo' => 1, 'bar' => 2);
        $handler = new DynamoDbHandler($this->client, 'foo');
        $handler->setFormatter($formatter);

        $formatter
             ->expects($this->once())
             ->method('format')
             ->with($record)
             ->will($this->returnValue($formatted));
        $this->client
             ->expects($this->once())
             ->method('formatAttributes')
             ->with($this->isType('array'))
             ->will($this->returnValue($formatted));
        $this->client
             ->expects($this->once())
             ->method('__call')
             ->with('putItem', array(array(
                 'TableName' => 'foo',
                 'Item' => $formatted,
             )));

        $handler->handle($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\TestCase;
use Monolog\Logger;

/**
 * @covers Monolog\Handler\NullHandler::handle
 */
class NullHandlerTest extends TestCase
{
    public function testHandle()
    {
        $handler = new NullHandler();
        $this->assertTrue($handler->handle($this->getRecord()));
    }

    public function testHandleLowerLevelRecord()
    {
        $handler = new NullHandler(Logger::WARNING);
        $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getPairs
     */
    public function testReplacement($val, $expected)
    {
        $proc = new PsrLogMessageProcessor;

        $message = $proc(array(
            'message' => '{foo}',
            'context' => array('foo' => $val),
        ));
        $this->assertEquals($expected, $message['message']);
    }

    public function getPairs()
    {
        return array(
            array('foo',    'foo'),
            array('3',      '3'),
            array(3,        '3'),
            array(null,     ''),
            array(true,     '1'),
            array(false,    ''),
            array(new \stdClass, '[object stdClass]'),
            array(array(), '[array]'),
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class ProcessIdProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\ProcessIdProcessor::__invoke
     */
    public function testProcessor()
    {
        $processor = new ProcessIdProcessor();
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('process_id', $record['extra']);
        $this->assertInternalType('int', $record['extra']['process_id']);
        $this->assertGreaterThan(0, $record['extra']['process_id']);
        $this->assertEquals(getmypid(), $record['extra']['process_id']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class MemoryPeakUsageProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke
     * @covers Monolog\Processor\MemoryProcessor::formatBytes
     */
    public function testProcessor()
    {
        $processor = new MemoryPeakUsageProcessor();
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('memory_peak_usage', $record['extra']);
        $this->assertRegExp('#[0-9.]+ (M|K)?B$#', $record['extra']['memory_peak_usage']);
    }

    /**
     * @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke
     * @covers Monolog\Processor\MemoryProcessor::formatBytes
     */
    public function testProcessorWithoutFormatting()
    {
        $processor = new MemoryPeakUsageProcessor(true, false);
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('memory_peak_usage', $record['extra']);
        $this->assertInternalType('int', $record['extra']['memory_peak_usage']);
        $this->assertGreaterThan(0, $record['extra']['memory_peak_usage']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class WebProcessorTest extends TestCase
{
    public function testProcessor()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'HTTP_REFERER'   => 'D',
            'SERVER_NAME'    => 'F',
            'UNIQUE_ID'      => 'G',
        );

        $processor = new WebProcessor($server);
        $record = $processor($this->getRecord());
        $this->assertEquals($server['REQUEST_URI'], $record['extra']['url']);
        $this->assertEquals($server['REMOTE_ADDR'], $record['extra']['ip']);
        $this->assertEquals($server['REQUEST_METHOD'], $record['extra']['http_method']);
        $this->assertEquals($server['HTTP_REFERER'], $record['extra']['referrer']);
        $this->assertEquals($server['SERVER_NAME'], $record['extra']['server']);
        $this->assertEquals($server['UNIQUE_ID'], $record['extra']['unique_id']);
    }

    public function testProcessorDoNothingIfNoRequestUri()
    {
        $server = array(
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
        );
        $processor = new WebProcessor($server);
        $record = $processor($this->getRecord());
        $this->assertEmpty($record['extra']);
    }

    public function testProcessorReturnNullIfNoHttpReferer()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'SERVER_NAME'    => 'F',
        );
        $processor = new WebProcessor($server);
        $record = $processor($this->getRecord());
        $this->assertNull($record['extra']['referrer']);
    }

    public function testProcessorDoesNotAddUniqueIdIfNotPresent()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'SERVER_NAME'    => 'F',
        );
        $processor = new WebProcessor($server);
        $record = $processor($this->getRecord());
        $this->assertFalse(isset($record['extra']['unique_id']));
    }

    public function testProcessorAddsOnlyRequestedExtraFields()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'SERVER_NAME'    => 'F',
        );

        $processor = new WebProcessor($server, array('url', 'http_method'));
        $record = $processor($this->getRecord());

        $this->assertSame(array('url' => 'A', 'http_method' => 'C'), $record['extra']);
    }

    public function testProcessorConfiguringOfExtraFields()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'SERVER_NAME'    => 'F',
        );

        $processor = new WebProcessor($server, array('url' => 'REMOTE_ADDR'));
        $record = $processor($this->getRecord());

        $this->assertSame(array('url' => 'B'), $record['extra']);
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testInvalidData()
    {
        new WebProcessor(new \stdClass);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class TagProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\TagProcessor::__invoke
     */
    public function testProcessor()
    {
        $tags = array(1, 2, 3);
        $processor = new TagProcessor($tags);
        $record = $processor($this->getRecord());

        $this->assertEquals($tags, $record['extra']['tags']);
    }

    /**
     * @covers Monolog\Processor\TagProcessor::__invoke
     */
    public function testProcessorTagModification()
    {
        $tags = array(1, 2, 3);
        $processor = new TagProcessor($tags);

        $record = $processor($this->getRecord());
        $this->assertEquals($tags, $record['extra']['tags']);

        $processor->setTags(array('a', 'b'));
        $record = $processor($this->getRecord());
        $this->assertEquals(array('a', 'b'), $record['extra']['tags']);

        $processor->addTags(array('a', 'c', 'foo' => 'bar'));
        $record = $processor($this->getRecord());
        $this->assertEquals(array('a', 'b', 'a', 'c', 'foo' => 'bar'), $record['extra']['tags']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

class Tester
{
    public function test($handler, $record)
    {
        $handler->handle($record);
    }
}

function tester($handler, $record)
{
    $handler->handle($record);
}

namespace Monolog\Processor;

use Monolog\Logger;
use Monolog\TestCase;
use Monolog\Handler\TestHandler;

class IntrospectionProcessorTest extends TestCase
{
    public function getHandler()
    {
        $processor = new IntrospectionProcessor();
        $handler = new TestHandler();
        $handler->pushProcessor($processor);

        return $handler;
    }

    public function testProcessorFromClass()
    {
        $handler = $this->getHandler();
        $tester = new \Acme\Tester;
        $tester->test($handler, $this->getRecord());
        list($record) = $handler->getRecords();
        $this->assertEquals(__FILE__, $record['extra']['file']);
        $this->assertEquals(18, $record['extra']['line']);
        $this->assertEquals('Acme\Tester', $record['extra']['class']);
        $this->assertEquals('test', $record['extra']['function']);
    }

    public function testProcessorFromFunc()
    {
        $handler = $this->getHandler();
        \Acme\tester($handler, $this->getRecord());
        list($record) = $handler->getRecords();
        $this->assertEquals(__FILE__, $record['extra']['file']);
        $this->assertEquals(24, $record['extra']['line']);
        $this->assertEquals(null, $record['extra']['class']);
        $this->assertEquals('Acme\tester', $record['extra']['function']);
    }

    public function testLevelTooLow()
    {
        $input = array(
            'level' => Logger::DEBUG,
            'extra' => array(),
        );

        $expected = $input;

        $processor = new IntrospectionProcessor(Logger::CRITICAL);
        $actual = $processor($input);

        $this->assertEquals($expected, $actual);
    }

    public function testLevelEqual()
    {
        $input = array(
            'level' => Logger::CRITICAL,
            'extra' => array(),
        );

        $expected = $input;
        $expected['extra'] = array(
            'file' => null,
            'line' => null,
            'class' => 'ReflectionMethod',
            'function' => 'invokeArgs',
        );

        $processor = new IntrospectionProcessor(Logger::CRITICAL);
        $actual = $processor($input);

        $this->assertEquals($expected, $actual);
    }

    public function testLevelHigher()
    {
        $input = array(
            'level' => Logger::EMERGENCY,
            'extra' => array(),
        );

        $expected = $input;
        $expected['extra'] = array(
            'file' => null,
            'line' => null,
            'class' => 'ReflectionMethod',
            'function' => 'invokeArgs',
        );

        $processor = new IntrospectionProcessor(Logger::CRITICAL);
        $actual = $processor($input);

        $this->assertEquals($expected, $actual);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class UidProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\UidProcessor::__invoke
     */
    public function testProcessor()
    {
        $processor = new UidProcessor();
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('uid', $record['extra']);
    }

    public function testGetUid()
    {
        $processor = new UidProcessor(10);
        $this->assertEquals(10, strlen($processor->getUid()));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class GitProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\GitProcessor::__invoke
     */
    public function testProcessor()
    {
        $processor = new GitProcessor();
        $record = $processor($this->getRecord());

        $this->assertArrayHasKey('git', $record['extra']);
        $this->assertTrue(!is_array($record['extra']['git']['branch']));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\TestCase;

class MemoryUsageProcessorTest extends TestCase
{
    /**
     * @covers Monolog\Processor\MemoryUsageProcessor::__invoke
     * @covers Monolog\Processor\MemoryProcessor::formatBytes
     */
    public function testProcessor()
    {
        $processor = new MemoryUsageProcessor();
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('memory_usage', $record['extra']);
        $this->assertRegExp('#[0-9.]+ (M|K)?B$#', $record['extra']['memory_usage']);
    }

    /**
     * @covers Monolog\Processor\MemoryUsageProcessor::__invoke
     * @covers Monolog\Processor\MemoryProcessor::formatBytes
     */
    public function testProcessorWithoutFormatting()
    {
        $processor = new MemoryUsageProcessor(true, false);
        $record = $processor($this->getRecord());
        $this->assertArrayHasKey('memory_usage', $record['extra']);
        $this->assertInternalType('int', $record['extra']['memory_usage']);
        $this->assertGreaterThan(0, $record['extra']['memory_usage']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

class RegistryTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        Registry::clear();
    }

    /**
     * @dataProvider hasLoggerProvider
     * @covers Monolog\Registry::hasLogger
     */
    public function testHasLogger(array $loggersToAdd, array $loggersToCheck, array $expectedResult)
    {
        foreach ($loggersToAdd as $loggerToAdd) {
            Registry::addLogger($loggerToAdd);
        }
        foreach ($loggersToCheck as $index => $loggerToCheck) {
            $this->assertSame($expectedResult[$index], Registry::hasLogger($loggerToCheck));
        }
    }

    public function hasLoggerProvider()
    {
        $logger1 = new Logger('test1');
        $logger2 = new Logger('test2');
        $logger3 = new Logger('test3');

        return array(
            // only instances
            array(
                array($logger1),
                array($logger1, $logger2),
                array(true, false),
            ),
            // only names
            array(
                array($logger1),
                array('test1', 'test2'),
                array(true, false),
            ),
            // mixed case
            array(
                array($logger1, $logger2),
                array('test1', $logger2, 'test3', $logger3),
                array(true, true, false, false),
            ),
        );
    }

    /**
     * @covers Monolog\Registry::clear
     */
    public function testClearClears()
    {
        Registry::addLogger(new Logger('test1'), 'log');
        Registry::clear();

        $this->setExpectedException('\InvalidArgumentException');
        Registry::getInstance('log');
    }

    /**
     * @dataProvider removedLoggerProvider
     * @covers Monolog\Registry::addLogger
     * @covers Monolog\Registry::removeLogger
     */
    public function testRemovesLogger($loggerToAdd, $remove)
    {
        Registry::addLogger($loggerToAdd);
        Registry::removeLogger($remove);

        $this->setExpectedException('\InvalidArgumentException');
        Registry::getInstance($loggerToAdd->getName());
    }

    public function removedLoggerProvider()
    {
        $logger1 = new Logger('test1');

        return array(
            array($logger1, $logger1),
            array($logger1, 'test1'),
        );
    }

    /**
     * @covers Monolog\Registry::addLogger
     * @covers Monolog\Registry::getInstance
     * @covers Monolog\Registry::__callStatic
     */
    public function testGetsSameLogger()
    {
        $logger1 = new Logger('test1');
        $logger2 = new Logger('test2');

        Registry::addLogger($logger1, 'test1');
        Registry::addLogger($logger2);

        $this->assertSame($logger1, Registry::getInstance('test1'));
        $this->assertSame($logger2, Registry::test2());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @covers Monolog\Registry::getInstance
     */
    public function testFailsOnNonExistantLogger()
    {
        Registry::getInstance('test1');
    }

    /**
     * @covers Monolog\Registry::addLogger
     */
    public function testReplacesLogger()
    {
        $log1 = new Logger('test1');
        $log2 = new Logger('test2');

        Registry::addLogger($log1, 'log');

        Registry::addLogger($log2, 'log', true);

        $this->assertSame($log2, Registry::getInstance('log'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @covers Monolog\Registry::addLogger
     */
    public function testFailsOnUnspecifiedReplacement()
    {
        $log1 = new Logger('test1');
        $log2 = new Logger('test2');

        Registry::addLogger($log1, 'log');

        Registry::addLogger($log2, 'log');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Monolog\Formatter\ChromePHPFormatter::format
     */
    public function testDefaultFormat()
    {
        $formatter = new ChromePHPFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('ip' => '127.0.0.1'),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertEquals(
            array(
                'meh',
                array(
                    'message' => 'log',
                    'context' => array('from' => 'logger'),
                    'extra' => array('ip' => '127.0.0.1'),
                ),
                'unknown',
                'error',
            ),
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\ChromePHPFormatter::format
     */
    public function testFormatWithFileAndLine()
    {
        $formatter = new ChromePHPFormatter();
        $record = array(
            'level' => Logger::CRITICAL,
            'level_name' => 'CRITICAL',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertEquals(
            array(
                'meh',
                array(
                    'message' => 'log',
                    'context' => array('from' => 'logger'),
                    'extra' => array('ip' => '127.0.0.1'),
                ),
                'test : 14',
                'error',
            ),
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\ChromePHPFormatter::format
     */
    public function testFormatWithoutContext()
    {
        $formatter = new ChromePHPFormatter();
        $record = array(
            'level' => Logger::DEBUG,
            'level_name' => 'DEBUG',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertEquals(
            array(
                'meh',
                'log',
                'unknown',
                'log',
            ),
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\ChromePHPFormatter::formatBatch
     */
    public function testBatchFormatThrowException()
    {
        $formatter = new ChromePHPFormatter();
        $records = array(
            array(
                'level' => Logger::INFO,
                'level_name' => 'INFO',
                'channel' => 'meh',
                'context' => array(),
                'datetime' => new \DateTime("@0"),
                'extra' => array(),
                'message' => 'log',
            ),
            array(
                'level' => Logger::WARNING,
                'level_name' => 'WARNING',
                'channel' => 'foo',
                'context' => array(),
                'datetime' => new \DateTime("@0"),
                'extra' => array(),
                'message' => 'log2',
            ),
        );

        $this->assertEquals(
            array(
                array(
                    'meh',
                    'log',
                    'unknown',
                    'info',
                ),
                array(
                    'foo',
                    'log2',
                    'unknown',
                    'warn',
                ),
            ),
            $formatter->formatBatch($records)
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Monolog\Formatter\WildfireFormatter::format
     */
    public function testDefaultFormat()
    {
        $wildfire = new WildfireFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('ip' => '127.0.0.1'),
            'message' => 'log',
        );

        $message = $wildfire->format($record);

        $this->assertEquals(
            '125|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},'
                .'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|',
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\WildfireFormatter::format
     */
    public function testFormatWithFileAndLine()
    {
        $wildfire = new WildfireFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14),
            'message' => 'log',
        );

        $message = $wildfire->format($record);

        $this->assertEquals(
            '129|[{"Type":"ERROR","File":"test","Line":14,"Label":"meh"},'
                .'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|',
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\WildfireFormatter::format
     */
    public function testFormatWithoutContext()
    {
        $wildfire = new WildfireFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $wildfire->format($record);

        $this->assertEquals(
            '58|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},"log"]|',
            $message
        );
    }

    /**
     * @covers Monolog\Formatter\WildfireFormatter::formatBatch
     * @expectedException BadMethodCallException
     */
    public function testBatchFormatThrowException()
    {
        $wildfire = new WildfireFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $wildfire->formatBatch(array($record));
    }

    /**
     * @covers Monolog\Formatter\WildfireFormatter::format
     */
    public function testTableFormat()
    {
        $wildfire = new WildfireFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'table-channel',
            'context' => array(
            WildfireFormatter::TABLE => array(
                    array('col1', 'col2', 'col3'),
                    array('val1', 'val2', 'val3'),
                    array('foo1', 'foo2', 'foo3'),
                    array('bar1', 'bar2', 'bar3'),
                ),
            ),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'table-message',
        );

        $message = $wildfire->format($record);

        $this->assertEquals(
            '171|[{"Type":"TABLE","File":"","Line":"","Label":"table-channel: table-message"},[["col1","col2","col3"],["val1","val2","val3"],["foo1","foo2","foo3"],["bar1","bar2","bar3"]]]|',
            $message
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('\Gelf\Message')) {
            $this->markTestSkipped("graylog2/gelf-php or mlehner/gelf-php is not installed");
        }
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testDefaultFormatter()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals(0, $message->getTimestamp());
        $this->assertEquals('log', $message->getShortMessage());
        $this->assertEquals('meh', $message->getFacility());
        $this->assertEquals(null, $message->getLine());
        $this->assertEquals(null, $message->getFile());
        $this->assertEquals($this->isLegacy() ? 3 : 'error', $message->getLevel());
        $this->assertNotEmpty($message->getHost());

        $formatter = new GelfMessageFormatter('mysystem');

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals('mysystem', $message->getHost());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithFileAndLine()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('file' => 'test', 'line' => 14),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals('test', $message->getFile());
        $this->assertEquals(14, $message->getLine());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     * @expectedException InvalidArgumentException
     */
    public function testFormatInvalidFails()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
        );

        $formatter->format($record);
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithContext()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_ctxt_from', $message_array);
        $this->assertEquals('logger', $message_array['_ctxt_from']);

        // Test with extraPrefix
        $formatter = new GelfMessageFormatter(null, null, 'CTX');
        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_CTXfrom', $message_array);
        $this->assertEquals('logger', $message_array['_CTXfrom']);
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithContextContainingException()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger', 'exception' => array(
                'class' => '\Exception',
                'file'  => '/some/file/in/dir.php:56',
                'trace' => array('/some/file/1.php:23', '/some/file/2.php:3'),
            )),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $this->assertEquals("/some/file/in/dir.php", $message->getFile());
        $this->assertEquals("56", $message->getLine());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithExtra()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_key', $message_array);
        $this->assertEquals('pair', $message_array['_key']);

        // Test with extraPrefix
        $formatter = new GelfMessageFormatter(null, 'EXT');
        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_EXTkey', $message_array);
        $this->assertEquals('pair', $message_array['_EXTkey']);
    }

    public function testFormatWithLargeData()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('exception' => str_repeat(' ', 32767)),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => str_repeat(' ', 32767)),
            'message' => 'log'
        );
        $message = $formatter->format($record);
        $messageArray = $message->toArray();
        $this->assertLessThanOrEqual(32766, strlen($messageArray['_key']));
        $this->assertLessThanOrEqual(32766, strlen($messageArray['_ctxt_exception']));
    }

    private function isLegacy()
    {
        return interface_exists('\Gelf\IMessagePublisher');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
{
    private $formatter;

    public function setUp()
    {
        $this->formatter = new ScalarFormatter();
    }

    public function buildTrace(\Exception $e)
    {
        $data = array();
        $trace = $e->getTrace();
        foreach ($trace as $frame) {
            if (isset($frame['file'])) {
                $data[] = $frame['file'].':'.$frame['line'];
            } else {
                $data[] = json_encode($frame);
            }
        }

        return $data;
    }

    public function encodeJson($data)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        return json_encode($data);
    }

    public function testFormat()
    {
        $exception = new \Exception('foo');
        $formatted = $this->formatter->format(array(
            'foo' => 'string',
            'bar' => 1,
            'baz' => false,
            'bam' => array(1, 2, 3),
            'bat' => array('foo' => 'bar'),
            'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'),
            'ban' => $exception,
        ));

        $this->assertSame(array(
            'foo' => 'string',
            'bar' => 1,
            'baz' => false,
            'bam' => $this->encodeJson(array(1, 2, 3)),
            'bat' => $this->encodeJson(array('foo' => 'bar')),
            'bap' => '1970-01-01 00:00:00',
            'ban' => $this->encodeJson(array(
                'class'   => get_class($exception),
                'message' => $exception->getMessage(),
                'code'    => $exception->getCode(),
                'file'    => $exception->getFile() . ':' . $exception->getLine(),
                'trace'   => $this->buildTrace($exception),
            )),
        ), $formatted);
    }

    public function testFormatWithErrorContext()
    {
        $context = array('file' => 'foo', 'line' => 1);
        $formatted = $this->formatter->format(array(
            'context' => $context,
        ));

        $this->assertSame(array(
            'context' => $this->encodeJson($context),
        ), $formatted);
    }

    public function testFormatWithExceptionContext()
    {
        $exception = new \Exception('foo');
        $formatted = $this->formatter->format(array(
            'context' => array(
                'exception' => $exception,
            ),
        ));

        $this->assertSame(array(
            'context' => $this->encodeJson(array(
                'exception' => array(
                    'class'   => get_class($exception),
                    'message' => $exception->getMessage(),
                    'code'    => $exception->getCode(),
                    'file'    => $exception->getFile() . ':' . $exception->getLine(),
                    'trace'   => $this->buildTrace($exception),
                ),
            )),
        ), $formatted);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\TestCase;

class LogglyFormatterTest extends TestCase
{
    /**
     * @covers Monolog\Formatter\LogglyFormatter::__construct
     */
    public function testConstruct()
    {
        $formatter = new LogglyFormatter();
        $this->assertEquals(LogglyFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
        $formatter = new LogglyFormatter(LogglyFormatter::BATCH_MODE_JSON);
        $this->assertEquals(LogglyFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
    }

    /**
     * @covers Monolog\Formatter\LogglyFormatter::format
     */
    public function testFormat()
    {
        $formatter = new LogglyFormatter();
        $record = $this->getRecord();
        $formatted_decoded = json_decode($formatter->format($record), true);
        $this->assertArrayHasKey("timestamp", $formatted_decoded);
        $this->assertEquals(new \DateTime($formatted_decoded["timestamp"]), $record["datetime"]);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        \PHPUnit_Framework_Error_Warning::$enabled = true;

        return parent::tearDown();
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testDefaultFormatter()
    {
        $formatter = new LogstashFormatter('test', 'hostname');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
        $this->assertEquals('log', $message['@message']);
        $this->assertEquals('meh', $message['@fields']['channel']);
        $this->assertContains('meh', $message['@tags']);
        $this->assertEquals(Logger::ERROR, $message['@fields']['level']);
        $this->assertEquals('test', $message['@type']);
        $this->assertEquals('hostname', $message['@source']);

        $formatter = new LogstashFormatter('mysystem');

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals('mysystem', $message['@type']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithFileAndLine()
    {
        $formatter = new LogstashFormatter('test');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('file' => 'test', 'line' => 14),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals('test', $message['@fields']['file']);
        $this->assertEquals(14, $message['@fields']['line']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithContext()
    {
        $formatter = new LogstashFormatter('test');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $message_array = $message['@fields'];

        $this->assertArrayHasKey('ctxt_from', $message_array);
        $this->assertEquals('logger', $message_array['ctxt_from']);

        // Test with extraPrefix
        $formatter = new LogstashFormatter('test', null, null, 'CTX');
        $message = json_decode($formatter->format($record), true);

        $message_array = $message['@fields'];

        $this->assertArrayHasKey('CTXfrom', $message_array);
        $this->assertEquals('logger', $message_array['CTXfrom']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithExtra()
    {
        $formatter = new LogstashFormatter('test');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $message_array = $message['@fields'];

        $this->assertArrayHasKey('key', $message_array);
        $this->assertEquals('pair', $message_array['key']);

        // Test with extraPrefix
        $formatter = new LogstashFormatter('test', null, 'EXT');
        $message = json_decode($formatter->format($record), true);

        $message_array = $message['@fields'];

        $this->assertArrayHasKey('EXTkey', $message_array);
        $this->assertEquals('pair', $message_array['EXTkey']);
    }

    public function testFormatWithApplicationName()
    {
        $formatter = new LogstashFormatter('app', 'test');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('@type', $message);
        $this->assertEquals('app', $message['@type']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testDefaultFormatterV1()
    {
        $formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_', LogstashFormatter::V1);
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
        $this->assertEquals("1", $message['@version']);
        $this->assertEquals('log', $message['message']);
        $this->assertEquals('meh', $message['channel']);
        $this->assertEquals('ERROR', $message['level']);
        $this->assertEquals('test', $message['type']);
        $this->assertEquals('hostname', $message['host']);

        $formatter = new LogstashFormatter('mysystem', null, null, 'ctxt_', LogstashFormatter::V1);

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals('mysystem', $message['type']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithFileAndLineV1()
    {
        $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('file' => 'test', 'line' => 14),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals('test', $message['file']);
        $this->assertEquals(14, $message['line']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithContextV1()
    {
        $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('ctxt_from', $message);
        $this->assertEquals('logger', $message['ctxt_from']);

        // Test with extraPrefix
        $formatter = new LogstashFormatter('test', null, null, 'CTX', LogstashFormatter::V1);
        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('CTXfrom', $message);
        $this->assertEquals('logger', $message['CTXfrom']);
    }

    /**
     * @covers Monolog\Formatter\LogstashFormatter::format
     */
    public function testFormatWithExtraV1()
    {
        $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('key', $message);
        $this->assertEquals('pair', $message['key']);

        // Test with extraPrefix
        $formatter = new LogstashFormatter('test', null, 'EXT', 'ctxt_', LogstashFormatter::V1);
        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('EXTkey', $message);
        $this->assertEquals('pair', $message['EXTkey']);
    }

    public function testFormatWithApplicationNameV1()
    {
        $formatter = new LogstashFormatter('app', 'test', null, 'ctxt_', LogstashFormatter::V1);
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertArrayHasKey('type', $message);
        $this->assertEquals('app', $message['type']);
    }

    public function testFormatWithLatin9Data()
    {
        if (version_compare(PHP_VERSION, '5.5.0', '<')) {
            // Ignore the warning that will be emitted by PHP <5.5.0
            \PHPUnit_Framework_Error_Warning::$enabled = false;
        }
        $formatter = new LogstashFormatter('test', 'hostname');
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => '¯\_(ツ)_/¯',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(
                'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist",
            ),
            'message' => 'log',
        );

        $message = json_decode($formatter->format($record), true);

        $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
        $this->assertEquals('log', $message['@message']);
        $this->assertEquals('¯\_(ツ)_/¯', $message['@fields']['channel']);
        $this->assertContains('¯\_(ツ)_/¯', $message['@tags']);
        $this->assertEquals(Logger::ERROR, $message['@fields']['level']);
        $this->assertEquals('test', $message['@type']);
        $this->assertEquals('hostname', $message['@source']);
        if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
            $this->assertEquals('ÖWN; FBCR/OrangeEspaña; Versão/4.0; Färist', $message['@fields']['user_agent']);
        } else {
            // PHP <5.5 does not return false for an element encoding failure,
            // instead it emits a warning (possibly) and nulls the value.
            $this->assertEquals(null, $message['@fields']['user_agent']);
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * @covers Monolog\Formatter\NormalizerFormatter
 */
class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        \PHPUnit_Framework_Error_Warning::$enabled = true;

        return parent::tearDown();
    }

    public function testFormat()
    {
        $formatter = new NormalizerFormatter('Y-m-d');
        $formatted = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'message' => 'foo',
            'datetime' => new \DateTime,
            'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
            'context' => array(
                'foo' => 'bar',
                'baz' => 'qux',
                'inf' => INF,
                '-inf' => -INF,
                'nan' => acos(4),
            ),
        ));

        $this->assertEquals(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'message' => 'foo',
            'datetime' => date('Y-m-d'),
            'extra' => array(
                'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})',
                'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)',
                'baz' => array(),
                'res' => '[resource] (stream)',
            ),
            'context' => array(
                'foo' => 'bar',
                'baz' => 'qux',
                'inf' => 'INF',
                '-inf' => '-INF',
                'nan' => 'NaN',
            ),
        ), $formatted);
    }

    public function testFormatExceptions()
    {
        $formatter = new NormalizerFormatter('Y-m-d');
        $e = new \LogicException('bar');
        $e2 = new \RuntimeException('foo', 0, $e);
        $formatted = $formatter->format(array(
            'exception' => $e2,
        ));

        $this->assertGreaterThan(5, count($formatted['exception']['trace']));
        $this->assertTrue(isset($formatted['exception']['previous']));
        unset($formatted['exception']['trace'], $formatted['exception']['previous']);

        $this->assertEquals(array(
            'exception' => array(
                'class'   => get_class($e2),
                'message' => $e2->getMessage(),
                'code'    => $e2->getCode(),
                'file'    => $e2->getFile().':'.$e2->getLine(),
            ),
        ), $formatted);
    }

    public function testFormatToStringExceptionHandle()
    {
        $formatter = new NormalizerFormatter('Y-m-d');
        $this->setExpectedException('RuntimeException', 'Could not convert to string');
        $formatter->format(array(
            'myObject' => new TestToStringError(),
        ));
    }

    public function testBatchFormat()
    {
        $formatter = new NormalizerFormatter('Y-m-d');
        $formatted = $formatter->formatBatch(array(
            array(
                'level_name' => 'CRITICAL',
                'channel' => 'test',
                'message' => 'bar',
                'context' => array(),
                'datetime' => new \DateTime,
                'extra' => array(),
            ),
            array(
                'level_name' => 'WARNING',
                'channel' => 'log',
                'message' => 'foo',
                'context' => array(),
                'datetime' => new \DateTime,
                'extra' => array(),
            ),
        ));
        $this->assertEquals(array(
            array(
                'level_name' => 'CRITICAL',
                'channel' => 'test',
                'message' => 'bar',
                'context' => array(),
                'datetime' => date('Y-m-d'),
                'extra' => array(),
            ),
            array(
                'level_name' => 'WARNING',
                'channel' => 'log',
                'message' => 'foo',
                'context' => array(),
                'datetime' => date('Y-m-d'),
                'extra' => array(),
            ),
        ), $formatted);
    }

    /**
     * Test issue #137
     */
    public function testIgnoresRecursiveObjectReferences()
    {
        // set up the recursion
        $foo = new \stdClass();
        $bar = new \stdClass();

        $foo->bar = $bar;
        $bar->foo = $foo;

        // set an error handler to assert that the error is not raised anymore
        $that = $this;
        set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
            if (error_reporting() & $level) {
                restore_error_handler();
                $that->fail("$message should not be raised");
            }
        });

        $formatter = new NormalizerFormatter();
        $reflMethod = new \ReflectionMethod($formatter, 'toJson');
        $reflMethod->setAccessible(true);
        $res = $reflMethod->invoke($formatter, array($foo, $bar), true);

        restore_error_handler();

        $this->assertEquals(@json_encode(array($foo, $bar)), $res);
    }

    public function testIgnoresInvalidTypes()
    {
        // set up the recursion
        $resource = fopen(__FILE__, 'r');

        // set an error handler to assert that the error is not raised anymore
        $that = $this;
        set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
            if (error_reporting() & $level) {
                restore_error_handler();
                $that->fail("$message should not be raised");
            }
        });

        $formatter = new NormalizerFormatter();
        $reflMethod = new \ReflectionMethod($formatter, 'toJson');
        $reflMethod->setAccessible(true);
        $res = $reflMethod->invoke($formatter, array($resource), true);

        restore_error_handler();

        $this->assertEquals(@json_encode(array($resource)), $res);
    }

    /**
     * @expectedException RuntimeException
     */
    public function testThrowsOnInvalidEncoding()
    {
        if (version_compare(PHP_VERSION, '5.5.0', '<')) {
            // Ignore the warning that will be emitted by PHP <5.5.0
            \PHPUnit_Framework_Error_Warning::$enabled = false;
        }
        $formatter = new NormalizerFormatter();
        $reflMethod = new \ReflectionMethod($formatter, 'toJson');
        $reflMethod->setAccessible(true);

        // send an invalid unicode sequence as a object that can't be cleaned
        $record = new \stdClass;
        $record->message = "\xB1\x31";
        $res = $reflMethod->invoke($formatter, $record);
        if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
            throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
        }
    }

    public function testConvertsInvalidEncodingAsLatin9()
    {
        if (version_compare(PHP_VERSION, '5.5.0', '<')) {
            // Ignore the warning that will be emitted by PHP <5.5.0
            \PHPUnit_Framework_Error_Warning::$enabled = false;
        }
        $formatter = new NormalizerFormatter();
        $reflMethod = new \ReflectionMethod($formatter, 'toJson');
        $reflMethod->setAccessible(true);

        $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));

        if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
            $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
        } else {
            // PHP <5.5 does not return false for an element encoding failure,
            // instead it emits a warning (possibly) and nulls the value.
            $this->assertSame('{"message":null}', $res);
        }
    }

    /**
     * @param mixed $in     Input
     * @param mixed $expect Expected output
     * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
     * @dataProvider providesDetectAndCleanUtf8
     */
    public function testDetectAndCleanUtf8($in, $expect)
    {
        $formatter = new NormalizerFormatter();
        $formatter->detectAndCleanUtf8($in);
        $this->assertSame($expect, $in);
    }

    public function providesDetectAndCleanUtf8()
    {
        $obj = new \stdClass;

        return array(
            'null' => array(null, null),
            'int' => array(123, 123),
            'float' => array(123.45, 123.45),
            'bool false' => array(false, false),
            'bool true' => array(true, true),
            'ascii string' => array('abcdef', 'abcdef'),
            'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
            'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
            'empty array' => array(array(), array()),
            'array' => array(array('abcdef'), array('abcdef')),
            'object' => array($obj, $obj),
        );
    }

    /**
     * @param int    $code
     * @param string $msg
     * @dataProvider providesHandleJsonErrorFailure
     */
    public function testHandleJsonErrorFailure($code, $msg)
    {
        $formatter = new NormalizerFormatter();
        $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
        $reflMethod->setAccessible(true);

        $this->setExpectedException('RuntimeException', $msg);
        $reflMethod->invoke($formatter, $code, 'faked');
    }

    public function providesHandleJsonErrorFailure()
    {
        return array(
            'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
            'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
            'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
            'default' => array(-1, 'Unknown error'),
        );
    }

    public function testExceptionTraceWithArgs()
    {
        if (defined('HHVM_VERSION')) {
            $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
        }

        // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
        // and no file or line are included in the trace because it's treated as internal function
        set_error_handler(function ($errno, $errstr, $errfile, $errline) {
            throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
        });

        try {
            // This will contain $resource and $wrappedResource as arguments in the trace item
            $resource = fopen('php://memory', 'rw+');
            fwrite($resource, 'test_resource');
            $wrappedResource = new TestFooNorm;
            $wrappedResource->foo = $resource;
            // Just do something stupid with a resource/wrapped resource as argument
            array_keys($wrappedResource);
        } catch (\Exception $e) {
            restore_error_handler();
        }

        $formatter = new NormalizerFormatter();
        $record = array('context' => array('exception' => $e));
        $result = $formatter->format($record);

        $this->assertRegExp(
            '%"resource":"\[resource\] \(stream\)"%',
            $result['context']['exception']['trace'][0]
        );

        if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
            $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%';
        } else {
            $pattern = '%\\\\"foo\\\\":null%';
        }

        // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
        $this->assertRegExp(
            $pattern,
            $result['context']['exception']['trace'][0]
        );
    }
}

class TestFooNorm
{
    public $foo = 'foo';
}

class TestBarNorm
{
    public function __toString()
    {
        return 'bar';
    }
}

class TestStreamFoo
{
    public $foo;
    public $resource;

    public function __construct($resource)
    {
        $this->resource = $resource;
        $this->foo = 'BAR';
    }

    public function __toString()
    {
        fseek($this->resource, 0);

        return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
    }
}

class TestToStringError
{
    public function __toString()
    {
        throw new \RuntimeException('Could not convert to string');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

class ElasticaFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists("Elastica\Document")) {
            $this->markTestSkipped("ruflin/elastica not installed");
        }
    }

    /**
     * @covers Monolog\Formatter\ElasticaFormatter::__construct
     * @covers Monolog\Formatter\ElasticaFormatter::format
     * @covers Monolog\Formatter\ElasticaFormatter::getDocument
     */
    public function testFormat()
    {
        // test log message
        $msg = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        // expected values
        $expected = $msg;
        $expected['datetime'] = '1970-01-01T00:00:00.000000+00:00';
        $expected['context'] = array(
            'class' => '[object] (stdClass: {})',
            'foo' => 7,
            0 => 'bar',
        );

        // format log message
        $formatter = new ElasticaFormatter('my_index', 'doc_type');
        $doc = $formatter->format($msg);
        $this->assertInstanceOf('Elastica\Document', $doc);

        // Document parameters
        $params = $doc->getParams();
        $this->assertEquals('my_index', $params['_index']);
        $this->assertEquals('doc_type', $params['_type']);

        // Document data values
        $data = $doc->getData();
        foreach (array_keys($expected) as $key) {
            $this->assertEquals($expected[$key], $data[$key]);
        }
    }

    /**
     * @covers Monolog\Formatter\ElasticaFormatter::getIndex
     * @covers Monolog\Formatter\ElasticaFormatter::getType
     */
    public function testGetters()
    {
        $formatter = new ElasticaFormatter('my_index', 'doc_type');
        $this->assertEquals('my_index', $formatter->getIndex());
        $this->assertEquals('doc_type', $formatter->getType());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * @covers Monolog\Formatter\LineFormatter
 */
class LineFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testDefFormatWithString()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'WARNING',
            'channel' => 'log',
            'context' => array(),
            'message' => 'foo',
            'datetime' => new \DateTime,
            'extra' => array(),
        ));
        $this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
    }

    public function testDefFormatWithArrayContext()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'message' => 'foo',
            'datetime' => new \DateTime,
            'extra' => array(),
            'context' => array(
                'foo' => 'bar',
                'baz' => 'qux',
                'bool' => false,
                'null' => null,
            ),
        ));
        $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
    }

    public function testDefFormatExtras()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime,
            'extra' => array('ip' => '127.0.0.1'),
            'message' => 'log',
        ));
        $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
    }

    public function testFormatExtras()
    {
        $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime,
            'extra' => array('ip' => '127.0.0.1', 'file' => 'test'),
            'message' => 'log',
        ));
        $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
    }

    public function testContextAndExtraOptionallyNotShownIfEmpty()
    {
        $formatter = new LineFormatter(null, 'Y-m-d', false, true);
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime,
            'extra' => array(),
            'message' => 'log',
        ));
        $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log  '."\n", $message);
    }

    public function testContextAndExtraReplacement()
    {
        $formatter = new LineFormatter('%context.foo% => %extra.foo%');
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('foo' => 'bar'),
            'datetime' => new \DateTime,
            'extra' => array('foo' => 'xbar'),
            'message' => 'log',
        ));
        $this->assertEquals('bar => xbar', $message);
    }

    public function testDefFormatWithObject()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime,
            'extra' => array('foo' => new TestFoo, 'bar' => new TestBar, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
            'message' => 'foobar',
        ));

        $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":"[object] (Monolog\\\\Formatter\\\\TestFoo: {\\"foo\\":\\"foo\\"})","bar":"[object] (Monolog\\\\Formatter\\\\TestBar: bar)","baz":[],"res":"[resource] (stream)"}'."\n", $message);
    }

    public function testDefFormatWithException()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(array(
            'level_name' => 'CRITICAL',
            'channel' => 'core',
            'context' => array('exception' => new \RuntimeException('Foo')),
            'datetime' => new \DateTime,
            'extra' => array(),
            'message' => 'foobar',
        ));

        $path = str_replace('\\/', '/', json_encode(__FILE__));

        $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message);
    }

    public function testDefFormatWithPreviousException()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $previous = new \LogicException('Wut?');
        $message = $formatter->format(array(
            'level_name' => 'CRITICAL',
            'channel' => 'core',
            'context' => array('exception' => new \RuntimeException('Foo', 0, $previous)),
            'datetime' => new \DateTime,
            'extra' => array(),
            'message' => 'foobar',
        ));

        $path = str_replace('\\/', '/', json_encode(__FILE__));

        $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).', LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 12).')"} []'."\n", $message);
    }

    public function testBatchFormat()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->formatBatch(array(
            array(
                'level_name' => 'CRITICAL',
                'channel' => 'test',
                'message' => 'bar',
                'context' => array(),
                'datetime' => new \DateTime,
                'extra' => array(),
            ),
            array(
                'level_name' => 'WARNING',
                'channel' => 'log',
                'message' => 'foo',
                'context' => array(),
                'datetime' => new \DateTime,
                'extra' => array(),
            ),
        ));
        $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
    }

    public function testFormatShouldStripInlineLineBreaks()
    {
        $formatter = new LineFormatter(null, 'Y-m-d');
        $message = $formatter->format(
            array(
                'message' => "foo\nbar",
                'context' => array(),
                'extra' => array(),
            )
        );

        $this->assertRegExp('/foo bar/', $message);
    }

    public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
    {
        $formatter = new LineFormatter(null, 'Y-m-d', true);
        $message = $formatter->format(
            array(
                'message' => "foo\nbar",
                'context' => array(),
                'extra' => array(),
            )
        );

        $this->assertRegExp('/foo\nbar/', $message);
    }
}

class TestFoo
{
    public $foo = 'foo';
}

class TestBar
{
    public function __toString()
    {
        return 'bar';
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;
use Monolog\TestCase;

class JsonFormatterTest extends TestCase
{
    /**
     * @covers Monolog\Formatter\JsonFormatter::__construct
     * @covers Monolog\Formatter\JsonFormatter::getBatchMode
     * @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines
     */
    public function testConstruct()
    {
        $formatter = new JsonFormatter();
        $this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
        $this->assertEquals(true, $formatter->isAppendingNewlines());
        $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false);
        $this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
        $this->assertEquals(false, $formatter->isAppendingNewlines());
    }

    /**
     * @covers Monolog\Formatter\JsonFormatter::format
     */
    public function testFormat()
    {
        $formatter = new JsonFormatter();
        $record = $this->getRecord();
        $this->assertEquals(json_encode($record)."\n", $formatter->format($record));

        $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
        $record = $this->getRecord();
        $this->assertEquals(json_encode($record), $formatter->format($record));
    }

    /**
     * @covers Monolog\Formatter\JsonFormatter::formatBatch
     * @covers Monolog\Formatter\JsonFormatter::formatBatchJson
     */
    public function testFormatBatch()
    {
        $formatter = new JsonFormatter();
        $records = array(
            $this->getRecord(Logger::WARNING),
            $this->getRecord(Logger::DEBUG),
        );
        $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
    }

    /**
     * @covers Monolog\Formatter\JsonFormatter::formatBatch
     * @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines
     */
    public function testFormatBatchNewlines()
    {
        $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
        $records = $expected = array(
            $this->getRecord(Logger::WARNING),
            $this->getRecord(Logger::DEBUG),
        );
        array_walk($expected, function (&$value, $key) {
            $value = json_encode($value);
        });
        $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
    }

    public function testDefFormatWithException()
    {
        $formatter = new JsonFormatter();
        $exception = new \RuntimeException('Foo');
        $message = $formatter->format(array(
            'level_name' => 'CRITICAL',
            'channel' => 'core',
            'context' => array('exception' => $exception),
            'datetime' => new \DateTime(),
            'extra' => array(),
            'message' => 'foobar',
        ));

        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $path = substr(json_encode($exception->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1);
        } else {
            $path = substr(json_encode($exception->getFile()), 1, -1);
        }
        $this->assertEquals('{"level_name":"CRITICAL","channel":"core","context":{"exception":{"class":"RuntimeException","message":"'.$exception->getMessage().'","code":'.$exception->getCode().',"file":"'.$path.':'.$exception->getLine().'"}},"datetime":'.json_encode(new \DateTime()).',"extra":[],"message":"foobar"}'."\n", $message);
    }

    public function testDefFormatWithPreviousException()
    {
        $formatter = new JsonFormatter();
        $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
        $message = $formatter->format(array(
            'level_name' => 'CRITICAL',
            'channel' => 'core',
            'context' => array('exception' => $exception),
            'datetime' => new \DateTime(),
            'extra' => array(),
            'message' => 'foobar',
        ));

        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $pathPrevious = substr(json_encode($exception->getPrevious()->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1);
            $pathException = substr(json_encode($exception->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1);
        } else {
            $pathPrevious = substr(json_encode($exception->getPrevious()->getFile()), 1, -1);
            $pathException = substr(json_encode($exception->getFile()), 1, -1);
        }
        $this->assertEquals('{"level_name":"CRITICAL","channel":"core","context":{"exception":{"class":"RuntimeException","message":"'.$exception->getMessage().'","code":'.$exception->getCode().',"file":"'.$pathException.':'.$exception->getLine().'","previous":{"class":"LogicException","message":"'.$exception->getPrevious()->getMessage().'","code":'.$exception->getPrevious()->getCode().',"file":"'.$pathPrevious.':'.$exception->getPrevious()->getLine().'"}}},"datetime":'.json_encode(new \DateTime()).',"extra":[],"message":"foobar"}'."\n", $message);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;
use Monolog\TestCase;

class FluentdFormatterTest extends TestCase
{
    /**
     * @covers Monolog\Formatter\FluentdFormatter::__construct
     * @covers Monolog\Formatter\FluentdFormatter::isUsingLevelsInTag
     */
    public function testConstruct()
    {
        $formatter = new FluentdFormatter();
        $this->assertEquals(false, $formatter->isUsingLevelsInTag());
        $formatter = new FluentdFormatter(false);
        $this->assertEquals(false, $formatter->isUsingLevelsInTag());
        $formatter = new FluentdFormatter(true);
        $this->assertEquals(true, $formatter->isUsingLevelsInTag());
    }

    /**
     * @covers Monolog\Formatter\FluentdFormatter::format
     */
    public function testFormat()
    {
        $record = $this->getRecord(Logger::WARNING);
        $record['datetime'] = new \DateTime("@0");

        $formatter = new FluentdFormatter();
        $this->assertEquals(
            '["test",0,{"message":"test","extra":[],"level":300,"level_name":"WARNING"}]',
            $formatter->format($record)
        );
    }

    /**
     * @covers Monolog\Formatter\FluentdFormatter::format
     */
    public function testFormatWithTag()
    {
        $record = $this->getRecord(Logger::ERROR);
        $record['datetime'] = new \DateTime("@0");

        $formatter = new FluentdFormatter(true);
        $this->assertEquals(
            '["test.error",0,{"message":"test","extra":[]}]',
            $formatter->format($record)
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

/**
 * @author Florian Plattner <me@florianplattner.de>
 */
class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('MongoDate')) {
            $this->markTestSkipped('mongo extension not installed');
        }
    }

    public function constructArgumentProvider()
    {
        return array(
            array(1, true, 1, true),
            array(0, false, 0, false),
        );
    }

    /**
     * @param $traceDepth
     * @param $traceAsString
     * @param $expectedTraceDepth
     * @param $expectedTraceAsString
     *
     * @dataProvider constructArgumentProvider
     */
    public function testConstruct($traceDepth, $traceAsString, $expectedTraceDepth, $expectedTraceAsString)
    {
        $formatter = new MongoDBFormatter($traceDepth, $traceAsString);

        $reflTrace = new \ReflectionProperty($formatter, 'exceptionTraceAsString');
        $reflTrace->setAccessible(true);
        $this->assertEquals($expectedTraceAsString, $reflTrace->getValue($formatter));

        $reflDepth = new\ReflectionProperty($formatter, 'maxNestingLevel');
        $reflDepth->setAccessible(true);
        $this->assertEquals($expectedTraceDepth, $reflDepth->getValue($formatter));
    }

    public function testSimpleFormat()
    {
        $record = array(
            'message' => 'some log message',
            'context' => array(),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter();
        $formattedRecord = $formatter->format($record);

        $this->assertCount(7, $formattedRecord);
        $this->assertEquals('some log message', $formattedRecord['message']);
        $this->assertEquals(array(), $formattedRecord['context']);
        $this->assertEquals(Logger::WARNING, $formattedRecord['level']);
        $this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']);
        $this->assertEquals('test', $formattedRecord['channel']);
        $this->assertInstanceOf('\MongoDate', $formattedRecord['datetime']);
        $this->assertEquals('0.00000000 1391212800', $formattedRecord['datetime']->__toString());
        $this->assertEquals(array(), $formattedRecord['extra']);
    }

    public function testRecursiveFormat()
    {
        $someObject = new \stdClass();
        $someObject->foo = 'something';
        $someObject->bar = 'stuff';

        $record = array(
            'message' => 'some log message',
            'context' => array(
                'stuff' => new \DateTime('2014-02-01 02:31:33'),
                'some_object' => $someObject,
                'context_string' => 'some string',
                'context_int' => 123456,
                'except' => new \Exception('exception message', 987),
            ),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter();
        $formattedRecord = $formatter->format($record);

        $this->assertCount(5, $formattedRecord['context']);
        $this->assertInstanceOf('\MongoDate', $formattedRecord['context']['stuff']);
        $this->assertEquals('0.00000000 1391221893', $formattedRecord['context']['stuff']->__toString());
        $this->assertEquals(
            array(
                'foo' => 'something',
                'bar' => 'stuff',
                'class' => 'stdClass',
            ),
            $formattedRecord['context']['some_object']
        );
        $this->assertEquals('some string', $formattedRecord['context']['context_string']);
        $this->assertEquals(123456, $formattedRecord['context']['context_int']);

        $this->assertCount(5, $formattedRecord['context']['except']);
        $this->assertEquals('exception message', $formattedRecord['context']['except']['message']);
        $this->assertEquals(987, $formattedRecord['context']['except']['code']);
        $this->assertInternalType('string', $formattedRecord['context']['except']['file']);
        $this->assertInternalType('integer', $formattedRecord['context']['except']['code']);
        $this->assertInternalType('string', $formattedRecord['context']['except']['trace']);
        $this->assertEquals('Exception', $formattedRecord['context']['except']['class']);
    }

    public function testFormatDepthArray()
    {
        $record = array(
            'message' => 'some log message',
            'context' => array(
                'nest2' => array(
                    'property' => 'anything',
                    'nest3' => array(
                        'nest4' => 'value',
                        'property' => 'nothing',
                    ),
                ),
            ),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter(2);
        $formattedResult = $formatter->format($record);

        $this->assertEquals(
            array(
                'nest2' => array(
                    'property' => 'anything',
                    'nest3' => '[...]',
                ),
            ),
            $formattedResult['context']
        );
    }

    public function testFormatDepthArrayInfiniteNesting()
    {
        $record = array(
            'message' => 'some log message',
            'context' => array(
                'nest2' => array(
                    'property' => 'something',
                    'nest3' => array(
                        'property' => 'anything',
                        'nest4' => array(
                            'property' => 'nothing',
                        ),
                    ),
                ),
            ),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter(0);
        $formattedResult = $formatter->format($record);

        $this->assertEquals(
            array(
                'nest2' => array(
                    'property' => 'something',
                    'nest3' => array(
                        'property' => 'anything',
                        'nest4' => array(
                            'property' => 'nothing',
                        ),
                    ),
                ),
            ),
            $formattedResult['context']
        );
    }

    public function testFormatDepthObjects()
    {
        $someObject = new \stdClass();
        $someObject->property = 'anything';
        $someObject->nest3 = new \stdClass();
        $someObject->nest3->property = 'nothing';
        $someObject->nest3->nest4 = 'invisible';

        $record = array(
            'message' => 'some log message',
            'context' => array(
                'nest2' => $someObject,
            ),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter(2, true);
        $formattedResult = $formatter->format($record);

        $this->assertEquals(
            array(
                'nest2' => array(
                    'property' => 'anything',
                    'nest3' => '[...]',
                    'class' => 'stdClass',
                ),
            ),
            $formattedResult['context']
        );
    }

    public function testFormatDepthException()
    {
        $record = array(
            'message' => 'some log message',
            'context' => array(
                'nest2' => new \Exception('exception message', 987),
            ),
            'level' => Logger::WARNING,
            'level_name' => Logger::getLevelName(Logger::WARNING),
            'channel' => 'test',
            'datetime' => new \DateTime('2014-02-01 00:00:00'),
            'extra' => array(),
        );

        $formatter = new MongoDBFormatter(2, false);
        $formattedRecord = $formatter->format($record);

        $this->assertEquals('exception message', $formattedRecord['context']['nest2']['message']);
        $this->assertEquals(987, $formattedRecord['context']['nest2']['code']);
        $this->assertEquals('[...]', $formattedRecord['context']['nest2']['trace']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;
use Monolog\TestCase;

class FlowdockFormatterTest extends TestCase
{
    /**
     * @covers Monolog\Formatter\FlowdockFormatter::format
     */
    public function testFormat()
    {
        $formatter = new FlowdockFormatter('test_source', 'source@test.com');
        $record = $this->getRecord();

        $expected = array(
            'source' => 'test_source',
            'from_address' => 'source@test.com',
            'subject' => 'in test_source: WARNING - test',
            'content' => 'test',
            'tags' => array('#logs', '#warning', '#test'),
            'project' => 'test_source',
        );
        $formatted = $formatter->format($record);

        $this->assertEquals($expected, $formatted['flowdock']);
    }

    /**
     * @ covers Monolog\Formatter\FlowdockFormatter::formatBatch
     */
    public function testFormatBatch()
    {
        $formatter = new FlowdockFormatter('test_source', 'source@test.com');
        $records = array(
            $this->getRecord(Logger::WARNING),
            $this->getRecord(Logger::DEBUG),
        );
        $formatted = $formatter->formatBatch($records);

        $this->assertArrayHasKey('flowdock', $formatted[0]);
        $this->assertArrayHasKey('flowdock', $formatted[1]);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Monolog\Handler\TestHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Processor\PsrLogMessageProcessor;
use Psr\Log\Test\LoggerInterfaceTest;

class PsrLogCompatTest extends LoggerInterfaceTest
{
    private $handler;

    public function getLogger()
    {
        $logger = new Logger('foo');
        $logger->pushHandler($handler = new TestHandler);
        $logger->pushProcessor(new PsrLogMessageProcessor);
        $handler->setFormatter(new LineFormatter('%level_name% %message%'));

        $this->handler = $handler;

        return $logger;
    }

    public function getLogs()
    {
        $convert = function ($record) {
            $lower = function ($match) {
                return strtolower($match[0]);
            };

            return preg_replace_callback('{^[A-Z]+}', $lower, $record['formatted']);
        };

        return array_map($convert, $this->handler->getRecords());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Monolog\Handler\TestHandler;

class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleError()
    {
        $logger = new Logger('test', array($handler = new TestHandler));
        $errHandler = new ErrorHandler($logger);

        $errHandler->registerErrorHandler(array(E_USER_NOTICE => Logger::EMERGENCY), false);
        trigger_error('Foo', E_USER_ERROR);
        $this->assertCount(1, $handler->getRecords());
        $this->assertTrue($handler->hasErrorRecords());
        trigger_error('Foo', E_USER_NOTICE);
        $this->assertCount(2, $handler->getRecords());
        $this->assertTrue($handler->hasEmergencyRecords());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Monolog\Processor\WebProcessor;
use Monolog\Handler\TestHandler;

class LoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Monolog\Logger::getName
     */
    public function testGetName()
    {
        $logger = new Logger('foo');
        $this->assertEquals('foo', $logger->getName());
    }

    /**
     * @covers Monolog\Logger::getLevelName
     */
    public function testGetLevelName()
    {
        $this->assertEquals('ERROR', Logger::getLevelName(Logger::ERROR));
    }

    /**
     * @covers Monolog\Logger::withName
     */
    public function testWithName()
    {
        $first = new Logger('first', array($handler = new TestHandler()));
        $second = $first->withName('second');

        $this->assertSame('first', $first->getName());
        $this->assertSame('second', $second->getName());
        $this->assertSame($handler, $second->popHandler());
    }

    /**
     * @covers Monolog\Logger::toMonologLevel
     */
    public function testConvertPSR3ToMonologLevel()
    {
        $this->assertEquals(Logger::toMonologLevel('debug'), 100);
        $this->assertEquals(Logger::toMonologLevel('info'), 200);
        $this->assertEquals(Logger::toMonologLevel('notice'), 250);
        $this->assertEquals(Logger::toMonologLevel('warning'), 300);
        $this->assertEquals(Logger::toMonologLevel('error'), 400);
        $this->assertEquals(Logger::toMonologLevel('critical'), 500);
        $this->assertEquals(Logger::toMonologLevel('alert'), 550);
        $this->assertEquals(Logger::toMonologLevel('emergency'), 600);
    }

    /**
     * @covers Monolog\Logger::getLevelName
     * @expectedException InvalidArgumentException
     */
    public function testGetLevelNameThrows()
    {
        Logger::getLevelName(5);
    }

    /**
     * @covers Monolog\Logger::__construct
     */
    public function testChannel()
    {
        $logger = new Logger('foo');
        $handler = new TestHandler;
        $logger->pushHandler($handler);
        $logger->addWarning('test');
        list($record) = $handler->getRecords();
        $this->assertEquals('foo', $record['channel']);
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testLog()
    {
        $logger = new Logger(__METHOD__);

        $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
        $handler->expects($this->once())
            ->method('handle');
        $logger->pushHandler($handler);

        $this->assertTrue($logger->addWarning('test'));
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testLogNotHandled()
    {
        $logger = new Logger(__METHOD__);

        $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'), array(Logger::ERROR));
        $handler->expects($this->never())
            ->method('handle');
        $logger->pushHandler($handler);

        $this->assertFalse($logger->addWarning('test'));
    }

    public function testHandlersInCtor()
    {
        $handler1 = new TestHandler;
        $handler2 = new TestHandler;
        $logger = new Logger(__METHOD__, array($handler1, $handler2));

        $this->assertEquals($handler1, $logger->popHandler());
        $this->assertEquals($handler2, $logger->popHandler());
    }

    public function testProcessorsInCtor()
    {
        $processor1 = new WebProcessor;
        $processor2 = new WebProcessor;
        $logger = new Logger(__METHOD__, array(), array($processor1, $processor2));

        $this->assertEquals($processor1, $logger->popProcessor());
        $this->assertEquals($processor2, $logger->popProcessor());
    }

    /**
     * @covers Monolog\Logger::pushHandler
     * @covers Monolog\Logger::popHandler
     * @expectedException LogicException
     */
    public function testPushPopHandler()
    {
        $logger = new Logger(__METHOD__);
        $handler1 = new TestHandler;
        $handler2 = new TestHandler;

        $logger->pushHandler($handler1);
        $logger->pushHandler($handler2);

        $this->assertEquals($handler2, $logger->popHandler());
        $this->assertEquals($handler1, $logger->popHandler());
        $logger->popHandler();
    }

    /**
     * @covers Monolog\Logger::setHandlers
     */
    public function testSetHandlers()
    {
        $logger = new Logger(__METHOD__);
        $handler1 = new TestHandler;
        $handler2 = new TestHandler;

        $logger->pushHandler($handler1);
        $logger->setHandlers(array($handler2));

        // handler1 has been removed
        $this->assertEquals(array($handler2), $logger->getHandlers());

        $logger->setHandlers(array(
            "AMapKey" => $handler1,
            "Woop" => $handler2,
        ));

        // Keys have been scrubbed
        $this->assertEquals(array($handler1, $handler2), $logger->getHandlers());
    }

    /**
     * @covers Monolog\Logger::pushProcessor
     * @covers Monolog\Logger::popProcessor
     * @expectedException LogicException
     */
    public function testPushPopProcessor()
    {
        $logger = new Logger(__METHOD__);
        $processor1 = new WebProcessor;
        $processor2 = new WebProcessor;

        $logger->pushProcessor($processor1);
        $logger->pushProcessor($processor2);

        $this->assertEquals($processor2, $logger->popProcessor());
        $this->assertEquals($processor1, $logger->popProcessor());
        $logger->popProcessor();
    }

    /**
     * @covers Monolog\Logger::pushProcessor
     * @expectedException InvalidArgumentException
     */
    public function testPushProcessorWithNonCallable()
    {
        $logger = new Logger(__METHOD__);

        $logger->pushProcessor(new \stdClass());
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testProcessorsAreExecuted()
    {
        $logger = new Logger(__METHOD__);
        $handler = new TestHandler;
        $logger->pushHandler($handler);
        $logger->pushProcessor(function ($record) {
            $record['extra']['win'] = true;

            return $record;
        });
        $logger->addError('test');
        list($record) = $handler->getRecords();
        $this->assertTrue($record['extra']['win']);
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testProcessorsAreCalledOnlyOnce()
    {
        $logger = new Logger(__METHOD__);
        $handler = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler->expects($this->any())
            ->method('handle')
            ->will($this->returnValue(true))
        ;
        $logger->pushHandler($handler);

        $processor = $this->getMockBuilder('Monolog\Processor\WebProcessor')
            ->disableOriginalConstructor()
            ->setMethods(array('__invoke'))
            ->getMock()
        ;
        $processor->expects($this->once())
            ->method('__invoke')
            ->will($this->returnArgument(0))
        ;
        $logger->pushProcessor($processor);

        $logger->addError('test');
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testProcessorsNotCalledWhenNotHandled()
    {
        $logger = new Logger(__METHOD__);
        $handler = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler->expects($this->once())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;
        $logger->pushHandler($handler);
        $that = $this;
        $logger->pushProcessor(function ($record) use ($that) {
            $that->fail('The processor should not be called');
        });
        $logger->addAlert('test');
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testHandlersNotCalledBeforeFirstHandling()
    {
        $logger = new Logger(__METHOD__);

        $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler1->expects($this->never())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;
        $handler1->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;
        $logger->pushHandler($handler1);

        $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler2->expects($this->once())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler2->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;
        $logger->pushHandler($handler2);

        $handler3 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler3->expects($this->once())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;
        $handler3->expects($this->never())
            ->method('handle')
        ;
        $logger->pushHandler($handler3);

        $logger->debug('test');
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testHandlersNotCalledBeforeFirstHandlingWithAssocArray()
    {
        $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler1->expects($this->never())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;
        $handler1->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;

        $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler2->expects($this->once())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler2->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;

        $handler3 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler3->expects($this->once())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;
        $handler3->expects($this->never())
            ->method('handle')
        ;

        $logger = new Logger(__METHOD__, array('last' => $handler3, 'second' => $handler2, 'first' => $handler1));

        $logger->debug('test');
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testBubblingWhenTheHandlerReturnsFalse()
    {
        $logger = new Logger(__METHOD__);

        $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler1->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler1->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;
        $logger->pushHandler($handler1);

        $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler2->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler2->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(false))
        ;
        $logger->pushHandler($handler2);

        $logger->debug('test');
    }

    /**
     * @covers Monolog\Logger::addRecord
     */
    public function testNotBubblingWhenTheHandlerReturnsTrue()
    {
        $logger = new Logger(__METHOD__);

        $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler1->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler1->expects($this->never())
            ->method('handle')
        ;
        $logger->pushHandler($handler1);

        $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler2->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;
        $handler2->expects($this->once())
            ->method('handle')
            ->will($this->returnValue(true))
        ;
        $logger->pushHandler($handler2);

        $logger->debug('test');
    }

    /**
     * @covers Monolog\Logger::isHandling
     */
    public function testIsHandling()
    {
        $logger = new Logger(__METHOD__);

        $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler1->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(false))
        ;

        $logger->pushHandler($handler1);
        $this->assertFalse($logger->isHandling(Logger::DEBUG));

        $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
        $handler2->expects($this->any())
            ->method('isHandling')
            ->will($this->returnValue(true))
        ;

        $logger->pushHandler($handler2);
        $this->assertTrue($logger->isHandling(Logger::DEBUG));
    }

    /**
     * @dataProvider logMethodProvider
     * @covers Monolog\Logger::addDebug
     * @covers Monolog\Logger::addInfo
     * @covers Monolog\Logger::addNotice
     * @covers Monolog\Logger::addWarning
     * @covers Monolog\Logger::addError
     * @covers Monolog\Logger::addCritical
     * @covers Monolog\Logger::addAlert
     * @covers Monolog\Logger::addEmergency
     * @covers Monolog\Logger::debug
     * @covers Monolog\Logger::info
     * @covers Monolog\Logger::notice
     * @covers Monolog\Logger::warn
     * @covers Monolog\Logger::err
     * @covers Monolog\Logger::crit
     * @covers Monolog\Logger::alert
     * @covers Monolog\Logger::emerg
     */
    public function testLogMethods($method, $expectedLevel)
    {
        $logger = new Logger('foo');
        $handler = new TestHandler;
        $logger->pushHandler($handler);
        $logger->{$method}('test');
        list($record) = $handler->getRecords();
        $this->assertEquals($expectedLevel, $record['level']);
    }

    public function logMethodProvider()
    {
        return array(
            // monolog methods
            array('addDebug',     Logger::DEBUG),
            array('addInfo',      Logger::INFO),
            array('addNotice',    Logger::NOTICE),
            array('addWarning',   Logger::WARNING),
            array('addError',     Logger::ERROR),
            array('addCritical',  Logger::CRITICAL),
            array('addAlert',     Logger::ALERT),
            array('addEmergency', Logger::EMERGENCY),

            // ZF/Sf2 compat methods
            array('debug',  Logger::DEBUG),
            array('info',   Logger::INFO),
            array('notice', Logger::NOTICE),
            array('warn',   Logger::WARNING),
            array('err',    Logger::ERROR),
            array('crit',   Logger::CRITICAL),
            array('alert',  Logger::ALERT),
            array('emerg',  Logger::EMERGENCY),
        );
    }

    /**
     * @dataProvider setTimezoneProvider
     * @covers Monolog\Logger::setTimezone
     */
    public function testSetTimezone($tz)
    {
        Logger::setTimezone($tz);
        $logger = new Logger('foo');
        $handler = new TestHandler;
        $logger->pushHandler($handler);
        $logger->info('test');
        list($record) = $handler->getRecords();
        $this->assertEquals($tz, $record['datetime']->getTimezone());
    }

    public function setTimezoneProvider()
    {
        return array_map(
            function ($tz) { return array(new \DateTimeZone($tz)); },
            \DateTimeZone::listIdentifiers()
        );
    }

    /**
     * @dataProvider useMicrosecondTimestampsProvider
     * @covers Monolog\Logger::useMicrosecondTimestamps
     * @covers Monolog\Logger::addRecord
     */
    public function testUseMicrosecondTimestamps($micro, $assert)
    {
        $logger = new Logger('foo');
        $logger->useMicrosecondTimestamps($micro);
        $handler = new TestHandler;
        $logger->pushHandler($handler);
        $logger->info('test');
        list($record) = $handler->getRecords();
        $this->{$assert}('000000', $record['datetime']->format('u'));
    }

    public function useMicrosecondTimestampsProvider()
    {
        return array(
            // this has a very small chance of a false negative (1/10^6)
            'with microseconds' => array(true, 'assertNotSame'),
            'without microseconds' => array(false, 'assertSame'),
        );
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @return array Record
     */
    protected function getRecord($level = Logger::WARNING, $message = 'test', $context = array())
    {
        return array(
            'message' => $message,
            'context' => $context,
            'level' => $level,
            'level_name' => Logger::getLevelName($level),
            'channel' => 'test',
            'datetime' => \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true))),
            'extra' => array(),
        );
    }

    /**
     * @return array
     */
    protected function getMultipleRecords()
    {
        return array(
            $this->getRecord(Logger::DEBUG, 'debug message 1'),
            $this->getRecord(Logger::DEBUG, 'debug message 2'),
            $this->getRecord(Logger::INFO, 'information'),
            $this->getRecord(Logger::WARNING, 'warning'),
            $this->getRecord(Logger::ERROR, 'error'),
        );
    }

    /**
     * @return Monolog\Formatter\FormatterInterface
     */
    protected function getIdentityFormatter()
    {
        $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
        $formatter->expects($this->any())
            ->method('format')
            ->will($this->returnCallback(function ($record) { return $record['message']; }));

        return $formatter;
    }
}
# Monolog - Logging for PHP [![Build Status](https://img.shields.io/travis/Seldaek/monolog.svg)](https://travis-ci.org/Seldaek/monolog)

[![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog)
[![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog)


Monolog sends your logs to files, sockets, inboxes, databases and various
web services. See the complete list of handlers below. Special handlers
allow you to build advanced logging strategies.

This library implements the [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
interface that you can type-hint against in your own libraries to keep
a maximum of interoperability. You can also use it in your applications to
make sure you can always use another compatible logger at a later time.
As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels.
Internally Monolog still uses its own level scheme since it predates PSR-3.

## Installation

Install the latest version with

```bash
$ composer require monolog/monolog
```

## Basic Usage

```php
<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');
```

## Documentation

- [Usage Instructions](doc/01-usage.md)
- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md)
- [Utility classes](doc/03-utilities.md)
- [Extending Monolog](doc/04-extending.md)

## Third Party Packages

Third party handlers, formatters and processors are
[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You
can also add your own there if you publish one.

## About

### Requirements

- Monolog works with PHP 5.3 or above, and is also tested to work with HHVM.

### Submitting bugs and feature requests

Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/monolog/issues)

### Framework Integrations

- Frameworks and libraries using [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
  can be used very easily with Monolog since it implements the interface.
- [Symfony2](http://symfony.com) comes out of the box with Monolog.
- [Silex](http://silex.sensiolabs.org/) comes out of the box with Monolog.
- [Laravel 4 & 5](http://laravel.com/) come out of the box with Monolog.
- [Lumen](http://lumen.laravel.com/) comes out of the box with Monolog.
- [PPI](http://www.ppi.io/) comes out of the box with Monolog.
- [CakePHP](http://cakephp.org/) is usable with Monolog via the [cakephp-monolog](https://github.com/jadb/cakephp-monolog) plugin.
- [Slim](http://www.slimframework.com/) is usable with Monolog via the [Slim-Monolog](https://github.com/Flynsarmy/Slim-Monolog) log writer.
- [XOOPS 2.6](http://xoops.org/) comes out of the box with Monolog.
- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog.
- [Nette Framework](http://nette.org/en/) can be used with Monolog via [Kdyby/Monolog](https://github.com/Kdyby/Monolog) extension.
- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog.

### Author

Jordi Boggiano - <j.boggiano@seld.be> - <http://twitter.com/seldaek><br />
See also the list of [contributors](https://github.com/Seldaek/monolog/contributors) which participated in this project.

### License

Monolog is licensed under the MIT License - see the `LICENSE` file for details

### Acknowledgements

This library is heavily inspired by Python's [Logbook](https://logbook.readthedocs.io/en/stable/)
library, although most concepts have been adjusted to fit to the PHP world.
# Monolog - Logging for PHP [![Build Status](https://img.shields.io/travis/Seldaek/monolog.svg)](https://travis-ci.org/Seldaek/monolog)

[![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog)
[![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog)
[![Reference Status](https://www.versioneye.com/php/monolog:monolog/reference_badge.svg)](https://www.versioneye.com/php/monolog:monolog/references)


Monolog sends your logs to files, sockets, inboxes, databases and various
web services. See the complete list of handlers below. Special handlers
allow you to build advanced logging strategies.

This library implements the [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
interface that you can type-hint against in your own libraries to keep
a maximum of interoperability. You can also use it in your applications to
make sure you can always use another compatible logger at a later time.
As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels.
Internally Monolog still uses its own level scheme since it predates PSR-3.

## Installation

Install the latest version with

```bash
$ composer require monolog/monolog
```

## Basic Usage

```php
<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');
```

## Documentation

- [Usage Instructions](doc/01-usage.md)
- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md)
- [Utility classes](doc/03-utilities.md)
- [Extending Monolog](doc/04-extending.md)

## Third Party Packages

Third party handlers, formatters and processors are
[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You
can also add your own there if you publish one.

## About

### Requirements

- Monolog works with PHP 5.3 or above, and is also tested to work with HHVM.

### Submitting bugs and feature requests

Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/monolog/issues)

### Framework Integrations

- Frameworks and libraries using [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
  can be used very easily with Monolog since it implements the interface.
- [Symfony2](http://symfony.com) comes out of the box with Monolog.
- [Silex](http://silex.sensiolabs.org/) comes out of the box with Monolog.
- [Laravel 4 & 5](http://laravel.com/) come out of the box with Monolog.
- [Lumen](http://lumen.laravel.com/) comes out of the box with Monolog.
- [PPI](http://www.ppi.io/) comes out of the box with Monolog.
- [CakePHP](http://cakephp.org/) is usable with Monolog via the [cakephp-monolog](https://github.com/jadb/cakephp-monolog) plugin.
- [Slim](http://www.slimframework.com/) is usable with Monolog via the [Slim-Monolog](https://github.com/Flynsarmy/Slim-Monolog) log writer.
- [XOOPS 2.6](http://xoops.org/) comes out of the box with Monolog.
- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog.
- [Nette Framework](http://nette.org/en/) can be used with Monolog via [Kdyby/Monolog](https://github.com/Kdyby/Monolog) extension.
- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog.

### Author

Jordi Boggiano - <j.boggiano@seld.be> - <http://twitter.com/seldaek><br />
See also the list of [contributors](https://github.com/Seldaek/monolog/contributors) which participated in this project.

### License

Monolog is licensed under the MIT License - see the `LICENSE` file for details

### Acknowledgements

This library is heavily inspired by Python's [Logbook](http://packages.python.org/Logbook/)
library, although most concepts have been adjusted to fit to the PHP world.
parameters:
    level: 3

    paths:
        - src/
#        - tests/


    ignoreErrors:
        - '#zend_monitor_|ZEND_MONITOR_#'
        - '#RollbarNotifier#'
        - '#Predis\\Client#'
        - '#^Cannot call method ltrim\(\) on int\|false.$#'
        - '#^Access to an undefined property Raven_Client::\$context.$#'
        - '#MongoDB\\(Client|Collection)#'
        - '#Gelf\\IMessagePublisher#'
# Using Monolog

- [Installation](#installation)
- [Core Concepts](#core-concepts)
- [Log Levels](#log-levels)
- [Configuring a logger](#configuring-a-logger)
- [Adding extra data in the records](#adding-extra-data-in-the-records)
- [Leveraging channels](#leveraging-channels)
- [Customizing the log format](#customizing-the-log-format)

## Installation

Monolog is available on Packagist ([monolog/monolog](http://packagist.org/packages/monolog/monolog))
and as such installable via [Composer](http://getcomposer.org/).

```bash
composer require monolog/monolog
```

If you do not use Composer, you can grab the code from GitHub, and use any
PSR-0 compatible autoloader (e.g. the [Symfony2 ClassLoader component](https://github.com/symfony/ClassLoader))
to load Monolog classes.

## Core Concepts

Every `Logger` instance has a channel (name) and a stack of handlers. Whenever
you add a record to the logger, it traverses the handler stack. Each handler
decides whether it fully handled the record, and if so, the propagation of the
record ends there.

This allows for flexible logging setups, for example having a `StreamHandler` at
the bottom of the stack that will log anything to disk, and on top of that add
a `MailHandler` that will send emails only when an error message is logged.
Handlers also have a `$bubble` property which defines whether they block the
record or not if they handled it. In this example, setting the `MailHandler`'s
`$bubble` argument to false means that records handled by the `MailHandler` will
not propagate to the `StreamHandler` anymore.

You can create many `Logger`s, each defining a channel (e.g.: db, request,
router, ..) and each of them combining various handlers, which can be shared
or not. The channel is reflected in the logs and allows you to easily see or
filter records.

Each Handler also has a Formatter, a default one with settings that make sense
will be created if you don't set one. The formatters normalize and format
incoming records so that they can be used by the handlers to output useful
information.

Custom severity levels are not available. Only the eight
[RFC 5424](http://tools.ietf.org/html/rfc5424) levels (debug, info, notice,
warning, error, critical, alert, emergency) are present for basic filtering
purposes, but for sorting and other use cases that would require
flexibility, you should add Processors to the Logger that can add extra
information (tags, user ip, ..) to the records before they are handled.

## Log Levels

Monolog supports the logging levels described by [RFC 5424](http://tools.ietf.org/html/rfc5424).

- **DEBUG** (100): Detailed debug information.

- **INFO** (200): Interesting events. Examples: User logs in, SQL logs.

- **NOTICE** (250): Normal but significant events.

- **WARNING** (300): Exceptional occurrences that are not errors. Examples:
  Use of deprecated APIs, poor use of an API, undesirable things that are not
  necessarily wrong.

- **ERROR** (400): Runtime errors that do not require immediate action but
  should typically be logged and monitored.

- **CRITICAL** (500): Critical conditions. Example: Application component
  unavailable, unexpected exception.

- **ALERT** (550): Action must be taken immediately. Example: Entire website
  down, database unavailable, etc. This should trigger the SMS alerts and wake
  you up.

- **EMERGENCY** (600): Emergency: system is unusable.

## Configuring a logger

Here is a basic setup to log to a file and to firephp on the DEBUG level:

```php
<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;

// Create the logger
$logger = new Logger('my_logger');
// Now add some handlers
$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));
$logger->pushHandler(new FirePHPHandler());

// You can now use your logger
$logger->addInfo('My logger is now ready');
```

Let's explain it. The first step is to create the logger instance which will
be used in your code. The argument is a channel name, which is useful when
you use several loggers (see below for more details about it).

The logger itself does not know how to handle a record. It delegates it to
some handlers. The code above registers two handlers in the stack to allow
handling records in two different ways.

Note that the FirePHPHandler is called first as it is added on top of the
stack. This allows you to temporarily add a logger with bubbling disabled if
you want to override other configured loggers.

> If you use Monolog standalone and are looking for an easy way to
> configure many handlers, the [theorchard/monolog-cascade](https://github.com/theorchard/monolog-cascade)
> can help you build complex logging configs via PHP arrays, yaml or json configs.

## Adding extra data in the records

Monolog provides two different ways to add extra informations along the simple
textual message.

### Using the logging context

The first way is the context, allowing to pass an array of data along the
record:

```php
<?php

$logger->addInfo('Adding a new user', array('username' => 'Seldaek'));
```

Simple handlers (like the StreamHandler for instance) will simply format
the array to a string but richer handlers can take advantage of the context
(FirePHP is able to display arrays in pretty way for instance).

### Using processors

The second way is to add extra data for all records by using a processor.
Processors can be any callable. They will get the record as parameter and
must return it after having eventually changed the `extra` part of it. Let's
write a processor adding some dummy data in the record:

```php
<?php

$logger->pushProcessor(function ($record) {
    $record['extra']['dummy'] = 'Hello world!';

    return $record;
});
```

Monolog provides some built-in processors that can be used in your project.
Look at the [dedicated chapter](https://github.com/Seldaek/monolog/blob/master/doc/02-handlers-formatters-processors.md#processors) for the list.

> Tip: processors can also be registered on a specific handler instead of
  the logger to apply only for this handler.

## Leveraging channels

Channels are a great way to identify to which part of the application a record
is related. This is useful in big applications (and is leveraged by
MonologBundle in Symfony2).

Picture two loggers sharing a handler that writes to a single log file.
Channels would allow you to identify the logger that issued every record.
You can easily grep through the log files filtering this or that channel.

```php
<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;

// Create some handlers
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$firephp = new FirePHPHandler();

// Create the main logger of the app
$logger = new Logger('my_logger');
$logger->pushHandler($stream);
$logger->pushHandler($firephp);

// Create a logger for the security-related stuff with a different channel
$securityLogger = new Logger('security');
$securityLogger->pushHandler($stream);
$securityLogger->pushHandler($firephp);

// Or clone the first one to only change the channel
$securityLogger = $logger->withName('security');
```

## Customizing the log format

In Monolog it's easy to customize the format of the logs written into files,
sockets, mails, databases and other handlers. Most of the handlers use the

```php
$record['formatted']
```

value to be automatically put into the log device. This value depends on the
formatter settings. You can choose between predefined formatter classes or
write your own (e.g. a multiline text file for human-readable output).

To configure a predefined formatter class, just set it as the handler's field:

```php
// the default date format is "Y-m-d H:i:s"
$dateFormat = "Y n j, g:i a";
// the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
$output = "%datetime% > %level_name% > %message% %context% %extra%\n";
// finally, create a formatter
$formatter = new LineFormatter($output, $dateFormat);

// Create a handler
$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);
$stream->setFormatter($formatter);
// bind it to a logger object
$securityLogger = new Logger('security');
$securityLogger->pushHandler($stream);
```

You may also reuse the same formatter between multiple handlers and share those
handlers between multiple loggers.

[Handlers, Formatters and Processors](02-handlers-formatters-processors.md) &rarr;
# Handlers, Formatters and Processors

- [Handlers](#handlers)
  - [Log to files and syslog](#log-to-files-and-syslog)
  - [Send alerts and emails](#send-alerts-and-emails)
  - [Log specific servers and networked logging](#log-specific-servers-and-networked-logging)
  - [Logging in development](#logging-in-development)
  - [Log to databases](#log-to-databases)
  - [Wrappers / Special Handlers](#wrappers--special-handlers)
- [Formatters](#formatters)
- [Processors](#processors)
- [Third Party Packages](#third-party-packages)

## Handlers

### Log to files and syslog

- _StreamHandler_: Logs records into any PHP stream, use this for log files.
- _RotatingFileHandler_: Logs records to a file and creates one logfile per day.
  It will also delete files older than `$maxFiles`. You should use
  [logrotate](http://linuxcommand.org/man_pages/logrotate8.html) for high profile
  setups though, this is just meant as a quick and dirty solution.
- _SyslogHandler_: Logs records to the syslog.
- _ErrorLogHandler_: Logs records to PHP's
  [`error_log()`](http://docs.php.net/manual/en/function.error-log.php) function.

### Send alerts and emails

- _NativeMailerHandler_: Sends emails using PHP's
  [`mail()`](http://php.net/manual/en/function.mail.php) function.
- _SwiftMailerHandler_: Sends emails using a [`Swift_Mailer`](http://swiftmailer.org/) instance.
- _PushoverHandler_: Sends mobile notifications via the [Pushover](https://www.pushover.net/) API.
- _HipChatHandler_: Logs records to a [HipChat](http://hipchat.com) chat room using its API.
- _FlowdockHandler_: Logs records to a [Flowdock](https://www.flowdock.com/) account.
- _SlackHandler_: Logs records to a [Slack](https://www.slack.com/) account.
- _MandrillHandler_: Sends emails via the Mandrill API using a [`Swift_Message`](http://swiftmailer.org/) instance.
- _FleepHookHandler_: Logs records to a [Fleep](https://fleep.io/) conversation using Webhooks.
- _IFTTTHandler_: Notifies an [IFTTT](https://ifttt.com/maker) trigger with the log channel, level name and message.

### Log specific servers and networked logging

- _SocketHandler_: Logs records to [sockets](http://php.net/fsockopen), use this
  for UNIX and TCP sockets. See an [example](sockets.md).
- _AmqpHandler_: Logs records to an [amqp](http://www.amqp.org/) compatible
  server. Requires the [php-amqp](http://pecl.php.net/package/amqp) extension (1.0+).
- _GelfHandler_: Logs records to a [Graylog2](http://www.graylog2.org) server.
- _CubeHandler_: Logs records to a [Cube](http://square.github.com/cube/) server.
- _RavenHandler_: Logs records to a [Sentry](http://getsentry.com/) server using
  [raven](https://packagist.org/packages/raven/raven).
- _ZendMonitorHandler_: Logs records to the Zend Monitor present in Zend Server.
- _NewRelicHandler_: Logs records to a [NewRelic](http://newrelic.com/) application.
- _LogglyHandler_: Logs records to a [Loggly](http://www.loggly.com/) account.
- _RollbarHandler_: Logs records to a [Rollbar](https://rollbar.com/) account.
- _SyslogUdpHandler_: Logs records to a remote [Syslogd](http://www.rsyslog.com/) server.
- _LogEntriesHandler_: Logs records to a [LogEntries](http://logentries.com/) account.

### Logging in development

- _FirePHPHandler_: Handler for [FirePHP](http://www.firephp.org/), providing
  inline `console` messages within [FireBug](http://getfirebug.com/).
- _ChromePHPHandler_: Handler for [ChromePHP](http://www.chromephp.com/), providing
  inline `console` messages within Chrome.
- _BrowserConsoleHandler_: Handler to send logs to browser's Javascript `console` with
  no browser extension required. Most browsers supporting `console` API are supported.
- _PHPConsoleHandler_: Handler for [PHP Console](https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef), providing
  inline `console` and notification popup messages within Chrome.

### Log to databases

- _RedisHandler_: Logs records to a [redis](http://redis.io) server.
- _MongoDBHandler_: Handler to write records in MongoDB via a
  [Mongo](http://pecl.php.net/package/mongo) extension connection.
- _CouchDBHandler_: Logs records to a CouchDB server.
- _DoctrineCouchDBHandler_: Logs records to a CouchDB server via the Doctrine CouchDB ODM.
- _ElasticSearchHandler_: Logs records to an Elastic Search server.
- _DynamoDbHandler_: Logs records to a DynamoDB table with the [AWS SDK](https://github.com/aws/aws-sdk-php).

### Wrappers / Special Handlers

- _FingersCrossedHandler_: A very interesting wrapper. It takes a logger as
  parameter and will accumulate log records of all levels until a record
  exceeds the defined severity level. At which point it delivers all records,
  including those of lower severity, to the handler it wraps. This means that
  until an error actually happens you will not see anything in your logs, but
  when it happens you will have the full information, including debug and info
  records. This provides you with all the information you need, but only when
  you need it.
- _WhatFailureGroupHandler_: This handler extends the _GroupHandler_ ignoring
   exceptions raised by each child handler. This allows you to ignore issues
   where a remote tcp connection may have died but you do not want your entire
   application to crash and may wish to continue to log to other handlers.
- _BufferHandler_: This handler will buffer all the log records it receives
  until `close()` is called at which point it will call `handleBatch()` on the
  handler it wraps with all the log messages at once. This is very useful to
  send an email with all records at once for example instead of having one mail
  for every log record.
- _GroupHandler_: This handler groups other handlers. Every record received is
  sent to all the handlers it is configured with.
- _FilterHandler_: This handler only lets records of the given levels through
   to the wrapped handler.
- _SamplingHandler_: Wraps around another handler and lets you sample records
   if you only want to store some of them.
- _NullHandler_: Any record it can handle will be thrown away. This can be used
  to put on top of an existing handler stack to disable it temporarily.
- _PsrHandler_: Can be used to forward log records to an existing PSR-3 logger
- _TestHandler_: Used for testing, it records everything that is sent to it and
  has accessors to read out the information.
- _HandlerWrapper_: A simple handler wrapper you can inherit from to create
 your own wrappers easily.

## Formatters

- _LineFormatter_: Formats a log record into a one-line string.
- _HtmlFormatter_: Used to format log records into a human readable html table, mainly suitable for emails.
- _NormalizerFormatter_: Normalizes objects/resources down to strings so a record can easily be serialized/encoded.
- _ScalarFormatter_: Used to format log records into an associative array of scalar values.
- _JsonFormatter_: Encodes a log record into json.
- _WildfireFormatter_: Used to format log records into the Wildfire/FirePHP protocol, only useful for the FirePHPHandler.
- _ChromePHPFormatter_: Used to format log records into the ChromePHP format, only useful for the ChromePHPHandler.
- _GelfMessageFormatter_: Used to format log records into Gelf message instances, only useful for the GelfHandler.
- _LogstashFormatter_: Used to format log records into [logstash](http://logstash.net/) event json, useful for any handler listed under inputs [here](http://logstash.net/docs/latest).
- _ElasticaFormatter_: Used to format log records into an Elastica\Document object, only useful for the ElasticSearchHandler.
- _LogglyFormatter_: Used to format log records into Loggly messages, only useful for the LogglyHandler.
- _FlowdockFormatter_: Used to format log records into Flowdock messages, only useful for the FlowdockHandler.
- _MongoDBFormatter_: Converts \DateTime instances to \MongoDate and objects recursively to arrays, only useful with the MongoDBHandler.

## Processors

- _PsrLogMessageProcessor_: Processes a log record's message according to PSR-3 rules, replacing `{foo}` with the value from `$context['foo']`.
- _IntrospectionProcessor_: Adds the line/file/class/method from which the log call originated.
- _WebProcessor_: Adds the current request URI, request method and client IP to a log record.
- _MemoryUsageProcessor_: Adds the current memory usage to a log record.
- _MemoryPeakUsageProcessor_: Adds the peak memory usage to a log record.
- _ProcessIdProcessor_: Adds the process id to a log record.
- _UidProcessor_: Adds a unique identifier to a log record.
- _GitProcessor_: Adds the current git branch and commit to a log record.
- _TagProcessor_: Adds an array of predefined tags to a log record.

## Third Party Packages

Third party handlers, formatters and processors are
[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You
can also add your own there if you publish one.

&larr; [Usage](01-usage.md) |  [Utility classes](03-utilities.md) &rarr;
Sockets Handler
===============

This handler allows you to write your logs to sockets using [fsockopen](http://php.net/fsockopen)
or [pfsockopen](http://php.net/pfsockopen).

Persistent sockets are mainly useful in web environments where you gain some performance not closing/opening
the connections between requests.

You can use a `unix://` prefix to access unix sockets and `udp://` to open UDP sockets instead of the default TCP.

Basic Example
-------------

```php
<?php

use Monolog\Logger;
use Monolog\Handler\SocketHandler;

// Create the logger
$logger = new Logger('my_logger');

// Create the handler
$handler = new SocketHandler('unix:///var/log/httpd_app_log.socket');
$handler->setPersistent(true);

// Now add the handler
$logger->pushHandler($handler, Logger::DEBUG);

// You can now use your logger
$logger->addInfo('My logger is now ready');

```

In this example, using syslog-ng, you should see the log on the log server:

    cweb1 [2012-02-26 00:12:03] my_logger.INFO: My logger is now ready [] []

# Extending Monolog

Monolog is fully extensible, allowing you to adapt your logger to your needs.

## Writing your own handler

Monolog provides many built-in handlers. But if the one you need does not
exist, you can write it and use it in your logger. The only requirement is
to implement `Monolog\Handler\HandlerInterface`.

Let's write a PDOHandler to log records to a database. We will extend the
abstract class provided by Monolog to keep things DRY.

```php
<?php

use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;

class PDOHandler extends AbstractProcessingHandler
{
    private $initialized = false;
    private $pdo;
    private $statement;

    public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)
    {
        $this->pdo = $pdo;
        parent::__construct($level, $bubble);
    }

    protected function write(array $record)
    {
        if (!$this->initialized) {
            $this->initialize();
        }

        $this->statement->execute(array(
            'channel' => $record['channel'],
            'level' => $record['level'],
            'message' => $record['formatted'],
            'time' => $record['datetime']->format('U'),
        ));
    }

    private function initialize()
    {
        $this->pdo->exec(
            'CREATE TABLE IF NOT EXISTS monolog '
            .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)'
        );
        $this->statement = $this->pdo->prepare(
            'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)'
        );

        $this->initialized = true;
    }
}
```

You can now use this handler in your logger:

```php
<?php

$logger->pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite')));

// You can now use your logger
$logger->addInfo('My logger is now ready');
```

The `Monolog\Handler\AbstractProcessingHandler` class provides most of the
logic needed for the handler, including the use of processors and the formatting
of the record (which is why we use ``$record['formatted']`` instead of ``$record['message']``).

&larr; [Utility classes](03-utilities.md)
# Utilities

- _Registry_: The `Monolog\Registry` class lets you configure global loggers that you
  can then statically access from anywhere. It is not really a best practice but can
  help in some older codebases or for ease of use.
- _ErrorHandler_: The `Monolog\ErrorHandler` class allows you to easily register
  a Logger instance as an exception handler, error handler or fatal error handler.
- _ErrorLevelActivationStrategy_: Activates a FingersCrossedHandler when a certain log
  level is reached.
- _ChannelLevelActivationStrategy_: Activates a FingersCrossedHandler when a certain
  log level is reached, depending on which channel received the log record.

&larr; [Handlers, Formatters and Processors](02-handlers-formatters-processors.md) |  [Extending Monolog](04-extending.md) &rarr;
<?xml version="1.0" encoding="UTF-8"?>

<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="Monolog Test Suite">
            <directory>tests/Monolog/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory suffix=".php">src/Monolog/</directory>
        </whitelist>
    </filter>

    <php>
        <ini name="date.timezone" value="UTC"/>
    </php>
</phpunit>
{
    "name": "monolog/monolog",
    "description": "Sends your logs to files, sockets, inboxes, databases and various web services",
    "keywords": ["log", "logging", "psr-3"],
    "homepage": "http://github.com/Seldaek/monolog",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Jordi Boggiano",
            "email": "j.boggiano@seld.be",
            "homepage": "http://seld.be"
        }
    ],
    "require": {
        "php": ">=5.3.0",
        "psr/log": "~1.0"
    },
    "require-dev": {
        "phpunit/phpunit": "~4.5",
        "graylog2/gelf-php": "~1.0",
        "sentry/sentry": "^0.13",
        "ruflin/elastica": ">=0.90 <3.0",
        "doctrine/couchdb": "~1.0@dev",
        "aws/aws-sdk-php": "^2.4.9 || ^3.0",
        "php-amqplib/php-amqplib": "~2.4",
        "swiftmailer/swiftmailer": "^5.3|^6.0",
        "php-console/php-console": "^3.1.3",
        "phpstan/phpstan": "^0.12.59"
    },
    "suggest": {
        "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
        "sentry/sentry": "Allow sending log messages to a Sentry server",
        "doctrine/couchdb": "Allow sending log messages to a CouchDB server",
        "ruflin/elastica": "Allow sending log messages to an Elastic Search server",
        "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
        "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
        "ext-mongo": "Allow sending log messages to a MongoDB server",
        "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver",
        "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
        "rollbar/rollbar": "Allow sending log messages to Rollbar",
        "php-console/php-console": "Allow sending log messages to Google Chrome"
    },
    "autoload": {
        "psr-4": {"Monolog\\": "src/Monolog"}
    },
    "autoload-dev": {
        "psr-4": {"Monolog\\": "tests/Monolog"}
    },
    "provide": {
        "psr/log-implementation": "1.0.0"
    },
    "scripts": {
        "test": "vendor/bin/phpunit",
        "phpstan": "vendor/bin/phpstan analyse"
    },
    "config": {
        "lock": false
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

 namespace Monolog\Handler;
 
 use Monolog\Logger;

/**
 * Inspired on LogEntriesHandler.
 *
 * @author Robert Kaufmann III <rok3@rok3.me>
 * @author Gabriel Machado <gabriel.ms1@hotmail.com>
 */
class InsightOpsHandler extends SocketHandler
{
    /**
     * @var string
     */
    protected $logToken;

    /**
     * @param string $token  Log token supplied by InsightOps
     * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'.
     * @param bool   $useSSL Whether or not SSL encryption should be used
     * @param int    $level  The minimum logging level to trigger this handler
     * @param bool   $bubble Whether or not messages that are handled should bubble up the stack.
     *
     * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
     */
    public function __construct($token, $region = 'us', $useSSL = true, $level = Logger::DEBUG, $bubble = true)
    {
        if ($useSSL && !extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for InsightOpsHandler');
        }

        $endpoint = $useSSL
            ? 'ssl://' . $region . '.data.logs.insight.rapid7.com:443'
            : $region . '.data.logs.insight.rapid7.com:80';

        parent::__construct($endpoint, $level, $bubble);
        $this->logToken = $token;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        return $this->logToken . ' ' . $record['formatted'];
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

/**
 * Used for testing purposes.
 *
 * It records all records and gives you access to them for verification.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 *
 * @method bool hasEmergency($record)
 * @method bool hasAlert($record)
 * @method bool hasCritical($record)
 * @method bool hasError($record)
 * @method bool hasWarning($record)
 * @method bool hasNotice($record)
 * @method bool hasInfo($record)
 * @method bool hasDebug($record)
 *
 * @method bool hasEmergencyRecords()
 * @method bool hasAlertRecords()
 * @method bool hasCriticalRecords()
 * @method bool hasErrorRecords()
 * @method bool hasWarningRecords()
 * @method bool hasNoticeRecords()
 * @method bool hasInfoRecords()
 * @method bool hasDebugRecords()
 *
 * @method bool hasEmergencyThatContains($message)
 * @method bool hasAlertThatContains($message)
 * @method bool hasCriticalThatContains($message)
 * @method bool hasErrorThatContains($message)
 * @method bool hasWarningThatContains($message)
 * @method bool hasNoticeThatContains($message)
 * @method bool hasInfoThatContains($message)
 * @method bool hasDebugThatContains($message)
 *
 * @method bool hasEmergencyThatMatches($message)
 * @method bool hasAlertThatMatches($message)
 * @method bool hasCriticalThatMatches($message)
 * @method bool hasErrorThatMatches($message)
 * @method bool hasWarningThatMatches($message)
 * @method bool hasNoticeThatMatches($message)
 * @method bool hasInfoThatMatches($message)
 * @method bool hasDebugThatMatches($message)
 *
 * @method bool hasEmergencyThatPasses($message)
 * @method bool hasAlertThatPasses($message)
 * @method bool hasCriticalThatPasses($message)
 * @method bool hasErrorThatPasses($message)
 * @method bool hasWarningThatPasses($message)
 * @method bool hasNoticeThatPasses($message)
 * @method bool hasInfoThatPasses($message)
 * @method bool hasDebugThatPasses($message)
 */
class TestHandler extends AbstractProcessingHandler
{
    protected $records = array();
    protected $recordsByLevel = array();
    private $skipReset = false;

    public function getRecords()
    {
        return $this->records;
    }

    public function clear()
    {
        $this->records = array();
        $this->recordsByLevel = array();
    }

    public function reset()
    {
        if (!$this->skipReset) {
            $this->clear();
        }
    }

    public function setSkipReset($skipReset)
    {
        $this->skipReset = $skipReset;
    }

    public function hasRecords($level)
    {
        return isset($this->recordsByLevel[$level]);
    }

    /**
     * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records
     * @param int          $level  Logger::LEVEL constant value
     */
    public function hasRecord($record, $level)
    {
        if (is_string($record)) {
            $record = array('message' => $record);
        }

        return $this->hasRecordThatPasses(function ($rec) use ($record) {
            if ($rec['message'] !== $record['message']) {
                return false;
            }
            if (isset($record['context']) && $rec['context'] !== $record['context']) {
                return false;
            }
            return true;
        }, $level);
    }

    public function hasRecordThatContains($message, $level)
    {
        return $this->hasRecordThatPasses(function ($rec) use ($message) {
            return strpos($rec['message'], $message) !== false;
        }, $level);
    }

    public function hasRecordThatMatches($regex, $level)
    {
        return $this->hasRecordThatPasses(function ($rec) use ($regex) {
            return preg_match($regex, $rec['message']) > 0;
        }, $level);
    }

    public function hasRecordThatPasses($predicate, $level)
    {
        if (!is_callable($predicate)) {
            throw new \InvalidArgumentException("Expected a callable for hasRecordThatSucceeds");
        }

        if (!isset($this->recordsByLevel[$level])) {
            return false;
        }

        foreach ($this->recordsByLevel[$level] as $i => $rec) {
            if (call_user_func($predicate, $rec, $i)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $this->recordsByLevel[$record['level']][] = $record;
        $this->records[] = $record;
    }

    public function __call($method, $args)
    {
        if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
            $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3];
            $level = constant('Monolog\Logger::' . strtoupper($matches[2]));
            if (method_exists($this, $genericMethod)) {
                $args[] = $level;

                return call_user_func_array(array($this, $genericMethod), $args);
            }
        }

        throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;

/**
 * IFTTTHandler uses cURL to trigger IFTTT Maker actions
 *
 * Register a secret key and trigger/event name at https://ifttt.com/maker
 *
 * value1 will be the channel from monolog's Logger constructor,
 * value2 will be the level name (ERROR, WARNING, ..)
 * value3 will be the log record's message
 *
 * @author Nehal Patel <nehal@nehalpatel.me>
 */
class IFTTTHandler extends AbstractProcessingHandler
{
    private $eventName;
    private $secretKey;

    /**
     * @param string $eventName The name of the IFTTT Maker event that should be triggered
     * @param string $secretKey A valid IFTTT secret key
     * @param int    $level     The minimum logging level at which this handler will be triggered
     * @param bool   $bubble    Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($eventName, $secretKey, $level = Logger::ERROR, $bubble = true)
    {
        $this->eventName = $eventName;
        $this->secretKey = $secretKey;

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritdoc}
     */
    public function write(array $record)
    {
        $postData = array(
            "value1" => $record["channel"],
            "value2" => $record["level_name"],
            "value3" => $record["message"],
        );
        $postString = Utils::jsonEncode($postData);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
        ));

        Curl\Util::execute($ch);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Stores to any socket - uses fsockopen() or pfsockopen().
 *
 * @author Pablo de Leon Belloc <pablolb@gmail.com>
 * @see    http://php.net/manual/en/function.fsockopen.php
 */
class SocketHandler extends AbstractProcessingHandler
{
    private $connectionString;
    private $connectionTimeout;
    private $resource;
    private $timeout = 0;
    private $writingTimeout = 10;
    private $lastSentBytes = null;
    private $chunkSize = null;
    private $persistent = false;
    private $errno;
    private $errstr;
    private $lastWritingAt;

    /**
     * @param string $connectionString Socket connection string
     * @param int    $level            The minimum logging level at which this handler will be triggered
     * @param bool   $bubble           Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->connectionString = $connectionString;
        $this->connectionTimeout = (float) ini_get('default_socket_timeout');
    }

    /**
     * Connect (if necessary) and write to the socket
     *
     * @param array $record
     *
     * @throws \UnexpectedValueException
     * @throws \RuntimeException
     */
    protected function write(array $record)
    {
        $this->connectIfNotConnected();
        $data = $this->generateDataStream($record);
        $this->writeToSocket($data);
    }

    /**
     * We will not close a PersistentSocket instance so it can be reused in other requests.
     */
    public function close()
    {
        if (!$this->isPersistent()) {
            $this->closeSocket();
        }
    }

    /**
     * Close socket, if open
     */
    public function closeSocket()
    {
        if (is_resource($this->resource)) {
            fclose($this->resource);
            $this->resource = null;
        }
    }

    /**
     * Set socket connection to nbe persistent. It only has effect before the connection is initiated.
     *
     * @param bool $persistent
     */
    public function setPersistent($persistent)
    {
        $this->persistent = (bool) $persistent;
    }

    /**
     * Set connection timeout.  Only has effect before we connect.
     *
     * @param float $seconds
     *
     * @see http://php.net/manual/en/function.fsockopen.php
     */
    public function setConnectionTimeout($seconds)
    {
        $this->validateTimeout($seconds);
        $this->connectionTimeout = (float) $seconds;
    }

    /**
     * Set write timeout. Only has effect before we connect.
     *
     * @param float $seconds
     *
     * @see http://php.net/manual/en/function.stream-set-timeout.php
     */
    public function setTimeout($seconds)
    {
        $this->validateTimeout($seconds);
        $this->timeout = (float) $seconds;
    }

    /**
     * Set writing timeout. Only has effect during connection in the writing cycle.
     *
     * @param float $seconds 0 for no timeout
     */
    public function setWritingTimeout($seconds)
    {
        $this->validateTimeout($seconds);
        $this->writingTimeout = (float) $seconds;
    }

    /**
     * Set chunk size. Only has effect during connection in the writing cycle.
     *
     * @param float $bytes
     */
    public function setChunkSize($bytes)
    {
        $this->chunkSize = $bytes;
    }

    /**
     * Get current connection string
     *
     * @return string
     */
    public function getConnectionString()
    {
        return $this->connectionString;
    }

    /**
     * Get persistent setting
     *
     * @return bool
     */
    public function isPersistent()
    {
        return $this->persistent;
    }

    /**
     * Get current connection timeout setting
     *
     * @return float
     */
    public function getConnectionTimeout()
    {
        return $this->connectionTimeout;
    }

    /**
     * Get current in-transfer timeout
     *
     * @return float
     */
    public function getTimeout()
    {
        return $this->timeout;
    }

    /**
     * Get current local writing timeout
     *
     * @return float
     */
    public function getWritingTimeout()
    {
        return $this->writingTimeout;
    }

    /**
     * Get current chunk size
     *
     * @return float
     */
    public function getChunkSize()
    {
        return $this->chunkSize;
    }

    /**
     * Check to see if the socket is currently available.
     *
     * UDP might appear to be connected but might fail when writing.  See http://php.net/fsockopen for details.
     *
     * @return bool
     */
    public function isConnected()
    {
        return is_resource($this->resource)
            && !feof($this->resource);  // on TCP - other party can close connection.
    }

    /**
     * Wrapper to allow mocking
     */
    protected function pfsockopen()
    {
        return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
    }

    /**
     * Wrapper to allow mocking
     */
    protected function fsockopen()
    {
        return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
    }

    /**
     * Wrapper to allow mocking
     *
     * @see http://php.net/manual/en/function.stream-set-timeout.php
     */
    protected function streamSetTimeout()
    {
        $seconds = floor($this->timeout);
        $microseconds = round(($this->timeout - $seconds) * 1e6);

        return stream_set_timeout($this->resource, $seconds, $microseconds);
    }

    /**
     * Wrapper to allow mocking
     *
     * @see http://php.net/manual/en/function.stream-set-chunk-size.php
     */
    protected function streamSetChunkSize()
    {
        return stream_set_chunk_size($this->resource, $this->chunkSize);
    }

    /**
     * Wrapper to allow mocking
     */
    protected function fwrite($data)
    {
        return @fwrite($this->resource, $data);
    }

    /**
     * Wrapper to allow mocking
     */
    protected function streamGetMetadata()
    {
        return stream_get_meta_data($this->resource);
    }

    private function validateTimeout($value)
    {
        $ok = filter_var($value, FILTER_VALIDATE_FLOAT);
        if ($ok === false || $value < 0) {
            throw new \InvalidArgumentException("Timeout must be 0 or a positive float (got $value)");
        }
    }

    private function connectIfNotConnected()
    {
        if ($this->isConnected()) {
            return;
        }
        $this->connect();
    }

    protected function generateDataStream($record)
    {
        return (string) $record['formatted'];
    }

    /**
     * @return resource|null
     */
    protected function getResource()
    {
        return $this->resource;
    }

    private function connect()
    {
        $this->createSocketResource();
        $this->setSocketTimeout();
        $this->setStreamChunkSize();
    }

    private function createSocketResource()
    {
        if ($this->isPersistent()) {
            $resource = $this->pfsockopen();
        } else {
            $resource = $this->fsockopen();
        }
        if (!$resource) {
            throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)");
        }
        $this->resource = $resource;
    }

    private function setSocketTimeout()
    {
        if (!$this->streamSetTimeout()) {
            throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
        }
    }

    private function setStreamChunkSize()
    {
        if ($this->chunkSize && !$this->streamSetChunkSize()) {
            throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()");
        }
    }

    private function writeToSocket($data)
    {
        $length = strlen($data);
        $sent = 0;
        $this->lastSentBytes = $sent;
        while ($this->isConnected() && $sent < $length) {
            if (0 == $sent) {
                $chunk = $this->fwrite($data);
            } else {
                $chunk = $this->fwrite(substr($data, $sent));
            }
            if ($chunk === false) {
                throw new \RuntimeException("Could not write to socket");
            }
            $sent += $chunk;
            $socketInfo = $this->streamGetMetadata();
            if ($socketInfo['timed_out']) {
                throw new \RuntimeException("Write timed-out");
            }

            if ($this->writingIsTimedOut($sent)) {
                throw new \RuntimeException("Write timed-out, no data sent for `{$this->writingTimeout}` seconds, probably we got disconnected (sent $sent of $length)");
            }
        }
        if (!$this->isConnected() && $sent < $length) {
            throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)");
        }
    }

    private function writingIsTimedOut($sent)
    {
        $writingTimeout = (int) floor($this->writingTimeout);
        if (0 === $writingTimeout) {
            return false;
        }

        if ($sent !== $this->lastSentBytes) {
            $this->lastWritingAt = time();
            $this->lastSentBytes = $sent;

            return false;
        } else {
            usleep(100);
        }

        if ((time() - $this->lastWritingAt) >= $writingTimeout) {
            $this->closeSocket();

            return true;
        }

        return false;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Sends notifications through Slack's Slackbot
 *
 * @author     Haralan Dobrev <hkdobrev@gmail.com>
 * @see        https://slack.com/apps/A0F81R8ET-slackbot
 * @deprecated According to Slack the API used on this handler it is deprecated.
 *             Therefore this handler will be removed on 2.x
 *             Slack suggests to use webhooks instead. Please contact slack for more information.
 */
class SlackbotHandler extends AbstractProcessingHandler
{
    /**
     * The slug of the Slack team
     * @var string
     */
    private $slackTeam;

    /**
     * Slackbot token
     * @var string
     */
    private $token;

    /**
     * Slack channel name
     * @var string
     */
    private $channel;

    /**
     * @param  string $slackTeam Slack team slug
     * @param  string $token     Slackbot token
     * @param  string $channel   Slack channel (encoded ID or name)
     * @param  int    $level     The minimum logging level at which this handler will be triggered
     * @param  bool   $bubble    Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, $bubble = true)
    {
        @trigger_error('SlackbotHandler is deprecated and will be removed on 2.x', E_USER_DEPRECATED);
        parent::__construct($level, $bubble);

        $this->slackTeam = $slackTeam;
        $this->token = $token;
        $this->channel = $channel;
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        $slackbotUrl = sprintf(
            'https://%s.slack.com/services/hooks/slackbot?token=%s&channel=%s',
            $this->slackTeam,
            $this->token,
            $this->channel
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $slackbotUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $record['message']);

        Curl\Util::execute($ch);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface;

/**
 * Buffers all records until closing the handler and then pass them as batch.
 *
 * This is useful for a MailHandler to send only one mail per request instead of
 * sending one per log message.
 *
 * @author Christophe Coevoet <stof@notk.org>
 */
class BufferHandler extends AbstractHandler
{
    protected $handler;
    protected $bufferSize = 0;
    protected $bufferLimit;
    protected $flushOnOverflow;
    protected $buffer = array();
    protected $initialized = false;

    /**
     * @param HandlerInterface $handler         Handler.
     * @param int              $bufferLimit     How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
     * @param int              $level           The minimum logging level at which this handler will be triggered
     * @param bool             $bubble          Whether the messages that are handled can bubble up the stack or not
     * @param bool             $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
     */
    public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, $bubble = true, $flushOnOverflow = false)
    {
        parent::__construct($level, $bubble);
        $this->handler = $handler;
        $this->bufferLimit = (int) $bufferLimit;
        $this->flushOnOverflow = $flushOnOverflow;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if ($record['level'] < $this->level) {
            return false;
        }

        if (!$this->initialized) {
            // __destructor() doesn't get called on Fatal errors
            register_shutdown_function(array($this, 'close'));
            $this->initialized = true;
        }

        if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) {
            if ($this->flushOnOverflow) {
                $this->flush();
            } else {
                array_shift($this->buffer);
                $this->bufferSize--;
            }
        }

        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        $this->buffer[] = $record;
        $this->bufferSize++;

        return false === $this->bubble;
    }

    public function flush()
    {
        if ($this->bufferSize === 0) {
            return;
        }

        $this->handler->handleBatch($this->buffer);
        $this->clear();
    }

    public function __destruct()
    {
        // suppress the parent behavior since we already have register_shutdown_function()
        // to call close(), and the reference contained there will prevent this from being
        // GC'd until the end of the request
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        $this->flush();
    }

    /**
     * Clears the buffer without flushing any messages down to the wrapped handler.
     */
    public function clear()
    {
        $this->bufferSize = 0;
        $this->buffer = array();
    }

    public function reset()
    {
        $this->flush();

        parent::reset();

        if ($this->handler instanceof ResettableInterface) {
            $this->handler->reset();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->handler->setFormatter($formatter);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->handler->getFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Logs to syslog service.
 *
 * usage example:
 *
 *   $log = new Logger('application');
 *   $syslog = new SyslogHandler('myfacility', 'local6');
 *   $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%");
 *   $syslog->setFormatter($formatter);
 *   $log->pushHandler($syslog);
 *
 * @author Sven Paulus <sven@karlsruhe.org>
 */
class SyslogHandler extends AbstractSyslogHandler
{
    protected $ident;
    protected $logopts;

    /**
     * @param string $ident
     * @param mixed  $facility
     * @param int    $level    The minimum logging level at which this handler will be triggered
     * @param bool   $bubble   Whether the messages that are handled can bubble up the stack or not
     * @param int    $logopts  Option flags for the openlog() call, defaults to LOG_PID
     */
    public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $logopts = LOG_PID)
    {
        parent::__construct($facility, $level, $bubble);

        $this->ident = $ident;
        $this->logopts = $logopts;
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        closelog();
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        if (!openlog($this->ident, $this->logopts, $this->facility)) {
            throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"');
        }
        syslog($this->logLevels[$record['level']], (string) $record['formatted']);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use RollbarNotifier;
use Exception;
use Monolog\Logger;

/**
 * Sends errors to Rollbar
 *
 * If the context data contains a `payload` key, that is used as an array
 * of payload options to RollbarNotifier's report_message/report_exception methods.
 *
 * Rollbar's context info will contain the context + extra keys from the log record
 * merged, and then on top of that a few keys:
 *
 *  - level (rollbar level name)
 *  - monolog_level (monolog level name, raw level, as rollbar only has 5 but monolog 8)
 *  - channel
 *  - datetime (unix timestamp)
 *
 * @author Paul Statezny <paulstatezny@gmail.com>
 */
class RollbarHandler extends AbstractProcessingHandler
{
    /**
     * Rollbar notifier
     *
     * @var RollbarNotifier
     */
    protected $rollbarNotifier;

    protected $levelMap = array(
        Logger::DEBUG     => 'debug',
        Logger::INFO      => 'info',
        Logger::NOTICE    => 'info',
        Logger::WARNING   => 'warning',
        Logger::ERROR     => 'error',
        Logger::CRITICAL  => 'critical',
        Logger::ALERT     => 'critical',
        Logger::EMERGENCY => 'critical',
    );

    /**
     * Records whether any log records have been added since the last flush of the rollbar notifier
     *
     * @var bool
     */
    private $hasRecords = false;

    protected $initialized = false;

    /**
     * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token
     * @param int             $level           The minimum logging level at which this handler will be triggered
     * @param bool            $bubble          Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true)
    {
        $this->rollbarNotifier = $rollbarNotifier;

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        if (!$this->initialized) {
            // __destructor() doesn't get called on Fatal errors
            register_shutdown_function(array($this, 'close'));
            $this->initialized = true;
        }

        $context = $record['context'];
        $payload = array();
        if (isset($context['payload'])) {
            $payload = $context['payload'];
            unset($context['payload']);
        }
        $context = array_merge($context, $record['extra'], array(
            'level' => $this->levelMap[$record['level']],
            'monolog_level' => $record['level_name'],
            'channel' => $record['channel'],
            'datetime' => $record['datetime']->format('U'),
        ));

        if (isset($context['exception']) && $context['exception'] instanceof Exception) {
            $payload['level'] = $context['level'];
            $exception = $context['exception'];
            unset($context['exception']);

            $this->rollbarNotifier->report_exception($exception, $context, $payload);
        } else {
            $this->rollbarNotifier->report_message(
                $record['message'],
                $context['level'],
                $context,
                $payload
            );
        }

        $this->hasRecords = true;
    }

    public function flush()
    {
        if ($this->hasRecords) {
            $this->rollbarNotifier->flush();
            $this->hasRecords = false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        $this->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function reset()
    {
        $this->flush();

        parent::reset();
    }


}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Monolog\Handler\FingersCrossed\ActivationStrategyInterface;
use Monolog\Logger;
use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface;

/**
 * Buffers all records until a certain level is reached
 *
 * The advantage of this approach is that you don't get any clutter in your log files.
 * Only requests which actually trigger an error (or whatever your actionLevel is) will be
 * in the logs, but they will contain all records, not only those above the level threshold.
 *
 * You can find the various activation strategies in the
 * Monolog\Handler\FingersCrossed\ namespace.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class FingersCrossedHandler extends AbstractHandler
{
    protected $handler;
    protected $activationStrategy;
    protected $buffering = true;
    protected $bufferSize;
    protected $buffer = array();
    protected $stopBuffering;
    protected $passthruLevel;

    /**
     * @param callable|HandlerInterface       $handler            Handler or factory callable($record|null, $fingersCrossedHandler).
     * @param int|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action
     * @param int                             $bufferSize         How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
     * @param bool                            $bubble             Whether the messages that are handled can bubble up the stack or not
     * @param bool                            $stopBuffering      Whether the handler should stop buffering after being triggered (default true)
     * @param int                             $passthruLevel      Minimum level to always flush to handler on close, even if strategy not triggered
     */
    public function __construct($handler, $activationStrategy = null, $bufferSize = 0, $bubble = true, $stopBuffering = true, $passthruLevel = null)
    {
        if (null === $activationStrategy) {
            $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING);
        }

        // convert simple int activationStrategy to an object
        if (!$activationStrategy instanceof ActivationStrategyInterface) {
            $activationStrategy = new ErrorLevelActivationStrategy($activationStrategy);
        }

        $this->handler = $handler;
        $this->activationStrategy = $activationStrategy;
        $this->bufferSize = $bufferSize;
        $this->bubble = $bubble;
        $this->stopBuffering = $stopBuffering;

        if ($passthruLevel !== null) {
            $this->passthruLevel = Logger::toMonologLevel($passthruLevel);
        }

        if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) {
            throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object");
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        return true;
    }

    /**
     * Manually activate this logger regardless of the activation strategy
     */
    public function activate()
    {
        if ($this->stopBuffering) {
            $this->buffering = false;
        }
        $this->getHandler(end($this->buffer) ?: null)->handleBatch($this->buffer);
        $this->buffer = array();
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        if ($this->buffering) {
            $this->buffer[] = $record;
            if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) {
                array_shift($this->buffer);
            }
            if ($this->activationStrategy->isHandlerActivated($record)) {
                $this->activate();
            }
        } else {
            $this->getHandler($record)->handle($record);
        }

        return false === $this->bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        $this->flushBuffer();
    }

    public function reset()
    {
        $this->flushBuffer();

        parent::reset();

        if ($this->getHandler() instanceof ResettableInterface) {
            $this->getHandler()->reset();
        }
    }

    /**
     * Clears the buffer without flushing any messages down to the wrapped handler.
     *
     * It also resets the handler to its initial buffering state.
     */
    public function clear()
    {
        $this->buffer = array();
        $this->reset();
    }

    /**
     * Resets the state of the handler. Stops forwarding records to the wrapped handler.
     */
    private function flushBuffer()
    {
        if (null !== $this->passthruLevel) {
            $level = $this->passthruLevel;
            $this->buffer = array_filter($this->buffer, function ($record) use ($level) {
                return $record['level'] >= $level;
            });
            if (count($this->buffer) > 0) {
                $this->getHandler(end($this->buffer) ?: null)->handleBatch($this->buffer);
            }
        }

        $this->buffer = array();
        $this->buffering = true;
    }

    /**
     * Return the nested handler
     *
     * If the handler was provided as a factory callable, this will trigger the handler's instantiation.
     *
     * @return HandlerInterface
     */
    public function getHandler(array $record = null)
    {
        if (!$this->handler instanceof HandlerInterface) {
            $this->handler = call_user_func($this->handler, $record, $this);
            if (!$this->handler instanceof HandlerInterface) {
                throw new \RuntimeException("The factory callable should return a HandlerInterface");
            }
        }

        return $this->handler;
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->getHandler()->setFormatter($formatter);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->getHandler()->getFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\ResettableInterface;
use Monolog\Formatter\FormatterInterface;

/**
 * This simple wrapper class can be used to extend handlers functionality.
 *
 * Example: A custom filtering that can be applied to any handler.
 *
 * Inherit from this class and override handle() like this:
 *
 *   public function handle(array $record)
 *   {
 *        if ($record meets certain conditions) {
 *            return false;
 *        }
 *        return $this->handler->handle($record);
 *   }
 *
 * @author Alexey Karapetov <alexey@karapetov.com>
 */
class HandlerWrapper implements HandlerInterface, ResettableInterface
{
    /**
     * @var HandlerInterface
     */
    protected $handler;

    /**
     * HandlerWrapper constructor.
     * @param HandlerInterface $handler
     */
    public function __construct(HandlerInterface $handler)
    {
        $this->handler = $handler;
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        return $this->handler->isHandling($record);
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        return $this->handler->handle($record);
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        return $this->handler->handleBatch($records);
    }

    /**
     * {@inheritdoc}
     */
    public function pushProcessor($callback)
    {
        $this->handler->pushProcessor($callback);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function popProcessor()
    {
        return $this->handler->popProcessor();
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->handler->setFormatter($formatter);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->handler->getFormatter();
    }

    public function reset()
    {
        if ($this->handler instanceof ResettableInterface) {
            return $this->handler->reset();
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\FingersCrossed;

/**
 * Interface for activation strategies for the FingersCrossedHandler.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface ActivationStrategyInterface
{
    /**
     * Returns whether the given record activates the handler.
     *
     * @param  array   $record
     * @return bool
     */
    public function isHandlerActivated(array $record);
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\FingersCrossed;

use Monolog\Logger;

/**
 * Error level based activation strategy.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class ErrorLevelActivationStrategy implements ActivationStrategyInterface
{
    private $actionLevel;

    public function __construct($actionLevel)
    {
        $this->actionLevel = Logger::toMonologLevel($actionLevel);
    }

    public function isHandlerActivated(array $record)
    {
        return $record['level'] >= $this->actionLevel;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\FingersCrossed;

use Monolog\Logger;

/**
 * Channel and Error level based monolog activation strategy. Allows to trigger activation
 * based on level per channel. e.g. trigger activation on level 'ERROR' by default, except
 * for records of the 'sql' channel; those should trigger activation on level 'WARN'.
 *
 * Example:
 *
 * <code>
 *   $activationStrategy = new ChannelLevelActivationStrategy(
 *       Logger::CRITICAL,
 *       array(
 *           'request' => Logger::ALERT,
 *           'sensitive' => Logger::ERROR,
 *       )
 *   );
 *   $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy);
 * </code>
 *
 * @author Mike Meessen <netmikey@gmail.com>
 */
class ChannelLevelActivationStrategy implements ActivationStrategyInterface
{
    private $defaultActionLevel;
    private $channelToActionLevel;

    /**
     * @param int   $defaultActionLevel   The default action level to be used if the record's category doesn't match any
     * @param array $channelToActionLevel An array that maps channel names to action levels.
     */
    public function __construct($defaultActionLevel, $channelToActionLevel = array())
    {
        $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel);
        $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel);
    }

    public function isHandlerActivated(array $record)
    {
        if (isset($this->channelToActionLevel[$record['channel']])) {
            return $record['level'] >= $this->channelToActionLevel[$record['channel']];
        }

        return $record['level'] >= $this->defaultActionLevel;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\ResettableInterface;

/**
 * Forwards records to multiple handlers
 *
 * @author Lenar Lõhmus <lenar@city.ee>
 */
class GroupHandler extends AbstractHandler
{
    protected $handlers;

    /**
     * @param array $handlers Array of Handlers.
     * @param bool  $bubble   Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(array $handlers, $bubble = true)
    {
        foreach ($handlers as $handler) {
            if (!$handler instanceof HandlerInterface) {
                throw new \InvalidArgumentException('The first argument of the GroupHandler must be an array of HandlerInterface instances.');
            }
        }

        $this->handlers = $handlers;
        $this->bubble = $bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->isHandling($record)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        foreach ($this->handlers as $handler) {
            $handler->handle($record);
        }

        return false === $this->bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        if ($this->processors) {
            $processed = array();
            foreach ($records as $record) {
                foreach ($this->processors as $processor) {
                    $record = call_user_func($processor, $record);
                }
                $processed[] = $record;
            }
            $records = $processed;
        }

        foreach ($this->handlers as $handler) {
            $handler->handleBatch($records);
        }
    }

    public function reset()
    {
        parent::reset();

        foreach ($this->handlers as $handler) {
            if ($handler instanceof ResettableInterface) {
                $handler->reset();
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        foreach ($this->handlers as $handler) {
            $handler->setFormatter($formatter);
        }

        return $this;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\ElasticaFormatter;
use Monolog\Logger;
use Elastica\Client;
use Elastica\Exception\ExceptionInterface;

/**
 * Elastic Search handler
 *
 * Usage example:
 *
 *    $client = new \Elastica\Client();
 *    $options = array(
 *        'index' => 'elastic_index_name',
 *        'type' => 'elastic_doc_type',
 *    );
 *    $handler = new ElasticSearchHandler($client, $options);
 *    $log = new Logger('application');
 *    $log->pushHandler($handler);
 *
 * @author Jelle Vink <jelle.vink@gmail.com>
 */
class ElasticSearchHandler extends AbstractProcessingHandler
{
    /**
     * @var Client
     */
    protected $client;

    /**
     * @var array Handler config options
     */
    protected $options = array();

    /**
     * @param Client $client  Elastica Client object
     * @param array  $options Handler configuration
     * @param int    $level   The minimum logging level at which this handler will be triggered
     * @param bool   $bubble  Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(Client $client, array $options = array(), $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->client = $client;
        $this->options = array_merge(
            array(
                'index'          => 'monolog',      // Elastic index name
                'type'           => 'record',       // Elastic document type
                'ignore_error'   => false,          // Suppress Elastica exceptions
            ),
            $options
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        $this->bulkSend(array($record['formatted']));
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        if ($formatter instanceof ElasticaFormatter) {
            return parent::setFormatter($formatter);
        }
        throw new \InvalidArgumentException('ElasticSearchHandler is only compatible with ElasticaFormatter');
    }

    /**
     * Getter options
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new ElasticaFormatter($this->options['index'], $this->options['type']);
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        $documents = $this->getFormatter()->formatBatch($records);
        $this->bulkSend($documents);
    }

    /**
     * Use Elasticsearch bulk API to send list of documents
     * @param  array             $documents
     * @throws \RuntimeException
     */
    protected function bulkSend(array $documents)
    {
        try {
            $this->client->addDocuments($documents);
        } catch (ExceptionInterface $e) {
            if (!$this->options['ignore_error']) {
                throw new \RuntimeException("Error sending messages to Elasticsearch", 0, $e);
            }
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;

/**
 * Sampling handler
 *
 * A sampled event stream can be useful for logging high frequency events in
 * a production environment where you only need an idea of what is happening
 * and are not concerned with capturing every occurrence. Since the decision to
 * handle or not handle a particular event is determined randomly, the
 * resulting sampled log is not guaranteed to contain 1/N of the events that
 * occurred in the application, but based on the Law of large numbers, it will
 * tend to be close to this ratio with a large number of attempts.
 *
 * @author Bryan Davis <bd808@wikimedia.org>
 * @author Kunal Mehta <legoktm@gmail.com>
 */
class SamplingHandler extends AbstractHandler
{
    /**
     * @var callable|HandlerInterface $handler
     */
    protected $handler;

    /**
     * @var int $factor
     */
    protected $factor;

    /**
     * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $samplingHandler).
     * @param int                       $factor  Sample factor
     */
    public function __construct($handler, $factor)
    {
        parent::__construct();
        $this->handler = $handler;
        $this->factor = $factor;

        if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) {
            throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object");
        }
    }

    public function isHandling(array $record)
    {
        return $this->getHandler($record)->isHandling($record);
    }

    public function handle(array $record)
    {
        if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) {
            if ($this->processors) {
                foreach ($this->processors as $processor) {
                    $record = call_user_func($processor, $record);
                }
            }

            $this->getHandler($record)->handle($record);
        }

        return false === $this->bubble;
    }

    /**
     * Return the nested handler
     *
     * If the handler was provided as a factory callable, this will trigger the handler's instantiation.
     *
     * @return HandlerInterface
     */
    public function getHandler(array $record = null)
    {
        if (!$this->handler instanceof HandlerInterface) {
            $this->handler = call_user_func($this->handler, $record, $this);
            if (!$this->handler instanceof HandlerInterface) {
                throw new \RuntimeException("The factory callable should return a HandlerInterface");
            }
        }

        return $this->handler;
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->getHandler()->setFormatter($formatter);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->getHandler()->getFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
use Monolog\ResettableInterface;

/**
 * Base Handler class providing the Handler structure
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
abstract class AbstractHandler implements HandlerInterface, ResettableInterface
{
    protected $level = Logger::DEBUG;
    protected $bubble = true;

    /**
     * @var FormatterInterface
     */
    protected $formatter;
    protected $processors = array();

    /**
     * @param int|string $level  The minimum logging level at which this handler will be triggered
     * @param bool       $bubble Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($level = Logger::DEBUG, $bubble = true)
    {
        $this->setLevel($level);
        $this->bubble = $bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        return $record['level'] >= $this->level;
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        foreach ($records as $record) {
            $this->handle($record);
        }
    }

    /**
     * Closes the handler.
     *
     * This will be called automatically when the object is destroyed
     */
    public function close()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function pushProcessor($callback)
    {
        if (!is_callable($callback)) {
            throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
        }
        array_unshift($this->processors, $callback);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function popProcessor()
    {
        if (!$this->processors) {
            throw new \LogicException('You tried to pop from an empty processor stack.');
        }

        return array_shift($this->processors);
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->formatter = $formatter;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        if (!$this->formatter) {
            $this->formatter = $this->getDefaultFormatter();
        }

        return $this->formatter;
    }

    /**
     * Sets minimum logging level at which this handler will be triggered.
     *
     * @param  int|string $level Level or level name
     * @return self
     */
    public function setLevel($level)
    {
        $this->level = Logger::toMonologLevel($level);

        return $this;
    }

    /**
     * Gets minimum logging level at which this handler will be triggered.
     *
     * @return int
     */
    public function getLevel()
    {
        return $this->level;
    }

    /**
     * Sets the bubbling behavior.
     *
     * @param  bool $bubble true means that this handler allows bubbling.
     *                      false means that bubbling is not permitted.
     * @return self
     */
    public function setBubble($bubble)
    {
        $this->bubble = $bubble;

        return $this;
    }

    /**
     * Gets the bubbling behavior.
     *
     * @return bool true means that this handler allows bubbling.
     *              false means that bubbling is not permitted.
     */
    public function getBubble()
    {
        return $this->bubble;
    }

    public function __destruct()
    {
        try {
            $this->close();
        } catch (\Exception $e) {
            // do nothing
        } catch (\Throwable $e) {
            // do nothing
        }
    }

    public function reset()
    {
        foreach ($this->processors as $processor) {
            if ($processor instanceof ResettableInterface) {
                $processor->reset();
            }
        }
    }

    /**
     * Gets the default formatter.
     *
     * @return FormatterInterface
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Swift;

/**
 * SwiftMailerHandler uses Swift_Mailer to send the emails
 *
 * @author Gyula Sallai
 */
class SwiftMailerHandler extends MailHandler
{
    protected $mailer;
    private $messageTemplate;

    /**
     * @param \Swift_Mailer           $mailer  The mailer to use
     * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
     * @param int                     $level   The minimum logging level at which this handler will be triggered
     * @param bool                    $bubble  Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, $bubble = true)
    {
        parent::__construct($level, $bubble);

        $this->mailer = $mailer;
        $this->messageTemplate = $message;
    }

    /**
     * {@inheritdoc}
     */
    protected function send($content, array $records)
    {
        $this->mailer->send($this->buildMessage($content, $records));
    }

    /**
     * Gets the formatter for the Swift_Message subject.
     *
     * @param  string             $format The format of the subject
     * @return FormatterInterface
     */
    protected function getSubjectFormatter($format)
    {
        return new LineFormatter($format);
    }

    /**
     * Creates instance of Swift_Message to be sent
     *
     * @param  string         $content formatted email body to be sent
     * @param  array          $records Log records that formed the content
     * @return \Swift_Message
     */
    protected function buildMessage($content, array $records)
    {
        $message = null;
        if ($this->messageTemplate instanceof \Swift_Message) {
            $message = clone $this->messageTemplate;
            $message->generateId();
        } elseif (is_callable($this->messageTemplate)) {
            $message = call_user_func($this->messageTemplate, $content, $records);
        }

        if (!$message instanceof \Swift_Message) {
            throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it');
        }

        if ($records) {
            $subjectFormatter = $this->getSubjectFormatter($message->getSubject());
            $message->setSubject($subjectFormatter->format($this->getHighestRecord($records)));
        }

        $message->setBody($content);
        if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
            $message->setDate(new \DateTimeImmutable());
        } else {
            $message->setDate(time());
        }

        return $message;
    }

    /**
     * BC getter, to be removed in 2.0
     */
    public function __get($name)
    {
        if ($name === 'message') {
            trigger_error('SwiftMailerHandler->message is deprecated, use ->buildMessage() instead to retrieve the message', E_USER_DEPRECATED);

            return $this->buildMessage(null, array());
        }

        throw new \InvalidArgumentException('Invalid property '.$name);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;
use Monolog\Formatter\FlowdockFormatter;
use Monolog\Formatter\FormatterInterface;

/**
 * Sends notifications through the Flowdock push API
 *
 * This must be configured with a FlowdockFormatter instance via setFormatter()
 *
 * Notes:
 * API token - Flowdock API token
 *
 * @author Dominik Liebler <liebler.dominik@gmail.com>
 * @see https://www.flowdock.com/api/push
 */
class FlowdockHandler extends SocketHandler
{
    /**
     * @var string
     */
    protected $apiToken;

    /**
     * @param string   $apiToken
     * @param bool|int $level    The minimum logging level at which this handler will be triggered
     * @param bool     $bubble   Whether the messages that are handled can bubble up the stack or not
     *
     * @throws MissingExtensionException if OpenSSL is missing
     */
    public function __construct($apiToken, $level = Logger::DEBUG, $bubble = true)
    {
        if (!extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
        }

        parent::__construct('ssl://api.flowdock.com:443', $level, $bubble);
        $this->apiToken = $apiToken;
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        if (!$formatter instanceof FlowdockFormatter) {
            throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
        }

        return parent::setFormatter($formatter);
    }

    /**
     * Gets the default formatter.
     *
     * @return FormatterInterface
     */
    protected function getDefaultFormatter()
    {
        throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        parent::write($record);

        $this->closeSocket();
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        return Utils::jsonEncode($record['formatted']['flowdock']);
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n";
        $header .= "Host: api.flowdock.com\r\n";
        $header .= "Content-Type: application/json\r\n";
        $header .= "Content-Length: " . strlen($content) . "\r\n";
        $header .= "\r\n";

        return $header;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Sends notifications through the pushover api to mobile phones
 *
 * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
 * @see    https://www.pushover.net/api
 */
class PushoverHandler extends SocketHandler
{
    private $token;
    private $users;
    private $title;
    private $user;
    private $retry;
    private $expire;

    private $highPriorityLevel;
    private $emergencyLevel;
    private $useFormattedMessage = false;

    /**
     * All parameters that can be sent to Pushover
     * @see https://pushover.net/api
     * @var array
     */
    private $parameterNames = array(
        'token' => true,
        'user' => true,
        'message' => true,
        'device' => true,
        'title' => true,
        'url' => true,
        'url_title' => true,
        'priority' => true,
        'timestamp' => true,
        'sound' => true,
        'retry' => true,
        'expire' => true,
        'callback' => true,
    );

    /**
     * Sounds the api supports by default
     * @see https://pushover.net/api#sounds
     * @var array
     */
    private $sounds = array(
        'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming',
        'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb',
        'persistent', 'echo', 'updown', 'none',
    );

    /**
     * @param string       $token             Pushover api token
     * @param string|array $users             Pushover user id or array of ids the message will be sent to
     * @param string       $title             Title sent to the Pushover API
     * @param int          $level             The minimum logging level at which this handler will be triggered
     * @param bool         $bubble            Whether the messages that are handled can bubble up the stack or not
     * @param bool         $useSSL            Whether to connect via SSL. Required when pushing messages to users that are not
     *                                        the pushover.net app owner. OpenSSL is required for this option.
     * @param int          $highPriorityLevel The minimum logging level at which this handler will start
     *                                        sending "high priority" requests to the Pushover API
     * @param int          $emergencyLevel    The minimum logging level at which this handler will start
     *                                        sending "emergency" requests to the Pushover API
     * @param int          $retry             The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user.
     * @param int          $expire            The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds).
     */
    public function __construct($token, $users, $title = null, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200)
    {
        $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80';
        parent::__construct($connectionString, $level, $bubble);

        $this->token = $token;
        $this->users = (array) $users;
        $this->title = $title ?: gethostname();
        $this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel);
        $this->emergencyLevel = Logger::toMonologLevel($emergencyLevel);
        $this->retry = $retry;
        $this->expire = $expire;
    }

    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    private function buildContent($record)
    {
        // Pushover has a limit of 512 characters on title and message combined.
        $maxMessageLength = 512 - strlen($this->title);

        $message = ($this->useFormattedMessage) ? $record['formatted'] : $record['message'];
        $message = substr($message, 0, $maxMessageLength);

        $timestamp = $record['datetime']->getTimestamp();

        $dataArray = array(
            'token' => $this->token,
            'user' => $this->user,
            'message' => $message,
            'title' => $this->title,
            'timestamp' => $timestamp,
        );

        if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) {
            $dataArray['priority'] = 2;
            $dataArray['retry'] = $this->retry;
            $dataArray['expire'] = $this->expire;
        } elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) {
            $dataArray['priority'] = 1;
        }

        // First determine the available parameters
        $context = array_intersect_key($record['context'], $this->parameterNames);
        $extra = array_intersect_key($record['extra'], $this->parameterNames);

        // Least important info should be merged with subsequent info
        $dataArray = array_merge($extra, $context, $dataArray);

        // Only pass sounds that are supported by the API
        if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) {
            unset($dataArray['sound']);
        }

        return http_build_query($dataArray);
    }

    private function buildHeader($content)
    {
        $header = "POST /1/messages.json HTTP/1.1\r\n";
        $header .= "Host: api.pushover.net\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($content) . "\r\n";
        $header .= "\r\n";

        return $header;
    }

    protected function write(array $record)
    {
        foreach ($this->users as $user) {
            $this->user = $user;

            parent::write($record);
            $this->closeSocket();
        }

        $this->user = null;
    }

    public function setHighPriorityLevel($value)
    {
        $this->highPriorityLevel = $value;
    }

    public function setEmergencyLevel($value)
    {
        $this->emergencyLevel = $value;
    }

    /**
     * Use the formatted message?
     * @param bool $value
     */
    public function useFormattedMessage($value)
    {
        $this->useFormattedMessage = (bool) $value;
    }
}
<?php declare(strict_types=1);

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Processor\ProcessorInterface;

/**
 * Interface to describe loggers that have processors
 *
 * This interface is present in monolog 1.x to ease forward compatibility.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
interface ProcessableHandlerInterface
{
    /**
     * Adds a processor in the stack.
     *
     * @param  ProcessorInterface|callable $callback
     * @return HandlerInterface            self
     */
    public function pushProcessor($callback): HandlerInterface;

    /**
     * Removes the processor on top of the stack and returns it.
     *
     * @throws \LogicException In case the processor stack is empty
     * @return callable
     */
    public function popProcessor(): callable;
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

/**
 * Exception can be thrown if an extension for an handler is missing
 *
 * @author  Christian Bergau <cbergau86@gmail.com>
 */
class MissingExtensionException extends \Exception
{
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;

/**
 * Common syslog functionality
 */
abstract class AbstractSyslogHandler extends AbstractProcessingHandler
{
    protected $facility;

    /**
     * Translates Monolog log levels to syslog log priorities.
     */
    protected $logLevels = array(
        Logger::DEBUG     => LOG_DEBUG,
        Logger::INFO      => LOG_INFO,
        Logger::NOTICE    => LOG_NOTICE,
        Logger::WARNING   => LOG_WARNING,
        Logger::ERROR     => LOG_ERR,
        Logger::CRITICAL  => LOG_CRIT,
        Logger::ALERT     => LOG_ALERT,
        Logger::EMERGENCY => LOG_EMERG,
    );

    /**
     * List of valid log facility names.
     */
    protected $facilities = array(
        'auth'     => LOG_AUTH,
        'authpriv' => LOG_AUTHPRIV,
        'cron'     => LOG_CRON,
        'daemon'   => LOG_DAEMON,
        'kern'     => LOG_KERN,
        'lpr'      => LOG_LPR,
        'mail'     => LOG_MAIL,
        'news'     => LOG_NEWS,
        'syslog'   => LOG_SYSLOG,
        'user'     => LOG_USER,
        'uucp'     => LOG_UUCP,
    );

    /**
     * @param mixed $facility
     * @param int   $level The minimum logging level at which this handler will be triggered
     * @param bool  $bubble Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($facility = LOG_USER, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);

        if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->facilities['local0'] = LOG_LOCAL0;
            $this->facilities['local1'] = LOG_LOCAL1;
            $this->facilities['local2'] = LOG_LOCAL2;
            $this->facilities['local3'] = LOG_LOCAL3;
            $this->facilities['local4'] = LOG_LOCAL4;
            $this->facilities['local5'] = LOG_LOCAL5;
            $this->facilities['local6'] = LOG_LOCAL6;
            $this->facilities['local7'] = LOG_LOCAL7;
        } else {
            $this->facilities['local0'] = 128; // LOG_LOCAL0
            $this->facilities['local1'] = 136; // LOG_LOCAL1
            $this->facilities['local2'] = 144; // LOG_LOCAL2
            $this->facilities['local3'] = 152; // LOG_LOCAL3
            $this->facilities['local4'] = 160; // LOG_LOCAL4
            $this->facilities['local5'] = 168; // LOG_LOCAL5
            $this->facilities['local6'] = 176; // LOG_LOCAL6
            $this->facilities['local7'] = 184; // LOG_LOCAL7
        }

        // convert textual description of facility to syslog constant
        if (array_key_exists(strtolower($facility), $this->facilities)) {
            $facility = $this->facilities[strtolower($facility)];
        } elseif (!in_array($facility, array_values($this->facilities), true)) {
            throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given');
        }

        $this->facility = $facility;
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter('%channel%.%level_name%: %message% %context% %extra%');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use Raven_Client;

/**
 * Handler to send messages to a Sentry (https://github.com/getsentry/sentry) server
 * using sentry-php (https://github.com/getsentry/sentry-php)
 *
 * @author Marc Abramowitz <marc@marc-abramowitz.com>
 */
class RavenHandler extends AbstractProcessingHandler
{
    /**
     * Translates Monolog log levels to Raven log levels.
     */
    protected $logLevels = array(
        Logger::DEBUG     => Raven_Client::DEBUG,
        Logger::INFO      => Raven_Client::INFO,
        Logger::NOTICE    => Raven_Client::INFO,
        Logger::WARNING   => Raven_Client::WARNING,
        Logger::ERROR     => Raven_Client::ERROR,
        Logger::CRITICAL  => Raven_Client::FATAL,
        Logger::ALERT     => Raven_Client::FATAL,
        Logger::EMERGENCY => Raven_Client::FATAL,
    );

    /**
     * @var string should represent the current version of the calling
     *             software. Can be any string (git commit, version number)
     */
    protected $release;

    /**
     * @var Raven_Client the client object that sends the message to the server
     */
    protected $ravenClient;

    /**
     * @var FormatterInterface The formatter to use for the logs generated via handleBatch()
     */
    protected $batchFormatter;

    /**
     * @param Raven_Client $ravenClient
     * @param int          $level       The minimum logging level at which this handler will be triggered
     * @param bool         $bubble      Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(Raven_Client $ravenClient, $level = Logger::DEBUG, $bubble = true)
    {
        @trigger_error('The Monolog\Handler\RavenHandler class is deprecated. You should rather upgrade to the sentry/sentry 2.x and use Sentry\Monolog\Handler, see https://github.com/getsentry/sentry-php/blob/master/src/Monolog/Handler.php', E_USER_DEPRECATED);

        parent::__construct($level, $bubble);

        $this->ravenClient = $ravenClient;
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        $level = $this->level;

        // filter records based on their level
        $records = array_filter($records, function ($record) use ($level) {
            return $record['level'] >= $level;
        });

        if (!$records) {
            return;
        }

        // the record with the highest severity is the "main" one
        $record = array_reduce($records, function ($highest, $record) {
            if (null === $highest || $record['level'] > $highest['level']) {
                return $record;
            }

            return $highest;
        });

        // the other ones are added as a context item
        $logs = array();
        foreach ($records as $r) {
            $logs[] = $this->processRecord($r);
        }

        if ($logs) {
            $record['context']['logs'] = (string) $this->getBatchFormatter()->formatBatch($logs);
        }

        $this->handle($record);
    }

    /**
     * Sets the formatter for the logs generated by handleBatch().
     *
     * @param FormatterInterface $formatter
     */
    public function setBatchFormatter(FormatterInterface $formatter)
    {
        $this->batchFormatter = $formatter;
    }

    /**
     * Gets the formatter for the logs generated by handleBatch().
     *
     * @return FormatterInterface
     */
    public function getBatchFormatter()
    {
        if (!$this->batchFormatter) {
            $this->batchFormatter = $this->getDefaultBatchFormatter();
        }

        return $this->batchFormatter;
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $previousUserContext = false;
        $options = array();
        $options['level'] = $this->logLevels[$record['level']];
        $options['tags'] = array();
        if (!empty($record['extra']['tags'])) {
            $options['tags'] = array_merge($options['tags'], $record['extra']['tags']);
            unset($record['extra']['tags']);
        }
        if (!empty($record['context']['tags'])) {
            $options['tags'] = array_merge($options['tags'], $record['context']['tags']);
            unset($record['context']['tags']);
        }
        if (!empty($record['context']['fingerprint'])) {
            $options['fingerprint'] = $record['context']['fingerprint'];
            unset($record['context']['fingerprint']);
        }
        if (!empty($record['context']['logger'])) {
            $options['logger'] = $record['context']['logger'];
            unset($record['context']['logger']);
        } else {
            $options['logger'] = $record['channel'];
        }
        foreach ($this->getExtraParameters() as $key) {
            foreach (array('extra', 'context') as $source) {
                if (!empty($record[$source][$key])) {
                    $options[$key] = $record[$source][$key];
                    unset($record[$source][$key]);
                }
            }
        }
        if (!empty($record['context'])) {
            $options['extra']['context'] = $record['context'];
            if (!empty($record['context']['user'])) {
                $previousUserContext = $this->ravenClient->context->user;
                $this->ravenClient->user_context($record['context']['user']);
                unset($options['extra']['context']['user']);
            }
        }
        if (!empty($record['extra'])) {
            $options['extra']['extra'] = $record['extra'];
        }

        if (!empty($this->release) && !isset($options['release'])) {
            $options['release'] = $this->release;
        }

        if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Exception || (PHP_VERSION_ID >= 70000 && $record['context']['exception'] instanceof \Throwable))) {
            $options['message'] = $record['formatted'];
            $this->ravenClient->captureException($record['context']['exception'], $options);
        } else {
            $this->ravenClient->captureMessage($record['formatted'], array(), $options);
        }

        if ($previousUserContext !== false) {
            $this->ravenClient->user_context($previousUserContext);
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter('[%channel%] %message%');
    }

    /**
     * Gets the default formatter for the logs generated by handleBatch().
     *
     * @return FormatterInterface
     */
    protected function getDefaultBatchFormatter()
    {
        return new LineFormatter();
    }

    /**
     * Gets extra parameters supported by Raven that can be found in "extra" and "context"
     *
     * @return array
     */
    protected function getExtraParameters()
    {
        return array('contexts', 'checksum', 'release', 'event_id');
    }

    /**
     * @param string $value
     * @return self
     */
    public function setRelease($value)
    {
        $this->release = $value;

        return $this;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Handler\SyslogUdp\UdpSocket;

/**
 * A Handler for logging to a remote syslogd server.
 *
 * @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com>
 * @author Dominik Kukacka <dominik.kukacka@gmail.com>
 */
class SyslogUdpHandler extends AbstractSyslogHandler
{
    const RFC3164 = 0;
    const RFC5424 = 1;

    private $dateFormats = array(
        self::RFC3164 => 'M d H:i:s',
        self::RFC5424 => \DateTime::RFC3339,
    );

    protected $socket;
    protected $ident;
    protected $rfc;

    /**
     * @param string $host
     * @param int    $port
     * @param mixed  $facility
     * @param int    $level    The minimum logging level at which this handler will be triggered
     * @param bool   $bubble   Whether the messages that are handled can bubble up the stack or not
     * @param string $ident    Program name or tag for each log message.
     * @param int    $rfc      RFC to format the message for.
     */
    public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $ident = 'php', $rfc = self::RFC5424)
    {
        parent::__construct($facility, $level, $bubble);

        $this->ident = $ident;
        $this->rfc = $rfc;

        $this->socket = new UdpSocket($host, $port ?: 514);
    }

    protected function write(array $record)
    {
        $lines = $this->splitMessageIntoLines($record['formatted']);

        $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']]);

        foreach ($lines as $line) {
            $this->socket->write($line, $header);
        }
    }

    public function close()
    {
        $this->socket->close();
    }

    private function splitMessageIntoLines($message)
    {
        if (is_array($message)) {
            $message = implode("\n", $message);
        }

        return preg_split('/$\R?^/m', $message, -1, PREG_SPLIT_NO_EMPTY);
    }

    /**
     * Make common syslog header (see rfc5424 or rfc3164)
     */
    protected function makeCommonSyslogHeader($severity)
    {
        $priority = $severity + $this->facility;

        if (!$pid = getmypid()) {
            $pid = '-';
        }

        if (!$hostname = gethostname()) {
            $hostname = '-';
        }

        $date = $this->getDateTime();

        if ($this->rfc === self::RFC3164) {
            return "<$priority>" .
                $date . " " .
                $hostname . " " .
                $this->ident . "[" . $pid . "]: ";
        } else {
            return "<$priority>1 " .
                $date . " " .
                $hostname . " " .
                $this->ident . " " .
                $pid . " - - ";
        }
    }

    protected function getDateTime()
    {
        return date($this->dateFormats[$this->rfc]);
    }

    /**
     * Inject your own socket, mainly used for testing
     */
    public function setSocket($socket)
    {
        $this->socket = $socket;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;

/**
 * Handler sending logs to browser's javascript console with no browser extension required
 *
 * @author Olivier Poitrey <rs@dailymotion.com>
 */
class BrowserConsoleHandler extends AbstractProcessingHandler
{
    protected static $initialized = false;
    protected static $records = array();

    /**
     * {@inheritDoc}
     *
     * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format.
     *
     * Example of formatted string:
     *
     *     You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%');
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        // Accumulate records
        static::$records[] = $record;

        // Register shutdown handler if not already done
        if (!static::$initialized) {
            static::$initialized = true;
            $this->registerShutdownFunction();
        }
    }

    /**
     * Convert records to javascript console commands and send it to the browser.
     * This method is automatically called on PHP shutdown if output is HTML or Javascript.
     */
    public static function send()
    {
        $format = static::getResponseFormat();
        if ($format === 'unknown') {
            return;
        }

        if (count(static::$records)) {
            if ($format === 'html') {
                static::writeOutput('<script>' . static::generateScript() . '</script>');
            } elseif ($format === 'js') {
                static::writeOutput(static::generateScript());
            }
            static::resetStatic();
        }
    }

    public function close()
    {
        self::resetStatic();
    }

    public function reset()
    {
        self::resetStatic();
    }

    /**
     * Forget all logged records
     */
    public static function resetStatic()
    {
        static::$records = array();
    }

    /**
     * Wrapper for register_shutdown_function to allow overriding
     */
    protected function registerShutdownFunction()
    {
        if (PHP_SAPI !== 'cli') {
            register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send'));
        }
    }

    /**
     * Wrapper for echo to allow overriding
     *
     * @param string $str
     */
    protected static function writeOutput($str)
    {
        echo $str;
    }

    /**
     * Checks the format of the response
     *
     * If Content-Type is set to application/javascript or text/javascript -> js
     * If Content-Type is set to text/html, or is unset -> html
     * If Content-Type is anything else -> unknown
     *
     * @return string One of 'js', 'html' or 'unknown'
     */
    protected static function getResponseFormat()
    {
        // Check content type
        foreach (headers_list() as $header) {
            if (stripos($header, 'content-type:') === 0) {
                // This handler only works with HTML and javascript outputs
                // text/javascript is obsolete in favour of application/javascript, but still used
                if (stripos($header, 'application/javascript') !== false || stripos($header, 'text/javascript') !== false) {
                    return 'js';
                }
                if (stripos($header, 'text/html') === false) {
                    return 'unknown';
                }
                break;
            }
        }

        return 'html';
    }

    private static function generateScript()
    {
        $script = array();
        foreach (static::$records as $record) {
            $context = static::dump('Context', $record['context']);
            $extra = static::dump('Extra', $record['extra']);

            if (empty($context) && empty($extra)) {
                $script[] = static::call_array('log', static::handleStyles($record['formatted']));
            } else {
                $script = array_merge($script,
                    array(static::call_array('groupCollapsed', static::handleStyles($record['formatted']))),
                    $context,
                    $extra,
                    array(static::call('groupEnd'))
                );
            }
        }

        return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);";
    }

    private static function handleStyles($formatted)
    {
        $args = array();
        $format = '%c' . $formatted;
        preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

        foreach (array_reverse($matches) as $match) {
            $args[] = '"font-weight: normal"';
            $args[] = static::quote(static::handleCustomStyles($match[2][0], $match[1][0]));

            $pos = $match[0][1];
            $format = substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . substr($format, $pos + strlen($match[0][0]));
        }

        $args[] = static::quote('font-weight: normal');
        $args[] = static::quote($format);

        return array_reverse($args);
    }

    private static function handleCustomStyles($style, $string)
    {
        static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey');
        static $labels = array();

        return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) {
            if (trim($m[1]) === 'autolabel') {
                // Format the string as a label with consistent auto assigned background color
                if (!isset($labels[$string])) {
                    $labels[$string] = $colors[count($labels) % count($colors)];
                }
                $color = $labels[$string];

                return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px";
            }

            return $m[1];
        }, $style);
    }

    private static function dump($title, array $dict)
    {
        $script = array();
        $dict = array_filter($dict);
        if (empty($dict)) {
            return $script;
        }
        $script[] = static::call('log', static::quote('%c%s'), static::quote('font-weight: bold'), static::quote($title));
        foreach ($dict as $key => $value) {
            $value = json_encode($value);
            if (empty($value)) {
                $value = static::quote('');
            }
            $script[] = static::call('log', static::quote('%s: %o'), static::quote($key), $value);
        }

        return $script;
    }

    private static function quote($arg)
    {
        return '"' . addcslashes($arg, "\"\n\\") . '"';
    }

    private static function call()
    {
        $args = func_get_args();
        $method = array_shift($args);

        return static::call_array($method, $args);
    }

    private static function call_array($method, array $args)
    {
        return 'c.' . $method . '(' . implode(', ', $args) . ');';
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\FormatterInterface;

/**
 * Simple handler wrapper that filters records based on a list of levels
 *
 * It can be configured with an exact list of levels to allow, or a min/max level.
 *
 * @author Hennadiy Verkh
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class FilterHandler extends AbstractHandler
{
    /**
     * Handler or factory callable($record, $this)
     *
     * @var callable|\Monolog\Handler\HandlerInterface
     */
    protected $handler;

    /**
     * Minimum level for logs that are passed to handler
     *
     * @var int[]
     */
    protected $acceptedLevels;

    /**
     * Whether the messages that are handled can bubble up the stack or not
     *
     * @var bool
     */
    protected $bubble;

    /**
     * @param callable|HandlerInterface $handler        Handler or factory callable($record|null, $filterHandler).
     * @param int|array                 $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided
     * @param int                       $maxLevel       Maximum level to accept, only used if $minLevelOrList is not an array
     * @param bool                      $bubble         Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, $bubble = true)
    {
        $this->handler  = $handler;
        $this->bubble   = $bubble;
        $this->setAcceptedLevels($minLevelOrList, $maxLevel);

        if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) {
            throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object");
        }
    }

    /**
     * @return array
     */
    public function getAcceptedLevels()
    {
        return array_flip($this->acceptedLevels);
    }

    /**
     * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided
     * @param int|string       $maxLevel       Maximum level or level name to accept, only used if $minLevelOrList is not an array
     */
    public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY)
    {
        if (is_array($minLevelOrList)) {
            $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList);
        } else {
            $minLevelOrList = Logger::toMonologLevel($minLevelOrList);
            $maxLevel = Logger::toMonologLevel($maxLevel);
            $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) {
                return $level >= $minLevelOrList && $level <= $maxLevel;
            }));
        }
        $this->acceptedLevels = array_flip($acceptedLevels);
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        return isset($this->acceptedLevels[$record['level']]);
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if (!$this->isHandling($record)) {
            return false;
        }

        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        $this->getHandler($record)->handle($record);

        return false === $this->bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        $filtered = array();
        foreach ($records as $record) {
            if ($this->isHandling($record)) {
                $filtered[] = $record;
            }
        }

        if (count($filtered) > 0) {
            $this->getHandler($filtered[count($filtered) - 1])->handleBatch($filtered);
        }
    }

    /**
     * Return the nested handler
     *
     * If the handler was provided as a factory callable, this will trigger the handler's instantiation.
     *
     * @return HandlerInterface
     */
    public function getHandler(array $record = null)
    {
        if (!$this->handler instanceof HandlerInterface) {
            $this->handler = call_user_func($this->handler, $record, $this);
            if (!$this->handler instanceof HandlerInterface) {
                throw new \RuntimeException("The factory callable should return a HandlerInterface");
            }
        }

        return $this->handler;
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->getHandler()->setFormatter($formatter);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return $this->getHandler()->getFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;

/**
 * Stores logs to files that are rotated every day and a limited number of files are kept.
 *
 * This rotation is only intended to be used as a workaround. Using logrotate to
 * handle the rotation is strongly encouraged when you can use it.
 *
 * @author Christophe Coevoet <stof@notk.org>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class RotatingFileHandler extends StreamHandler
{
    const FILE_PER_DAY = 'Y-m-d';
    const FILE_PER_MONTH = 'Y-m';
    const FILE_PER_YEAR = 'Y';

    protected $filename;
    protected $maxFiles;
    protected $mustRotate;
    protected $nextRotation;
    protected $filenameFormat;
    protected $dateFormat;

    /**
     * @param string   $filename
     * @param int      $maxFiles       The maximal amount of files to keep (0 means unlimited)
     * @param int      $level          The minimum logging level at which this handler will be triggered
     * @param bool     $bubble         Whether the messages that are handled can bubble up the stack or not
     * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
     * @param bool     $useLocking     Try to lock log file before doing any writes
     */
    public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false)
    {
        $this->filename = Utils::canonicalizePath($filename);
        $this->maxFiles = (int) $maxFiles;
        $this->nextRotation = new \DateTime('tomorrow');
        $this->filenameFormat = '{filename}-{date}';
        $this->dateFormat = 'Y-m-d';

        parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking);
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        parent::close();

        if (true === $this->mustRotate) {
            $this->rotate();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function reset()
    {
        parent::reset();

        if (true === $this->mustRotate) {
            $this->rotate();
        }
    }

    public function setFilenameFormat($filenameFormat, $dateFormat)
    {
        if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
            trigger_error(
                'Invalid date format - format must be one of '.
                'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
                'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
                'date formats using slashes, underscores and/or dots instead of dashes.',
                E_USER_DEPRECATED
            );
        }
        if (substr_count($filenameFormat, '{date}') === 0) {
            trigger_error(
                'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.',
                E_USER_DEPRECATED
            );
        }
        $this->filenameFormat = $filenameFormat;
        $this->dateFormat = $dateFormat;
        $this->url = $this->getTimedFilename();
        $this->close();
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        // on the first record written, if the log is new, we should rotate (once per day)
        if (null === $this->mustRotate) {
            $this->mustRotate = !file_exists($this->url);
        }

        if ($this->nextRotation < $record['datetime']) {
            $this->mustRotate = true;
            $this->close();
        }

        parent::write($record);
    }

    /**
     * Rotates the files.
     */
    protected function rotate()
    {
        // update filename
        $this->url = $this->getTimedFilename();
        $this->nextRotation = new \DateTime('tomorrow');

        // skip GC of old logs if files are unlimited
        if (0 === $this->maxFiles) {
            return;
        }

        $logFiles = glob($this->getGlobPattern());
        if ($this->maxFiles >= count($logFiles)) {
            // no files to remove
            return;
        }

        // Sorting the files by name to remove the older ones
        usort($logFiles, function ($a, $b) {
            return strcmp($b, $a);
        });

        foreach (array_slice($logFiles, $this->maxFiles) as $file) {
            if (is_writable($file)) {
                // suppress errors here as unlink() might fail if two processes
                // are cleaning up/rotating at the same time
                set_error_handler(function ($errno, $errstr, $errfile, $errline) {});
                unlink($file);
                restore_error_handler();
            }
        }

        $this->mustRotate = false;
    }

    protected function getTimedFilename()
    {
        $fileInfo = pathinfo($this->filename);
        $timedFilename = str_replace(
            array('{filename}', '{date}'),
            array($fileInfo['filename'], date($this->dateFormat)),
            $fileInfo['dirname'] . '/' . $this->filenameFormat
        );

        if (!empty($fileInfo['extension'])) {
            $timedFilename .= '.'.$fileInfo['extension'];
        }

        return $timedFilename;
    }

    protected function getGlobPattern()
    {
        $fileInfo = pathinfo($this->filename);
        $glob = str_replace(
            array('{filename}', '{date}'),
            array($fileInfo['filename'], '[0-9][0-9][0-9][0-9]*'),
            $fileInfo['dirname'] . '/' . $this->filenameFormat
        );
        if (!empty($fileInfo['extension'])) {
            $glob .= '.'.$fileInfo['extension'];
        }

        return $glob;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;

/**
 * NativeMailerHandler uses the mail() function to send the emails
 *
 * @author Christophe Coevoet <stof@notk.org>
 * @author Mark Garrett <mark@moderndeveloperllc.com>
 */
class NativeMailerHandler extends MailHandler
{
    /**
     * The email addresses to which the message will be sent
     * @var array
     */
    protected $to;

    /**
     * The subject of the email
     * @var string
     */
    protected $subject;

    /**
     * Optional headers for the message
     * @var array
     */
    protected $headers = array();

    /**
     * Optional parameters for the message
     * @var array
     */
    protected $parameters = array();

    /**
     * The wordwrap length for the message
     * @var int
     */
    protected $maxColumnWidth;

    /**
     * The Content-type for the message
     * @var string
     */
    protected $contentType = 'text/plain';

    /**
     * The encoding for the message
     * @var string
     */
    protected $encoding = 'utf-8';

    /**
     * @param string|array $to             The receiver of the mail
     * @param string       $subject        The subject of the mail
     * @param string       $from           The sender of the mail
     * @param int          $level          The minimum logging level at which this handler will be triggered
     * @param bool         $bubble         Whether the messages that are handled can bubble up the stack or not
     * @param int          $maxColumnWidth The maximum column width that the message lines will have
     */
    public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
    {
        parent::__construct($level, $bubble);
        $this->to = is_array($to) ? $to : array($to);
        $this->subject = $subject;
        $this->addHeader(sprintf('From: %s', $from));
        $this->maxColumnWidth = $maxColumnWidth;
    }

    /**
     * Add headers to the message
     *
     * @param  string|array $headers Custom added headers
     * @return self
     */
    public function addHeader($headers)
    {
        foreach ((array) $headers as $header) {
            if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) {
                throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons');
            }
            $this->headers[] = $header;
        }

        return $this;
    }

    /**
     * Add parameters to the message
     *
     * @param  string|array $parameters Custom added parameters
     * @return self
     */
    public function addParameter($parameters)
    {
        $this->parameters = array_merge($this->parameters, (array) $parameters);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    protected function send($content, array $records)
    {
        $content = wordwrap($content, $this->maxColumnWidth);
        $headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n");
        $headers .= 'Content-type: ' . $this->getContentType() . '; charset=' . $this->getEncoding() . "\r\n";
        if ($this->getContentType() == 'text/html' && false === strpos($headers, 'MIME-Version:')) {
            $headers .= 'MIME-Version: 1.0' . "\r\n";
        }

        $subject = $this->subject;
        if ($records) {
            $subjectFormatter = new LineFormatter($this->subject);
            $subject = $subjectFormatter->format($this->getHighestRecord($records));
        }

        $parameters = implode(' ', $this->parameters);
        foreach ($this->to as $to) {
            mail($to, $subject, $content, $headers, $parameters);
        }
    }

    /**
     * @return string $contentType
     */
    public function getContentType()
    {
        return $this->contentType;
    }

    /**
     * @return string $encoding
     */
    public function getEncoding()
    {
        return $this->encoding;
    }

    /**
     * @param  string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML
     *                             messages.
     * @return self
     */
    public function setContentType($contentType)
    {
        if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) {
            throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection');
        }

        $this->contentType = $contentType;

        return $this;
    }

    /**
     * @param  string $encoding
     * @return self
     */
    public function setEncoding($encoding)
    {
        if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) {
            throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection');
        }

        $this->encoding = $encoding;

        return $this;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\NormalizerFormatter;

/**
 * Logs to a MongoDB database.
 *
 * usage example:
 *
 *   $log = new Logger('application');
 *   $mongodb = new MongoDBHandler(new \Mongo("mongodb://localhost:27017"), "logs", "prod");
 *   $log->pushHandler($mongodb);
 *
 * @author Thomas Tourlourat <thomas@tourlourat.com>
 */
class MongoDBHandler extends AbstractProcessingHandler
{
    protected $mongoCollection;

    public function __construct($mongo, $database, $collection, $level = Logger::DEBUG, $bubble = true)
    {
        if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo || $mongo instanceof \MongoDB\Client)) {
            throw new \InvalidArgumentException('MongoClient, Mongo or MongoDB\Client instance required');
        }

        $this->mongoCollection = $mongo->selectCollection($database, $collection);

        parent::__construct($level, $bubble);
    }

    protected function write(array $record)
    {
        if ($this->mongoCollection instanceof \MongoDB\Collection) {
            $this->mongoCollection->insertOne($record["formatted"]);
        } else {
            $this->mongoCollection->save($record["formatted"]);
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new NormalizerFormatter();
    }
}
<?php declare(strict_types=1);

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;

/**
 * Helper trait for implementing FormattableInterface
 *
 * This trait is present in monolog 1.x to ease forward compatibility.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
trait FormattableHandlerTrait
{
    /**
     * @var FormatterInterface
     */
    protected $formatter;

    /**
     * {@inheritdoc}
     * @suppress PhanTypeMismatchReturn
     */
    public function setFormatter(FormatterInterface $formatter): HandlerInterface
    {
        $this->formatter = $formatter;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter(): FormatterInterface
    {
        if (!$this->formatter) {
            $this->formatter = $this->getDefaultFormatter();
        }

        return $this->formatter;
    }

    /**
     * Gets the default formatter.
     *
     * Overwrite this if the LineFormatter is not a good default for your handler.
     */
    protected function getDefaultFormatter(): FormatterInterface
    {
        return new LineFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Gelf\IMessagePublisher;
use Gelf\PublisherInterface;
use Gelf\Publisher;
use InvalidArgumentException;
use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter;

/**
 * Handler to send messages to a Graylog2 (http://www.graylog2.org) server
 *
 * @author Matt Lehner <mlehner@gmail.com>
 * @author Benjamin Zikarsky <benjamin@zikarsky.de>
 */
class GelfHandler extends AbstractProcessingHandler
{
    /**
     * @var Publisher|PublisherInterface|IMessagePublisher the publisher object that sends the message to the server
     */
    protected $publisher;

    /**
     * @param PublisherInterface|IMessagePublisher|Publisher $publisher a publisher object
     * @param int                                            $level     The minimum logging level at which this handler will be triggered
     * @param bool                                           $bubble    Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($publisher, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);

        if (!$publisher instanceof Publisher && !$publisher instanceof IMessagePublisher && !$publisher instanceof PublisherInterface) {
            throw new InvalidArgumentException('Invalid publisher, expected a Gelf\Publisher, Gelf\IMessagePublisher or Gelf\PublisherInterface instance');
        }

        $this->publisher = $publisher;
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $this->publisher->publish($record['formatted']);
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new GelfMessageFormatter();
    }
}
<?php
/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\NormalizerFormatter;
use Monolog\Logger;

/**
 * Handler sending logs to Zend Monitor
 *
 * @author  Christian Bergau <cbergau86@gmail.com>
 * @author  Jason Davis <happydude@jasondavis.net>
 */
class ZendMonitorHandler extends AbstractProcessingHandler
{
    /**
     * Monolog level / ZendMonitor Custom Event priority map
     *
     * @var array
     */
    protected $levelMap = array();

    /**
     * Construct
     *
     * @param  int                       $level
     * @param  bool                      $bubble
     * @throws MissingExtensionException
     */
    public function __construct($level = Logger::DEBUG, $bubble = true)
    {
        if (!function_exists('zend_monitor_custom_event')) {
            throw new MissingExtensionException(
                'You must have Zend Server installed with Zend Monitor enabled in order to use this handler'
            );
        }
        //zend monitor constants are not defined if zend monitor is not enabled.
        $this->levelMap = array(
            Logger::DEBUG     => \ZEND_MONITOR_EVENT_SEVERITY_INFO,
            Logger::INFO      => \ZEND_MONITOR_EVENT_SEVERITY_INFO,
            Logger::NOTICE    => \ZEND_MONITOR_EVENT_SEVERITY_INFO,
            Logger::WARNING   => \ZEND_MONITOR_EVENT_SEVERITY_WARNING,
            Logger::ERROR     => \ZEND_MONITOR_EVENT_SEVERITY_ERROR,
            Logger::CRITICAL  => \ZEND_MONITOR_EVENT_SEVERITY_ERROR,
            Logger::ALERT     => \ZEND_MONITOR_EVENT_SEVERITY_ERROR,
            Logger::EMERGENCY => \ZEND_MONITOR_EVENT_SEVERITY_ERROR,
        );
        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $this->writeZendMonitorCustomEvent(
            Logger::getLevelName($record['level']),
            $record['message'],
            $record['formatted'],
            $this->levelMap[$record['level']]
        );
    }

    /**
     * Write to Zend Monitor Events
     * @param string $type Text displayed in "Class Name (custom)" field
     * @param string $message Text displayed in "Error String"
     * @param mixed $formatted Displayed in Custom Variables tab
     * @param int $severity Set the event severity level (-1,0,1)
     */
    protected function writeZendMonitorCustomEvent($type, $message, $formatted, $severity)
    {
        zend_monitor_custom_event($type, $message, $formatted, $severity);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultFormatter()
    {
        return new NormalizerFormatter();
    }

    /**
     * Get the level map
     *
     * @return array
     */
    public function getLevelMap()
    {
        return $this->levelMap;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Exception;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
use Monolog\Utils;
use PhpConsole\Connector;
use PhpConsole\Handler;
use PhpConsole\Helper;

/**
 * Monolog handler for Google Chrome extension "PHP Console"
 *
 * Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely
 *
 * Usage:
 * 1. Install Google Chrome extension https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef
 * 2. See overview https://github.com/barbushin/php-console#overview
 * 3. Install PHP Console library https://github.com/barbushin/php-console#installation
 * 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png)
 *
 *      $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler()));
 *      \Monolog\ErrorHandler::register($logger);
 *      echo $undefinedVar;
 *      $logger->addDebug('SELECT * FROM users', array('db', 'time' => 0.012));
 *      PC::debug($_SERVER); // PHP Console debugger for any type of vars
 *
 * @author Sergey Barbushin https://www.linkedin.com/in/barbushin
 */
class PHPConsoleHandler extends AbstractProcessingHandler
{
    private $options = array(
        'enabled' => true, // bool Is PHP Console server enabled
        'classesPartialsTraceIgnore' => array('Monolog\\'), // array Hide calls of classes started with...
        'debugTagsKeysInContext' => array(0, 'tag'), // bool Is PHP Console server enabled
        'useOwnErrorsHandler' => false, // bool Enable errors handling
        'useOwnExceptionsHandler' => false, // bool Enable exceptions handling
        'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths
        'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s')
        'serverEncoding' => null, // string|null Server internal encoding
        'headersLimit' => null, // int|null Set headers size limit for your web-server
        'password' => null, // string|null Protect PHP Console connection by password
        'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed
        'ipMasks' => array(), // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
        'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required)
        'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings
        'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level
        'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number
        'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item
        'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON
        'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug
        'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ)
    );

    /** @var Connector */
    private $connector;

    /**
     * @param  array          $options   See \Monolog\Handler\PHPConsoleHandler::$options for more details
     * @param  Connector|null $connector Instance of \PhpConsole\Connector class (optional)
     * @param  int            $level
     * @param  bool           $bubble
     * @throws Exception
     */
    public function __construct(array $options = array(), Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
    {
        if (!class_exists('PhpConsole\Connector')) {
            throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
        }
        parent::__construct($level, $bubble);
        $this->options = $this->initOptions($options);
        $this->connector = $this->initConnector($connector);
    }

    private function initOptions(array $options)
    {
        $wrongOptions = array_diff(array_keys($options), array_keys($this->options));
        if ($wrongOptions) {
            throw new Exception('Unknown options: ' . implode(', ', $wrongOptions));
        }

        return array_replace($this->options, $options);
    }

    private function initConnector(Connector $connector = null)
    {
        if (!$connector) {
            if ($this->options['dataStorage']) {
                Connector::setPostponeStorage($this->options['dataStorage']);
            }
            $connector = Connector::getInstance();
        }

        if ($this->options['registerHelper'] && !Helper::isRegistered()) {
            Helper::register();
        }

        if ($this->options['enabled'] && $connector->isActiveClient()) {
            if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) {
                $handler = Handler::getInstance();
                $handler->setHandleErrors($this->options['useOwnErrorsHandler']);
                $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']);
                $handler->start();
            }
            if ($this->options['sourcesBasePath']) {
                $connector->setSourcesBasePath($this->options['sourcesBasePath']);
            }
            if ($this->options['serverEncoding']) {
                $connector->setServerEncoding($this->options['serverEncoding']);
            }
            if ($this->options['password']) {
                $connector->setPassword($this->options['password']);
            }
            if ($this->options['enableSslOnlyMode']) {
                $connector->enableSslOnlyMode();
            }
            if ($this->options['ipMasks']) {
                $connector->setAllowedIpMasks($this->options['ipMasks']);
            }
            if ($this->options['headersLimit']) {
                $connector->setHeadersLimit($this->options['headersLimit']);
            }
            if ($this->options['detectDumpTraceAndSource']) {
                $connector->getDebugDispatcher()->detectTraceAndSource = true;
            }
            $dumper = $connector->getDumper();
            $dumper->levelLimit = $this->options['dumperLevelLimit'];
            $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit'];
            $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit'];
            $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit'];
            $dumper->detectCallbacks = $this->options['dumperDetectCallbacks'];
            if ($this->options['enableEvalListener']) {
                $connector->startEvalRequestsListener();
            }
        }

        return $connector;
    }

    public function getConnector()
    {
        return $this->connector;
    }

    public function getOptions()
    {
        return $this->options;
    }

    public function handle(array $record)
    {
        if ($this->options['enabled'] && $this->connector->isActiveClient()) {
            return parent::handle($record);
        }

        return !$this->bubble;
    }

    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param  array $record
     * @return void
     */
    protected function write(array $record)
    {
        if ($record['level'] < Logger::NOTICE) {
            $this->handleDebugRecord($record);
        } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
            $this->handleExceptionRecord($record);
        } else {
            $this->handleErrorRecord($record);
        }
    }

    private function handleDebugRecord(array $record)
    {
        $tags = $this->getRecordTags($record);
        $message = $record['message'];
        if ($record['context']) {
            $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($record['context'])), null, true);
        }
        $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
    }

    private function handleExceptionRecord(array $record)
    {
        $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']);
    }

    private function handleErrorRecord(array $record)
    {
        $context = $record['context'];

        $this->connector->getErrorsDispatcher()->dispatchError(
            isset($context['code']) ? $context['code'] : null,
            isset($context['message']) ? $context['message'] : $record['message'],
            isset($context['file']) ? $context['file'] : null,
            isset($context['line']) ? $context['line'] : null,
            $this->options['classesPartialsTraceIgnore']
        );
    }

    private function getRecordTags(array &$record)
    {
        $tags = null;
        if (!empty($record['context'])) {
            $context = & $record['context'];
            foreach ($this->options['debugTagsKeysInContext'] as $key) {
                if (!empty($context[$key])) {
                    $tags = $context[$key];
                    if ($key === 0) {
                        array_shift($context);
                    } else {
                        unset($context[$key]);
                    }
                    break;
                }
            }
        }

        return $tags ?: strtolower($record['level_name']);
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter('%message%');
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;
use Monolog\Logger;

/**
 * Stores to PHP error_log() handler.
 *
 * @author Elan Ruusamäe <glen@delfi.ee>
 */
class ErrorLogHandler extends AbstractProcessingHandler
{
    const OPERATING_SYSTEM = 0;
    const SAPI = 4;

    protected $messageType;
    protected $expandNewlines;

    /**
     * @param int  $messageType    Says where the error should go.
     * @param int  $level          The minimum logging level at which this handler will be triggered
     * @param bool $bubble         Whether the messages that are handled can bubble up the stack or not
     * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries
     */
    public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, $bubble = true, $expandNewlines = false)
    {
        parent::__construct($level, $bubble);

        if (false === in_array($messageType, self::getAvailableTypes())) {
            $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true));
            throw new \InvalidArgumentException($message);
        }

        $this->messageType = $messageType;
        $this->expandNewlines = $expandNewlines;
    }

    /**
     * @return array With all available types
     */
    public static function getAvailableTypes()
    {
        return array(
            self::OPERATING_SYSTEM,
            self::SAPI,
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%');
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        if ($this->expandNewlines) {
            $lines = preg_split('{[\r\n]+}', (string) $record['formatted']);
            foreach ($lines as $line) {
                error_log($line, $this->messageType);
            }
        } else {
            error_log((string) $record['formatted'], $this->messageType);
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * @author Robert Kaufmann III <rok3@rok3.me>
 */
class LogEntriesHandler extends SocketHandler
{
    /**
     * @var string
     */
    protected $logToken;

    /**
     * @param string $token  Log token supplied by LogEntries
     * @param bool   $useSSL Whether or not SSL encryption should be used.
     * @param int    $level  The minimum logging level to trigger this handler
     * @param bool   $bubble Whether or not messages that are handled should bubble up the stack.
     *
     * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
     */
    public function __construct($token, $useSSL = true, $level = Logger::DEBUG, $bubble = true, $host = 'data.logentries.com')
    {
        if ($useSSL && !extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
        }

        $endpoint = $useSSL ? 'ssl://' . $host . ':443' : $host . ':80';
        parent::__construct($endpoint, $level, $bubble);
        $this->logToken = $token;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        return $this->logToken . ' ' . $record['formatted'];
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Simple handler wrapper that deduplicates log records across multiple requests
 *
 * It also includes the BufferHandler functionality and will buffer
 * all messages until the end of the request or flush() is called.
 *
 * This works by storing all log records' messages above $deduplicationLevel
 * to the file specified by $deduplicationStore. When further logs come in at the end of the
 * request (or when flush() is called), all those above $deduplicationLevel are checked
 * against the existing stored logs. If they match and the timestamps in the stored log is
 * not older than $time seconds, the new log record is discarded. If no log record is new, the
 * whole data set is discarded.
 *
 * This is mainly useful in combination with Mail handlers or things like Slack or HipChat handlers
 * that send messages to people, to avoid spamming with the same message over and over in case of
 * a major component failure like a database server being down which makes all requests fail in the
 * same way.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class DeduplicationHandler extends BufferHandler
{
    /**
     * @var string
     */
    protected $deduplicationStore;

    /**
     * @var int
     */
    protected $deduplicationLevel;

    /**
     * @var int
     */
    protected $time;

    /**
     * @var bool
     */
    private $gc = false;

    /**
     * @param HandlerInterface $handler            Handler.
     * @param string           $deduplicationStore The file/path where the deduplication log should be kept
     * @param int              $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes
     * @param int              $time               The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through
     * @param bool             $bubble             Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, $bubble = true)
    {
        parent::__construct($handler, 0, Logger::DEBUG, $bubble, false);

        $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore;
        $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel);
        $this->time = $time;
    }

    public function flush()
    {
        if ($this->bufferSize === 0) {
            return;
        }

        $passthru = null;

        foreach ($this->buffer as $record) {
            if ($record['level'] >= $this->deduplicationLevel) {

                $passthru = $passthru || !$this->isDuplicate($record);
                if ($passthru) {
                    $this->appendRecord($record);
                }
            }
        }

        // default of null is valid as well as if no record matches duplicationLevel we just pass through
        if ($passthru === true || $passthru === null) {
            $this->handler->handleBatch($this->buffer);
        }

        $this->clear();

        if ($this->gc) {
            $this->collectLogs();
        }
    }

    private function isDuplicate(array $record)
    {
        if (!file_exists($this->deduplicationStore)) {
            return false;
        }

        $store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!is_array($store)) {
            return false;
        }

        $yesterday = time() - 86400;
        $timestampValidity = $record['datetime']->getTimestamp() - $this->time;
        $expectedMessage = preg_replace('{[\r\n].*}', '', $record['message']);

        for ($i = count($store) - 1; $i >= 0; $i--) {
            list($timestamp, $level, $message) = explode(':', $store[$i], 3);

            if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) {
                return true;
            }

            if ($timestamp < $yesterday) {
                $this->gc = true;
            }
        }

        return false;
    }

    private function collectLogs()
    {
        if (!file_exists($this->deduplicationStore)) {
            return false;
        }

        $handle = fopen($this->deduplicationStore, 'rw+');
        flock($handle, LOCK_EX);
        $validLogs = array();

        $timestampValidity = time() - $this->time;

        while (!feof($handle)) {
            $log = fgets($handle);
            if (substr($log, 0, 10) >= $timestampValidity) {
                $validLogs[] = $log;
            }
        }

        ftruncate($handle, 0);
        rewind($handle);
        foreach ($validLogs as $log) {
            fwrite($handle, $log);
        }

        flock($handle, LOCK_UN);
        fclose($handle);

        $this->gc = false;
    }

    private function appendRecord(array $record)
    {
        file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\WildfireFormatter;

/**
 * Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol.
 *
 * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com>
 */
class FirePHPHandler extends AbstractProcessingHandler
{
    /**
     * WildFire JSON header message format
     */
    const PROTOCOL_URI = 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2';

    /**
     * FirePHP structure for parsing messages & their presentation
     */
    const STRUCTURE_URI = 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1';

    /**
     * Must reference a "known" plugin, otherwise headers won't display in FirePHP
     */
    const PLUGIN_URI = 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3';

    /**
     * Header prefix for Wildfire to recognize & parse headers
     */
    const HEADER_PREFIX = 'X-Wf';

    /**
     * Whether or not Wildfire vendor-specific headers have been generated & sent yet
     */
    protected static $initialized = false;

    /**
     * Shared static message index between potentially multiple handlers
     * @var int
     */
    protected static $messageIndex = 1;

    protected static $sendHeaders = true;

    /**
     * Base header creation function used by init headers & record headers
     *
     * @param  array  $meta    Wildfire Plugin, Protocol & Structure Indexes
     * @param  string $message Log message
     * @return array  Complete header string ready for the client as key and message as value
     */
    protected function createHeader(array $meta, $message)
    {
        $header = sprintf('%s-%s', self::HEADER_PREFIX, join('-', $meta));

        return array($header => $message);
    }

    /**
     * Creates message header from record
     *
     * @see createHeader()
     * @param  array  $record
     * @return array
     */
    protected function createRecordHeader(array $record)
    {
        // Wildfire is extensible to support multiple protocols & plugins in a single request,
        // but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake.
        return $this->createHeader(
            array(1, 1, 1, self::$messageIndex++),
            $record['formatted']
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new WildfireFormatter();
    }

    /**
     * Wildfire initialization headers to enable message parsing
     *
     * @see createHeader()
     * @see sendHeader()
     * @return array
     */
    protected function getInitHeaders()
    {
        // Initial payload consists of required headers for Wildfire
        return array_merge(
            $this->createHeader(array('Protocol', 1), self::PROTOCOL_URI),
            $this->createHeader(array(1, 'Structure', 1), self::STRUCTURE_URI),
            $this->createHeader(array(1, 'Plugin', 1), self::PLUGIN_URI)
        );
    }

    /**
     * Send header string to the client
     *
     * @param string $header
     * @param string $content
     */
    protected function sendHeader($header, $content)
    {
        if (!headers_sent() && self::$sendHeaders) {
            header(sprintf('%s: %s', $header, $content));
        }
    }

    /**
     * Creates & sends header for a record, ensuring init headers have been sent prior
     *
     * @see sendHeader()
     * @see sendInitHeaders()
     * @param array $record
     */
    protected function write(array $record)
    {
        if (!self::$sendHeaders) {
            return;
        }

        // WildFire-specific headers must be sent prior to any messages
        if (!self::$initialized) {
            self::$initialized = true;

            self::$sendHeaders = $this->headersAccepted();
            if (!self::$sendHeaders) {
                return;
            }

            foreach ($this->getInitHeaders() as $header => $content) {
                $this->sendHeader($header, $content);
            }
        }

        $header = $this->createRecordHeader($record);
        if (trim(current($header)) !== '') {
            $this->sendHeader(key($header), current($header));
        }
    }

    /**
     * Verifies if the headers are accepted by the current user agent
     *
     * @return bool
     */
    protected function headersAccepted()
    {
        if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) {
            return true;
        }

        return isset($_SERVER['HTTP_X_FIREPHP_VERSION']);
    }

    /**
     * BC getter for the sendHeaders property that has been made static
     */
    public function __get($property)
    {
        if ('sendHeaders' !== $property) {
            throw new \InvalidArgumentException('Undefined property '.$property);
        }

        return static::$sendHeaders;
    }

    /**
     * BC setter for the sendHeaders property that has been made static
     */
    public function __set($property, $value)
    {
        if ('sendHeaders' !== $property) {
            throw new \InvalidArgumentException('Undefined property '.$property);
        }

        static::$sendHeaders = $value;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\Curl;

class Util
{
    private static $retriableErrorCodes = array(
        CURLE_COULDNT_RESOLVE_HOST,
        CURLE_COULDNT_CONNECT,
        CURLE_HTTP_NOT_FOUND,
        CURLE_READ_ERROR,
        CURLE_OPERATION_TIMEOUTED,
        CURLE_HTTP_POST_ERROR,
        CURLE_SSL_CONNECT_ERROR,
    );

    /**
     * Executes a CURL request with optional retries and exception on failure
     *
     * @param  resource          $ch curl handler
     * @throws \RuntimeException
     */
    public static function execute($ch, $retries = 5, $closeAfterDone = true)
    {
        while ($retries--) {
            if (curl_exec($ch) === false) {
                $curlErrno = curl_errno($ch);

                if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) {
                    $curlError = curl_error($ch);

                    if ($closeAfterDone) {
                        curl_close($ch);
                    }

                    throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
                }

                continue;
            }

            if ($closeAfterDone) {
                curl_close($ch);
            }
            break;
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\NormalizerFormatter;
use Doctrine\CouchDB\CouchDBClient;

/**
 * CouchDB handler for Doctrine CouchDB ODM
 *
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class DoctrineCouchDBHandler extends AbstractProcessingHandler
{
    private $client;

    public function __construct(CouchDBClient $client, $level = Logger::DEBUG, $bubble = true)
    {
        $this->client = $client;
        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        $this->client->postDocument($record['formatted']);
    }

    protected function getDefaultFormatter()
    {
        return new NormalizerFormatter;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Aws\Sdk;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;
use Monolog\Formatter\ScalarFormatter;
use Monolog\Logger;

/**
 * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/)
 *
 * @link https://github.com/aws/aws-sdk-php/
 * @author Andrew Lawson <adlawson@gmail.com>
 */
class DynamoDbHandler extends AbstractProcessingHandler
{
    const DATE_FORMAT = 'Y-m-d\TH:i:s.uO';

    /**
     * @var DynamoDbClient
     */
    protected $client;

    /**
     * @var string
     */
    protected $table;

    /**
     * @var int
     */
    protected $version;

    /**
     * @var Marshaler
     */
    protected $marshaler;

    /**
     * @param DynamoDbClient $client
     * @param string         $table
     * @param int            $level
     * @param bool           $bubble
     */
    public function __construct(DynamoDbClient $client, $table, $level = Logger::DEBUG, $bubble = true)
    {
        if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) {
            $this->version = 3;
            $this->marshaler = new Marshaler;
        } else {
            $this->version = 2;
        }

        $this->client = $client;
        $this->table = $table;

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $filtered = $this->filterEmptyFields($record['formatted']);
        if ($this->version === 3) {
            $formatted = $this->marshaler->marshalItem($filtered);
        } else {
            /** @phpstan-ignore-next-line */
            $formatted = $this->client->formatAttributes($filtered);
        }

        $this->client->putItem(array(
            'TableName' => $this->table,
            'Item' => $formatted,
        ));
    }

    /**
     * @param  array $record
     * @return array
     */
    protected function filterEmptyFields(array $record)
    {
        return array_filter($record, function ($value) {
            return !empty($value) || false === $value || 0 === $value;
        });
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultFormatter()
    {
        return new ScalarFormatter(self::DATE_FORMAT);
    }
}
<?php declare(strict_types=1);

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;

/**
 * Interface to describe loggers that have a formatter
 *
 * This interface is present in monolog 1.x to ease forward compatibility.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
interface FormattableHandlerInterface
{
    /**
     * Sets the formatter.
     *
     * @param  FormatterInterface $formatter
     * @return HandlerInterface   self
     */
    public function setFormatter(FormatterInterface $formatter): HandlerInterface;

    /**
     * Gets the formatter.
     *
     * @return FormatterInterface
     */
    public function getFormatter(): FormatterInterface;
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

/**
 * Base class for all mail handlers
 *
 * @author Gyula Sallai
 */
abstract class MailHandler extends AbstractProcessingHandler
{
    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        $messages = array();

        foreach ($records as $record) {
            if ($record['level'] < $this->level) {
                continue;
            }
            $messages[] = $this->processRecord($record);
        }

        if (!empty($messages)) {
            $this->send((string) $this->getFormatter()->formatBatch($messages), $messages);
        }
    }

    /**
     * Send a mail with the given content
     *
     * @param string $content formatted email body to be sent
     * @param array  $records the array of log records that formed this content
     */
    abstract protected function send($content, array $records);

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $this->send((string) $record['formatted'], array($record));
    }

    protected function getHighestRecord(array $records)
    {
        $highestRecord = null;
        foreach ($records as $record) {
            if ($highestRecord === null || $highestRecord['level'] < $record['level']) {
                $highestRecord = $record;
            }
        }

        return $highestRecord;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;

/**
 * Stores to any stream resource
 *
 * Can be used to store into php://stderr, remote and local files, etc.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class StreamHandler extends AbstractProcessingHandler
{
    /** @private 512KB */
    const CHUNK_SIZE = 524288;

    /** @var resource|null */
    protected $stream;
    protected $url;
    private $errorMessage;
    protected $filePermission;
    protected $useLocking;
    private $dirCreated;

    /**
     * @param resource|string $stream
     * @param int             $level          The minimum logging level at which this handler will be triggered
     * @param bool            $bubble         Whether the messages that are handled can bubble up the stack or not
     * @param int|null        $filePermission Optional file permissions (default (0644) are only for owner read/write)
     * @param bool            $useLocking     Try to lock log file before doing any writes
     *
     * @throws \Exception                If a missing directory is not buildable
     * @throws \InvalidArgumentException If stream is not a resource or string
     */
    public function __construct($stream, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false)
    {
        parent::__construct($level, $bubble);
        if (is_resource($stream)) {
            $this->stream = $stream;
            $this->streamSetChunkSize();
        } elseif (is_string($stream)) {
            $this->url = Utils::canonicalizePath($stream);
        } else {
            throw new \InvalidArgumentException('A stream must either be a resource or a string.');
        }

        $this->filePermission = $filePermission;
        $this->useLocking = $useLocking;
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        if ($this->url && is_resource($this->stream)) {
            fclose($this->stream);
        }
        $this->stream = null;
        $this->dirCreated = null;
    }

    /**
     * Return the currently active stream if it is open
     *
     * @return resource|null
     */
    public function getStream()
    {
        return $this->stream;
    }

    /**
     * Return the stream URL if it was configured with a URL and not an active resource
     *
     * @return string|null
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        if (!is_resource($this->stream)) {
            if (null === $this->url || '' === $this->url) {
                throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
            }
            $this->createDir();
            $this->errorMessage = null;
            set_error_handler(array($this, 'customErrorHandler'));
            $this->stream = fopen($this->url, 'a');
            if ($this->filePermission !== null) {
                @chmod($this->url, $this->filePermission);
            }
            restore_error_handler();
            if (!is_resource($this->stream)) {
                $this->stream = null;

                throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $this->url));
            }
            $this->streamSetChunkSize();
        }

        if ($this->useLocking) {
            // ignoring errors here, there's not much we can do about them
            flock($this->stream, LOCK_EX);
        }

        $this->streamWrite($this->stream, $record);

        if ($this->useLocking) {
            flock($this->stream, LOCK_UN);
        }
    }

    /**
     * Write to stream
     * @param resource $stream
     * @param array $record
     */
    protected function streamWrite($stream, array $record)
    {
        fwrite($stream, (string) $record['formatted']);
    }

    protected function streamSetChunkSize()
    {
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            return stream_set_chunk_size($this->stream, self::CHUNK_SIZE);
        }

        return false;
    }

    private function customErrorHandler($code, $msg)
    {
        $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
    }

    /**
     * @param string $stream
     *
     * @return null|string
     */
    private function getDirFromStream($stream)
    {
        $pos = strpos($stream, '://');
        if ($pos === false) {
            return dirname($stream);
        }

        if ('file://' === substr($stream, 0, 7)) {
            return dirname(substr($stream, 7));
        }

        return null;
    }

    private function createDir()
    {
        // Do not try to create dir if it has already been tried.
        if ($this->dirCreated) {
            return;
        }

        $dir = $this->getDirFromStream($this->url);
        if (null !== $dir && !is_dir($dir)) {
            $this->errorMessage = null;
            set_error_handler(array($this, 'customErrorHandler'));
            $status = mkdir($dir, 0777, true);
            restore_error_handler();
            if (false === $status && !is_dir($dir)) {
                throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and its not buildable: '.$this->errorMessage, $dir));
            }
        }
        $this->dirCreated = true;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\LogglyFormatter;

/**
 * Sends errors to Loggly.
 *
 * @author Przemek Sobstel <przemek@sobstel.org>
 * @author Adam Pancutt <adam@pancutt.com>
 * @author Gregory Barchard <gregory@barchard.net>
 */
class LogglyHandler extends AbstractProcessingHandler
{
    const HOST = 'logs-01.loggly.com';
    const ENDPOINT_SINGLE = 'inputs';
    const ENDPOINT_BATCH = 'bulk';

    protected $token;

    protected $tag = array();

    public function __construct($token, $level = Logger::DEBUG, $bubble = true)
    {
        if (!extension_loaded('curl')) {
            throw new \LogicException('The curl extension is needed to use the LogglyHandler');
        }

        $this->token = $token;

        parent::__construct($level, $bubble);
    }

    public function setTag($tag)
    {
        $tag = !empty($tag) ? $tag : array();
        $this->tag = is_array($tag) ? $tag : array($tag);
    }

    public function addTag($tag)
    {
        if (!empty($tag)) {
            $tag = is_array($tag) ? $tag : array($tag);
            $this->tag = array_unique(array_merge($this->tag, $tag));
        }
    }

    protected function write(array $record)
    {
        $this->send($record["formatted"], self::ENDPOINT_SINGLE);
    }

    public function handleBatch(array $records)
    {
        $level = $this->level;

        $records = array_filter($records, function ($record) use ($level) {
            return ($record['level'] >= $level);
        });

        if ($records) {
            $this->send($this->getFormatter()->formatBatch($records), self::ENDPOINT_BATCH);
        }
    }

    protected function send($data, $endpoint)
    {
        $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);

        $headers = array('Content-Type: application/json');

        if (!empty($this->tag)) {
            $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag);
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        Curl\Util::execute($ch);
    }

    protected function getDefaultFormatter()
    {
        return new LogglyFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use Monolog\Utils;
use Monolog\Handler\Slack\SlackRecord;

/**
 * Sends notifications through Slack Webhooks
 *
 * @author Haralan Dobrev <hkdobrev@gmail.com>
 * @see    https://api.slack.com/incoming-webhooks
 */
class SlackWebhookHandler extends AbstractProcessingHandler
{
    /**
     * Slack Webhook token
     * @var string
     */
    private $webhookUrl;

    /**
     * Instance of the SlackRecord util class preparing data for Slack API.
     * @var SlackRecord
     */
    private $slackRecord;

    /**
     * @param  string      $webhookUrl             Slack Webhook URL
     * @param  string|null $channel                Slack channel (encoded ID or name)
     * @param  string|null $username               Name of a bot
     * @param  bool        $useAttachment          Whether the message should be added to Slack as attachment (plain text otherwise)
     * @param  string|null $iconEmoji              The emoji name to use (or null)
     * @param  bool        $useShortAttachment     Whether the the context/extra messages added to Slack as attachments are in a short style
     * @param  bool        $includeContextAndExtra Whether the attachment should include context and extra data
     * @param  int         $level                  The minimum logging level at which this handler will be triggered
     * @param  bool        $bubble                 Whether the messages that are handled can bubble up the stack or not
     * @param  array       $excludeFields          Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
     */
    public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true, array $excludeFields = array())
    {
        parent::__construct($level, $bubble);

        $this->webhookUrl = $webhookUrl;

        $this->slackRecord = new SlackRecord(
            $channel,
            $username,
            $useAttachment,
            $iconEmoji,
            $useShortAttachment,
            $includeContextAndExtra,
            $excludeFields,
            $this->formatter
        );
    }

    public function getSlackRecord()
    {
        return $this->slackRecord;
    }

    public function getWebhookUrl()
    {
        return $this->webhookUrl;
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        $postData = $this->slackRecord->getSlackData($record);
        $postString = Utils::jsonEncode($postData);

        $ch = curl_init();
        $options = array(
            CURLOPT_URL => $this->webhookUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json'),
            CURLOPT_POSTFIELDS => $postString
        );
        if (defined('CURLOPT_SAFE_UPLOAD')) {
            $options[CURLOPT_SAFE_UPLOAD] = true;
        }

        curl_setopt_array($ch, $options);

        Curl\Util::execute($ch);
    }

    public function setFormatter(FormatterInterface $formatter)
    {
        parent::setFormatter($formatter);
        $this->slackRecord->setFormatter($formatter);

        return $this;
    }

    public function getFormatter()
    {
        $formatter = parent::getFormatter();
        $this->slackRecord->setFormatter($formatter);

        return $formatter;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

/**
 * Forwards records to multiple handlers suppressing failures of each handler
 * and continuing through to give every handler a chance to succeed.
 *
 * @author Craig D'Amelio <craig@damelio.ca>
 */
class WhatFailureGroupHandler extends GroupHandler
{
    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        foreach ($this->handlers as $handler) {
            try {
                $handler->handle($record);
            } catch (\Exception $e) {
                // What failure?
            } catch (\Throwable $e) {
                // What failure?
            }
        }

        return false === $this->bubble;
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        if ($this->processors) {
            $processed = array();
            foreach ($records as $record) {
                foreach ($this->processors as $processor) {
                    $record = call_user_func($processor, $record);
                }
                $processed[] = $record;
            }
            $records = $processed;
        }

        foreach ($this->handlers as $handler) {
            try {
                $handler->handleBatch($records);
            } catch (\Exception $e) {
                // What failure?
            } catch (\Throwable $e) {
                // What failure?
            }
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\ChromePHPFormatter;
use Monolog\Logger;
use Monolog\Utils;

/**
 * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/)
 *
 * This also works out of the box with Firefox 43+
 *
 * @author Christophe Coevoet <stof@notk.org>
 */
class ChromePHPHandler extends AbstractProcessingHandler
{
    /**
     * Version of the extension
     */
    const VERSION = '4.0';

    /**
     * Header name
     */
    const HEADER_NAME = 'X-ChromeLogger-Data';

    /**
     * Regular expression to detect supported browsers (matches any Chrome, or Firefox 43+)
     */
    const USER_AGENT_REGEX = '{\b(?:Chrome/\d+(?:\.\d+)*|HeadlessChrome|Firefox/(?:4[3-9]|[5-9]\d|\d{3,})(?:\.\d)*)\b}';

    protected static $initialized = false;

    /**
     * Tracks whether we sent too much data
     *
     * Chrome limits the headers to 4KB, so when we sent 3KB we stop sending
     *
     * @var bool
     */
    protected static $overflowed = false;

    protected static $json = array(
        'version' => self::VERSION,
        'columns' => array('label', 'log', 'backtrace', 'type'),
        'rows' => array(),
    );

    protected static $sendHeaders = true;

    /**
     * @param int  $level  The minimum logging level at which this handler will be triggered
     * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);
        if (!function_exists('json_encode')) {
            throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s ChromePHPHandler');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        $messages = array();

        foreach ($records as $record) {
            if ($record['level'] < $this->level) {
                continue;
            }
            $messages[] = $this->processRecord($record);
        }

        if (!empty($messages)) {
            $messages = $this->getFormatter()->formatBatch($messages);
            self::$json['rows'] = array_merge(self::$json['rows'], $messages);
            $this->send();
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new ChromePHPFormatter();
    }

    /**
     * Creates & sends header for a record
     *
     * @see sendHeader()
     * @see send()
     * @param array $record
     */
    protected function write(array $record)
    {
        self::$json['rows'][] = $record['formatted'];

        $this->send();
    }

    /**
     * Sends the log header
     *
     * @see sendHeader()
     */
    protected function send()
    {
        if (self::$overflowed || !self::$sendHeaders) {
            return;
        }

        if (!self::$initialized) {
            self::$initialized = true;

            self::$sendHeaders = $this->headersAccepted();
            if (!self::$sendHeaders) {
                return;
            }

            self::$json['request_uri'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        }

        $json = Utils::jsonEncode(self::$json, null, true);
        $data = base64_encode(utf8_encode($json));
        if (strlen($data) > 3 * 1024) {
            self::$overflowed = true;

            $record = array(
                'message' => 'Incomplete logs, chrome header size limit reached',
                'context' => array(),
                'level' => Logger::WARNING,
                'level_name' => Logger::getLevelName(Logger::WARNING),
                'channel' => 'monolog',
                'datetime' => new \DateTime(),
                'extra' => array(),
            );
            self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record);
            $json = Utils::jsonEncode(self::$json, null, true);
            $data = base64_encode(utf8_encode($json));
        }

        if (trim($data) !== '') {
            $this->sendHeader(self::HEADER_NAME, $data);
        }
    }

    /**
     * Send header string to the client
     *
     * @param string $header
     * @param string $content
     */
    protected function sendHeader($header, $content)
    {
        if (!headers_sent() && self::$sendHeaders) {
            header(sprintf('%s: %s', $header, $content));
        }
    }

    /**
     * Verifies if the headers are accepted by the current user agent
     *
     * @return bool
     */
    protected function headersAccepted()
    {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }

        return preg_match(self::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']);
    }

    /**
     * BC getter for the sendHeaders property that has been made static
     */
    public function __get($property)
    {
        if ('sendHeaders' !== $property) {
            throw new \InvalidArgumentException('Undefined property '.$property);
        }

        return static::$sendHeaders;
    }

    /**
     * BC setter for the sendHeaders property that has been made static
     */
    public function __set($property, $value)
    {
        if ('sendHeaders' !== $property) {
            throw new \InvalidArgumentException('Undefined property '.$property);
        }

        static::$sendHeaders = $value;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\Slack;

use Monolog\Logger;
use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface;

/**
 * Slack record utility helping to log to Slack webhooks or API.
 *
 * @author Greg Kedzierski <greg@gregkedzierski.com>
 * @author Haralan Dobrev <hkdobrev@gmail.com>
 * @see    https://api.slack.com/incoming-webhooks
 * @see    https://api.slack.com/docs/message-attachments
 */
class SlackRecord
{
    const COLOR_DANGER = 'danger';

    const COLOR_WARNING = 'warning';

    const COLOR_GOOD = 'good';

    const COLOR_DEFAULT = '#e3e4e6';

    /**
     * Slack channel (encoded ID or name)
     * @var string|null
     */
    private $channel;

    /**
     * Name of a bot
     * @var string|null
     */
    private $username;

    /**
     * User icon e.g. 'ghost', 'http://example.com/user.png'
     * @var string
     */
    private $userIcon;

    /**
     * Whether the message should be added to Slack as attachment (plain text otherwise)
     * @var bool
     */
    private $useAttachment;

    /**
     * Whether the the context/extra messages added to Slack as attachments are in a short style
     * @var bool
     */
    private $useShortAttachment;

    /**
     * Whether the attachment should include context and extra data
     * @var bool
     */
    private $includeContextAndExtra;

    /**
     * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
     * @var array
     */
    private $excludeFields;

    /**
     * @var FormatterInterface
     */
    private $formatter;

    /**
     * @var NormalizerFormatter
     */
    private $normalizerFormatter;

    public function __construct($channel = null, $username = null, $useAttachment = true, $userIcon = null, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array(), FormatterInterface $formatter = null)
    {
        $this->channel = $channel;
        $this->username = $username;
        $this->userIcon = trim($userIcon, ':');
        $this->useAttachment = $useAttachment;
        $this->useShortAttachment = $useShortAttachment;
        $this->includeContextAndExtra = $includeContextAndExtra;
        $this->excludeFields = $excludeFields;
        $this->formatter = $formatter;

        if ($this->includeContextAndExtra) {
            $this->normalizerFormatter = new NormalizerFormatter();
        }
    }

    public function getSlackData(array $record)
    {
        $dataArray = array();
        $record = $this->excludeFields($record);

        if ($this->username) {
            $dataArray['username'] = $this->username;
        }

        if ($this->channel) {
            $dataArray['channel'] = $this->channel;
        }

        if ($this->formatter && !$this->useAttachment) {
            $message = $this->formatter->format($record);
        } else {
            $message = $record['message'];
        }

        if ($this->useAttachment) {
            $attachment = array(
                'fallback'  => $message,
                'text'      => $message,
                'color'     => $this->getAttachmentColor($record['level']),
                'fields'    => array(),
                'mrkdwn_in' => array('fields'),
                'ts'        => $record['datetime']->getTimestamp()
            );

            if ($this->useShortAttachment) {
                $attachment['title'] = $record['level_name'];
            } else {
                $attachment['title'] = 'Message';
                $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']);
            }


            if ($this->includeContextAndExtra) {
                foreach (array('extra', 'context') as $key) {
                    if (empty($record[$key])) {
                        continue;
                    }

                    if ($this->useShortAttachment) {
                        $attachment['fields'][] = $this->generateAttachmentField(
                            $key,
                            $record[$key]
                        );
                    } else {
                        // Add all extra fields as individual fields in attachment
                        $attachment['fields'] = array_merge(
                            $attachment['fields'],
                            $this->generateAttachmentFields($record[$key])
                        );
                    }
                }
            }

            $dataArray['attachments'] = array($attachment);
        } else {
            $dataArray['text'] = $message;
        }

        if ($this->userIcon) {
            if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) {
                $dataArray['icon_url'] = $this->userIcon;
            } else {
                $dataArray['icon_emoji'] = ":{$this->userIcon}:";
            }
        }

        return $dataArray;
    }

    /**
     * Returned a Slack message attachment color associated with
     * provided level.
     *
     * @param  int    $level
     * @return string
     */
    public function getAttachmentColor($level)
    {
        switch (true) {
            case $level >= Logger::ERROR:
                return self::COLOR_DANGER;
            case $level >= Logger::WARNING:
                return self::COLOR_WARNING;
            case $level >= Logger::INFO:
                return self::COLOR_GOOD;
            default:
                return self::COLOR_DEFAULT;
        }
    }

    /**
     * Stringifies an array of key/value pairs to be used in attachment fields
     *
     * @param array $fields
     *
     * @return string
     */
    public function stringify($fields)
    {
        $normalized = $this->normalizerFormatter->format($fields);
        $prettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128;
        $flags = 0;
        if (PHP_VERSION_ID >= 50400) {
            $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
        }

        $hasSecondDimension = count(array_filter($normalized, 'is_array'));
        $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric'));

        return $hasSecondDimension || $hasNonNumericKeys
            ? Utils::jsonEncode($normalized, $prettyPrintFlag | $flags)
            : Utils::jsonEncode($normalized, $flags);
    }

    /**
     * Sets the formatter
     *
     * @param FormatterInterface $formatter
     */
    public function setFormatter(FormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    /**
     * Generates attachment field
     *
     * @param string       $title
     * @param string|array $value
     *
     * @return array
     */
    private function generateAttachmentField($title, $value)
    {
        $value = is_array($value)
            ? sprintf('```%s```', $this->stringify($value))
            : $value;

        return array(
            'title' => ucfirst($title),
            'value' => $value,
            'short' => false
        );
    }

    /**
     * Generates a collection of attachment fields from array
     *
     * @param array $data
     *
     * @return array
     */
    private function generateAttachmentFields(array $data)
    {
        $fields = array();
        foreach ($this->normalizerFormatter->format($data) as $key => $value) {
            $fields[] = $this->generateAttachmentField($key, $value);
        }

        return $fields;
    }

    /**
     * Get a copy of record with fields excluded according to $this->excludeFields
     *
     * @param array $record
     *
     * @return array
     */
    private function excludeFields(array $record)
    {
        foreach ($this->excludeFields as $field) {
            $keys = explode('.', $field);
            $node = &$record;
            $lastKey = end($keys);
            foreach ($keys as $key) {
                if (!isset($node[$key])) {
                    break;
                }
                if ($lastKey === $key) {
                    unset($node[$key]);
                    break;
                }
                $node = &$node[$key];
            }
        }

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Psr\Log\LoggerInterface;

/**
 * Proxies log messages to an existing PSR-3 compliant logger.
 *
 * @author Michael Moussa <michael.moussa@gmail.com>
 */
class PsrHandler extends AbstractHandler
{
    /**
     * PSR-3 compliant logger
     *
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
     * @param int             $level  The minimum logging level at which this handler will be triggered
     * @param bool            $bubble Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);

        $this->logger = $logger;
    }

    /**
     * {@inheritDoc}
     */
    public function handle(array $record)
    {
        if (!$this->isHandling($record)) {
            return false;
        }

        $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']);

        return false === $this->bubble;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter;

/**
 * Class to record a log on a NewRelic application.
 * Enabling New Relic High Security mode may prevent capture of useful information.
 *
 * This handler requires a NormalizerFormatter to function and expects an array in $record['formatted']
 *
 * @see https://docs.newrelic.com/docs/agents/php-agent
 * @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security
 */
class NewRelicHandler extends AbstractProcessingHandler
{
    /**
     * Name of the New Relic application that will receive logs from this handler.
     *
     * @var string
     */
    protected $appName;

    /**
     * Name of the current transaction
     *
     * @var string
     */
    protected $transactionName;

    /**
     * Some context and extra data is passed into the handler as arrays of values. Do we send them as is
     * (useful if we are using the API), or explode them for display on the NewRelic RPM website?
     *
     * @var bool
     */
    protected $explodeArrays;

    /**
     * {@inheritDoc}
     *
     * @param string $appName
     * @param bool   $explodeArrays
     * @param string $transactionName
     */
    public function __construct(
        $level = Logger::ERROR,
        $bubble = true,
        $appName = null,
        $explodeArrays = false,
        $transactionName = null
    ) {
        parent::__construct($level, $bubble);

        $this->appName       = $appName;
        $this->explodeArrays = $explodeArrays;
        $this->transactionName = $transactionName;
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        if (!$this->isNewRelicEnabled()) {
            throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler');
        }

        if ($appName = $this->getAppName($record['context'])) {
            $this->setNewRelicAppName($appName);
        }

        if ($transactionName = $this->getTransactionName($record['context'])) {
            $this->setNewRelicTransactionName($transactionName);
            unset($record['formatted']['context']['transaction_name']);
        }

        if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Exception || (PHP_VERSION_ID >= 70000 && $record['context']['exception'] instanceof \Throwable))) {
            newrelic_notice_error($record['message'], $record['context']['exception']);
            unset($record['formatted']['context']['exception']);
        } else {
            newrelic_notice_error($record['message']);
        }

        if (isset($record['formatted']['context']) && is_array($record['formatted']['context'])) {
            foreach ($record['formatted']['context'] as $key => $parameter) {
                if (is_array($parameter) && $this->explodeArrays) {
                    foreach ($parameter as $paramKey => $paramValue) {
                        $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue);
                    }
                } else {
                    $this->setNewRelicParameter('context_' . $key, $parameter);
                }
            }
        }

        if (isset($record['formatted']['extra']) && is_array($record['formatted']['extra'])) {
            foreach ($record['formatted']['extra'] as $key => $parameter) {
                if (is_array($parameter) && $this->explodeArrays) {
                    foreach ($parameter as $paramKey => $paramValue) {
                        $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue);
                    }
                } else {
                    $this->setNewRelicParameter('extra_' . $key, $parameter);
                }
            }
        }
    }

    /**
     * Checks whether the NewRelic extension is enabled in the system.
     *
     * @return bool
     */
    protected function isNewRelicEnabled()
    {
        return extension_loaded('newrelic');
    }

    /**
     * Returns the appname where this log should be sent. Each log can override the default appname, set in this
     * handler's constructor, by providing the appname in it's context.
     *
     * @param  array       $context
     * @return null|string
     */
    protected function getAppName(array $context)
    {
        if (isset($context['appname'])) {
            return $context['appname'];
        }

        return $this->appName;
    }

    /**
     * Returns the name of the current transaction. Each log can override the default transaction name, set in this
     * handler's constructor, by providing the transaction_name in it's context
     *
     * @param array $context
     *
     * @return null|string
     */
    protected function getTransactionName(array $context)
    {
        if (isset($context['transaction_name'])) {
            return $context['transaction_name'];
        }

        return $this->transactionName;
    }

    /**
     * Sets the NewRelic application that should receive this log.
     *
     * @param string $appName
     */
    protected function setNewRelicAppName($appName)
    {
        newrelic_set_appname($appName);
    }

    /**
     * Overwrites the name of the current transaction
     *
     * @param string $transactionName
     */
    protected function setNewRelicTransactionName($transactionName)
    {
        newrelic_name_transaction($transactionName);
    }

    /**
     * @param string $key
     * @param mixed  $value
     */
    protected function setNewRelicParameter($key, $value)
    {
        if (null === $value || is_scalar($value)) {
            newrelic_add_custom_parameter($key, $value);
        } else {
            newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true));
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new NormalizerFormatter();
    }
}
<?php declare(strict_types=1);

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\ResettableInterface;

/**
 * Helper trait for implementing ProcessableInterface
 *
 * This trait is present in monolog 1.x to ease forward compatibility.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
trait ProcessableHandlerTrait
{
    /**
     * @var callable[]
     */
    protected $processors = [];

    /**
     * {@inheritdoc}
     * @suppress PhanTypeMismatchReturn
     */
    public function pushProcessor($callback): HandlerInterface
    {
        array_unshift($this->processors, $callback);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function popProcessor(): callable
    {
        if (!$this->processors) {
            throw new \LogicException('You tried to pop from an empty processor stack.');
        }

        return array_shift($this->processors);
    }

    /**
     * Processes a record.
     */
    protected function processRecord(array $record): array
    {
        foreach ($this->processors as $processor) {
            $record = $processor($record);
        }

        return $record;
    }

    protected function resetProcessors(): void
    {
        foreach ($this->processors as $processor) {
            if ($processor instanceof ResettableInterface) {
                $processor->reset();
            }
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;

/**
 * Interface that all Monolog Handlers must implement
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
interface HandlerInterface
{
    /**
     * Checks whether the given record will be handled by this handler.
     *
     * This is mostly done for performance reasons, to avoid calling processors for nothing.
     *
     * Handlers should still check the record levels within handle(), returning false in isHandling()
     * is no guarantee that handle() will not be called, and isHandling() might not be called
     * for a given record.
     *
     * @param array $record Partial log record containing only a level key
     *
     * @return bool
     */
    public function isHandling(array $record);

    /**
     * Handles a record.
     *
     * All records may be passed to this method, and the handler should discard
     * those that it does not want to handle.
     *
     * The return value of this function controls the bubbling process of the handler stack.
     * Unless the bubbling is interrupted (by returning true), the Logger class will keep on
     * calling further handlers in the stack with a given log record.
     *
     * @param  array   $record The record to handle
     * @return bool true means that this handler handled the record, and that bubbling is not permitted.
     *                        false means the record was either not processed or that this handler allows bubbling.
     */
    public function handle(array $record);

    /**
     * Handles a set of records at once.
     *
     * @param array $records The records to handle (an array of record arrays)
     */
    public function handleBatch(array $records);

    /**
     * Adds a processor in the stack.
     *
     * @param  callable $callback
     * @return self
     */
    public function pushProcessor($callback);

    /**
     * Removes the processor on top of the stack and returns it.
     *
     * @return callable
     */
    public function popProcessor();

    /**
     * Sets the formatter.
     *
     * @param  FormatterInterface $formatter
     * @return self
     */
    public function setFormatter(FormatterInterface $formatter);

    /**
     * Gets the formatter.
     *
     * @return FormatterInterface
     */
    public function getFormatter();
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use Monolog\Utils;
use Monolog\Handler\Slack\SlackRecord;

/**
 * Sends notifications through Slack API
 *
 * @author Greg Kedzierski <greg@gregkedzierski.com>
 * @see    https://api.slack.com/
 */
class SlackHandler extends SocketHandler
{
    /**
     * Slack API token
     * @var string
     */
    private $token;

    /**
     * Instance of the SlackRecord util class preparing data for Slack API.
     * @var SlackRecord
     */
    private $slackRecord;

    /**
     * @param  string                    $token                  Slack API token
     * @param  string                    $channel                Slack channel (encoded ID or name)
     * @param  string|null               $username               Name of a bot
     * @param  bool                      $useAttachment          Whether the message should be added to Slack as attachment (plain text otherwise)
     * @param  string|null               $iconEmoji              The emoji name to use (or null)
     * @param  int                       $level                  The minimum logging level at which this handler will be triggered
     * @param  bool                      $bubble                 Whether the messages that are handled can bubble up the stack or not
     * @param  bool                      $useShortAttachment     Whether the the context/extra messages added to Slack as attachments are in a short style
     * @param  bool                      $includeContextAndExtra Whether the attachment should include context and extra data
     * @param  array                     $excludeFields          Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
     * @throws MissingExtensionException If no OpenSSL PHP extension configured
     */
    public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array())
    {
        if (!extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
        }

        parent::__construct('ssl://slack.com:443', $level, $bubble);

        $this->slackRecord = new SlackRecord(
            $channel,
            $username,
            $useAttachment,
            $iconEmoji,
            $useShortAttachment,
            $includeContextAndExtra,
            $excludeFields,
            $this->formatter
        );

        $this->token = $token;
    }

    public function getSlackRecord()
    {
        return $this->slackRecord;
    }

    public function getToken()
    {
        return $this->token;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        $dataArray = $this->prepareContentData($record);

        return http_build_query($dataArray);
    }

    /**
     * Prepares content data
     *
     * @param  array $record
     * @return array
     */
    protected function prepareContentData($record)
    {
        $dataArray = $this->slackRecord->getSlackData($record);
        $dataArray['token'] = $this->token;

        if (!empty($dataArray['attachments'])) {
            $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']);
        }

        return $dataArray;
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
        $header .= "Host: slack.com\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($content) . "\r\n";
        $header .= "\r\n";

        return $header;
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        parent::write($record);
        $this->finalizeWrite();
    }

    /**
     * Finalizes the request by reading some bytes and then closing the socket
     *
     * If we do not read some but close the socket too early, slack sometimes
     * drops the request entirely.
     */
    protected function finalizeWrite()
    {
        $res = $this->getResource();
        if (is_resource($res)) {
            @fread($res, 2048);
        }
        $this->closeSocket();
    }

    /**
     * Returned a Slack message attachment color associated with
     * provided level.
     *
     * @param  int    $level
     * @return string
     * @deprecated Use underlying SlackRecord instead
     */
    protected function getAttachmentColor($level)
    {
        trigger_error(
            'SlackHandler::getAttachmentColor() is deprecated. Use underlying SlackRecord instead.',
            E_USER_DEPRECATED
        );

        return $this->slackRecord->getAttachmentColor($level);
    }

    /**
     * Stringifies an array of key/value pairs to be used in attachment fields
     *
     * @param  array  $fields
     * @return string
     * @deprecated Use underlying SlackRecord instead
     */
    protected function stringify($fields)
    {
        trigger_error(
            'SlackHandler::stringify() is deprecated. Use underlying SlackRecord instead.',
            E_USER_DEPRECATED
        );

        return $this->slackRecord->stringify($fields);
    }

    public function setFormatter(FormatterInterface $formatter)
    {
        parent::setFormatter($formatter);
        $this->slackRecord->setFormatter($formatter);

        return $this;
    }

    public function getFormatter()
    {
        $formatter = parent::getFormatter();
        $this->slackRecord->setFormatter($formatter);

        return $formatter;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Sends notifications through the hipchat api to a hipchat room
 *
 * Notes:
 * API token - HipChat API token
 * Room      - HipChat Room Id or name, where messages are sent
 * Name      - Name used to send the message (from)
 * notify    - Should the message trigger a notification in the clients
 * version   - The API version to use (HipChatHandler::API_V1 | HipChatHandler::API_V2)
 *
 * @author Rafael Dohms <rafael@doh.ms>
 * @see    https://www.hipchat.com/docs/api
 */
class HipChatHandler extends SocketHandler
{
    /**
     * Use API version 1
     */
    const API_V1 = 'v1';

    /**
     * Use API version v2
     */
    const API_V2 = 'v2';

    /**
     * The maximum allowed length for the name used in the "from" field.
     */
    const MAXIMUM_NAME_LENGTH = 15;

    /**
     * The maximum allowed length for the message.
     */
    const MAXIMUM_MESSAGE_LENGTH = 9500;

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $room;

    /**
     * @var string
     */
    private $name;

    /**
     * @var bool
     */
    private $notify;

    /**
     * @var string
     */
    private $format;

    /**
     * @var string
     */
    private $host;

    /**
     * @var string
     */
    private $version;

    /**
     * @param string $token   HipChat API Token
     * @param string $room    The room that should be alerted of the message (Id or Name)
     * @param string $name    Name used in the "from" field.
     * @param bool   $notify  Trigger a notification in clients or not
     * @param int    $level   The minimum logging level at which this handler will be triggered
     * @param bool   $bubble  Whether the messages that are handled can bubble up the stack or not
     * @param bool   $useSSL  Whether to connect via SSL.
     * @param string $format  The format of the messages (default to text, can be set to html if you have html in the messages)
     * @param string $host    The HipChat server hostname.
     * @param string $version The HipChat API version (default HipChatHandler::API_V1)
     */
    public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com', $version = self::API_V1)
    {
        @trigger_error('The Monolog\Handler\HipChatHandler class is deprecated. You should migrate to Slack and the SlackWebhookHandler / SlackbotHandler, see https://www.atlassian.com/partnerships/slack', E_USER_DEPRECATED);

        if ($version == self::API_V1 && !$this->validateStringLength($name, static::MAXIMUM_NAME_LENGTH)) {
            throw new \InvalidArgumentException('The supplied name is too long. HipChat\'s v1 API supports names up to 15 UTF-8 characters.');
        }

        $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
        parent::__construct($connectionString, $level, $bubble);

        $this->token = $token;
        $this->name = $name;
        $this->notify = $notify;
        $this->room = $room;
        $this->format = $format;
        $this->host = $host;
        $this->version = $version;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        $dataArray = array(
            'notify' => $this->version == self::API_V1 ?
                ($this->notify ? 1 : 0) :
                ($this->notify ? 'true' : 'false'),
            'message' => $record['formatted'],
            'message_format' => $this->format,
            'color' => $this->getAlertColor($record['level']),
        );

        if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
            if (function_exists('mb_substr')) {
                $dataArray['message'] = mb_substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
            } else {
                $dataArray['message'] = substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
            }
        }

        // if we are using the legacy API then we need to send some additional information
        if ($this->version == self::API_V1) {
            $dataArray['room_id'] = $this->room;
        }

        // append the sender name if it is set
        // always append it if we use the v1 api (it is required in v1)
        if ($this->version == self::API_V1 || $this->name !== null) {
            $dataArray['from'] = (string) $this->name;
        }

        return http_build_query($dataArray);
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        if ($this->version == self::API_V1) {
            $header = "POST /v1/rooms/message?format=json&auth_token={$this->token} HTTP/1.1\r\n";
        } else {
            // needed for rooms with special (spaces, etc) characters in the name
            $room = rawurlencode($this->room);
            $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
        }

        $header .= "Host: {$this->host}\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($content) . "\r\n";
        $header .= "\r\n";

        return $header;
    }

    /**
     * Assigns a color to each level of log records.
     *
     * @param  int    $level
     * @return string
     */
    protected function getAlertColor($level)
    {
        switch (true) {
            case $level >= Logger::ERROR:
                return 'red';
            case $level >= Logger::WARNING:
                return 'yellow';
            case $level >= Logger::INFO:
                return 'green';
            case $level == Logger::DEBUG:
                return 'gray';
            default:
                return 'yellow';
        }
    }

    /**
     * {@inheritdoc}
     *
     * @param array $record
     */
    protected function write(array $record)
    {
        parent::write($record);
        $this->finalizeWrite();
    }

    /**
     * Finalizes the request by reading some bytes and then closing the socket
     *
     * If we do not read some but close the socket too early, hipchat sometimes
     * drops the request entirely.
     */
    protected function finalizeWrite()
    {
        $res = $this->getResource();
        if (is_resource($res)) {
            @fread($res, 2048);
        }
        $this->closeSocket();
    }

    /**
     * {@inheritdoc}
     */
    public function handleBatch(array $records)
    {
        if (count($records) == 0) {
            return true;
        }

        $batchRecords = $this->combineRecords($records);

        $handled = false;
        foreach ($batchRecords as $batchRecord) {
            if ($this->isHandling($batchRecord)) {
                $this->write($batchRecord);
                $handled = true;
            }
        }

        if (!$handled) {
            return false;
        }

        return false === $this->bubble;
    }

    /**
     * Combines multiple records into one. Error level of the combined record
     * will be the highest level from the given records. Datetime will be taken
     * from the first record.
     *
     * @param array $records
     * @return array
     */
    private function combineRecords(array $records)
    {
        $batchRecord = null;
        $batchRecords = array();
        $messages = array();
        $formattedMessages = array();
        $level = 0;
        $levelName = null;
        $datetime = null;

        foreach ($records as $record) {
            $record = $this->processRecord($record);

            if ($record['level'] > $level) {
                $level = $record['level'];
                $levelName = $record['level_name'];
            }

            if (null === $datetime) {
                $datetime = $record['datetime'];
            }

            $messages[] = $record['message'];
            $messageStr = implode(PHP_EOL, $messages);
            $formattedMessages[] = $this->getFormatter()->format($record);
            $formattedMessageStr = implode('', $formattedMessages);

            $batchRecord = array(
                'message'   => $messageStr,
                'formatted' => $formattedMessageStr,
                'context'   => array(),
                'extra'     => array(),
            );

            if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
                // Pop the last message and implode the remaining messages
                $lastMessage = array_pop($messages);
                $lastFormattedMessage = array_pop($formattedMessages);
                $batchRecord['message'] = implode(PHP_EOL, $messages);
                $batchRecord['formatted'] = implode('', $formattedMessages);

                $batchRecords[] = $batchRecord;
                $messages = array($lastMessage);
                $formattedMessages = array($lastFormattedMessage);

                $batchRecord = null;
            }
        }

        if (null !== $batchRecord) {
            $batchRecords[] = $batchRecord;
        }

        // Set the max level and datetime for all records
        foreach ($batchRecords as &$batchRecord) {
            $batchRecord = array_merge(
                $batchRecord,
                array(
                    'level'      => $level,
                    'level_name' => $levelName,
                    'datetime'   => $datetime,
                )
            );
        }

        return $batchRecords;
    }

    /**
     * Validates the length of a string.
     *
     * If the `mb_strlen()` function is available, it will use that, as HipChat
     * allows UTF-8 characters. Otherwise, it will fall back to `strlen()`.
     *
     * Note that this might cause false failures in the specific case of using
     * a valid name with less than 16 characters, but 16 or more bytes, on a
     * system where `mb_strlen()` is unavailable.
     *
     * @param string $str
     * @param int    $length
     *
     * @return bool
     */
    private function validateStringLength($str, $length)
    {
        if (function_exists('mb_strlen')) {
            return (mb_strlen($str) <= $length);
        }

        return (strlen($str) <= $length);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;
use Monolog\Logger;

/**
 * Sends logs to Fleep.io using Webhook integrations
 *
 * You'll need a Fleep.io account to use this handler.
 *
 * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation
 * @author Ando Roots <ando@sqroot.eu>
 */
class FleepHookHandler extends SocketHandler
{
    const FLEEP_HOST = 'fleep.io';

    const FLEEP_HOOK_URI = '/hook/';

    /**
     * @var string Webhook token (specifies the conversation where logs are sent)
     */
    protected $token;

    /**
     * Construct a new Fleep.io Handler.
     *
     * For instructions on how to create a new web hook in your conversations
     * see https://fleep.io/integrations/webhooks/
     *
     * @param  string                    $token  Webhook token
     * @param  bool|int                  $level  The minimum logging level at which this handler will be triggered
     * @param  bool                      $bubble Whether the messages that are handled can bubble up the stack or not
     * @throws MissingExtensionException
     */
    public function __construct($token, $level = Logger::DEBUG, $bubble = true)
    {
        if (!extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler');
        }

        $this->token = $token;

        $connectionString = 'ssl://' . self::FLEEP_HOST . ':443';
        parent::__construct($connectionString, $level, $bubble);
    }

    /**
     * Returns the default formatter to use with this handler
     *
     * Overloaded to remove empty context and extra arrays from the end of the log message.
     *
     * @return LineFormatter
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter(null, null, true, true);
    }

    /**
     * Handles a log record
     *
     * @param array $record
     */
    public function write(array $record)
    {
        parent::write($record);
        $this->closeSocket();
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        $header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n";
        $header .= "Host: " . self::FLEEP_HOST . "\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($content) . "\r\n";
        $header .= "\r\n";

        return $header;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        $dataArray = array(
            'message' => $record['formatted'],
        );

        return http_build_query($dataArray);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Blackhole
 *
 * Any record it can handle will be thrown away. This can be used
 * to put on top of an existing stack to override it temporarily.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class NullHandler extends AbstractHandler
{
    /**
     * @param int $level The minimum logging level at which this handler will be triggered
     */
    public function __construct($level = Logger::DEBUG)
    {
        parent::__construct($level, false);
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if ($record['level'] < $this->level) {
            return false;
        }

        return true;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Channel\AMQPChannel;
use AMQPExchange;

class AmqpHandler extends AbstractProcessingHandler
{
    /**
     * @var AMQPExchange|AMQPChannel $exchange
     */
    protected $exchange;

    /**
     * @var string
     */
    protected $exchangeName;

    /**
     * @param AMQPExchange|AMQPChannel $exchange     AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use
     * @param string                   $exchangeName
     * @param int                      $level
     * @param bool                     $bubble       Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
    {
        if ($exchange instanceof AMQPExchange) {
            $exchange->setName($exchangeName);
        } elseif ($exchange instanceof AMQPChannel) {
            $this->exchangeName = $exchangeName;
        } else {
            throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required');
        }
        $this->exchange = $exchange;

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        $data = $record["formatted"];
        $routingKey = $this->getRoutingKey($record);

        if ($this->exchange instanceof AMQPExchange) {
            $this->exchange->publish(
                $data,
                $routingKey,
                0,
                array(
                    'delivery_mode' => 2,
                    'content_type' => 'application/json',
                )
            );
        } else {
            $this->exchange->basic_publish(
                $this->createAmqpMessage($data),
                $this->exchangeName,
                $routingKey
            );
        }
    }

    /**
     * {@inheritDoc}
     */
    public function handleBatch(array $records)
    {
        if ($this->exchange instanceof AMQPExchange) {
            parent::handleBatch($records);

            return;
        }

        foreach ($records as $record) {
            if (!$this->isHandling($record)) {
                continue;
            }

            $record = $this->processRecord($record);
            $data = $this->getFormatter()->format($record);

            $this->exchange->batch_basic_publish(
                $this->createAmqpMessage($data),
                $this->exchangeName,
                $this->getRoutingKey($record)
            );
        }

        $this->exchange->publish_batch();
    }

    /**
     * Gets the routing key for the AMQP exchange
     *
     * @param  array  $record
     * @return string
     */
    protected function getRoutingKey(array $record)
    {
        $routingKey = sprintf(
            '%s.%s',
            // TODO 2.0 remove substr call
            substr($record['level_name'], 0, 4),
            $record['channel']
        );

        return strtolower($routingKey);
    }

    /**
     * @param  string      $data
     * @return AMQPMessage
     */
    private function createAmqpMessage($data)
    {
        return new AMQPMessage(
            (string) $data,
            array(
                'delivery_mode' => 2,
                'content_type' => 'application/json',
            )
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * MandrillHandler uses cURL to send the emails to the Mandrill API
 *
 * @author Adam Nicholson <adamnicholson10@gmail.com>
 */
class MandrillHandler extends MailHandler
{
    protected $message;
    protected $apiKey;

    /**
     * @param string                  $apiKey  A valid Mandrill API key
     * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
     * @param int                     $level   The minimum logging level at which this handler will be triggered
     * @param bool                    $bubble  Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($apiKey, $message, $level = Logger::ERROR, $bubble = true)
    {
        parent::__construct($level, $bubble);

        if (!$message instanceof \Swift_Message && is_callable($message)) {
            $message = call_user_func($message);
        }
        if (!$message instanceof \Swift_Message) {
            throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it');
        }
        $this->message = $message;
        $this->apiKey = $apiKey;
    }

    /**
     * {@inheritdoc}
     */
    protected function send($content, array $records)
    {
        $message = clone $this->message;
        $message->setBody($content);
        if (version_compare(\Swift::VERSION, '6.0.0', '>=')) {
            $message->setDate(new \DateTimeImmutable());
        } else {
            $message->setDate(time());
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
            'key' => $this->apiKey,
            'raw_message' => (string) $message,
            'async' => false,
        )));

        Curl\Util::execute($ch);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\ResettableInterface;

/**
 * Base Handler class providing the Handler structure
 *
 * Classes extending it should (in most cases) only implement write($record)
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Christophe Coevoet <stof@notk.org>
 */
abstract class AbstractProcessingHandler extends AbstractHandler
{
    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        if (!$this->isHandling($record)) {
            return false;
        }

        $record = $this->processRecord($record);

        $record['formatted'] = $this->getFormatter()->format($record);

        $this->write($record);

        return false === $this->bubble;
    }

    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param  array $record
     * @return void
     */
    abstract protected function write(array $record);

    /**
     * Processes a record.
     *
     * @param  array $record
     * @return array
     */
    protected function processRecord(array $record)
    {
        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\JsonFormatter;
use Monolog\Logger;

/**
 * CouchDB handler
 *
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class CouchDBHandler extends AbstractProcessingHandler
{
    private $options;

    public function __construct(array $options = array(), $level = Logger::DEBUG, $bubble = true)
    {
        $this->options = array_merge(array(
            'host'     => 'localhost',
            'port'     => 5984,
            'dbname'   => 'logger',
            'username' => null,
            'password' => null,
        ), $options);

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        $basicAuth = null;
        if ($this->options['username']) {
            $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']);
        }

        $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
        $context = stream_context_create(array(
            'http' => array(
                'method'        => 'POST',
                'content'       => $record['formatted'],
                'ignore_errors' => true,
                'max_redirects' => 0,
                'header'        => 'Content-type: application/json',
            ),
        ));

        if (false === @file_get_contents($url, null, $context)) {
            throw new \RuntimeException(sprintf('Could not connect to %s', $url));
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Formatter\LineFormatter;
use Monolog\Logger;

/**
 * Logs to a Redis key using rpush
 *
 * usage example:
 *
 *   $log = new Logger('application');
 *   $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs", "prod");
 *   $log->pushHandler($redis);
 *
 * @author Thomas Tourlourat <thomas@tourlourat.com>
 */
class RedisHandler extends AbstractProcessingHandler
{
    private $redisClient;
    private $redisKey;
    protected $capSize;

    /**
     * @param \Predis\Client|\Redis $redis   The redis instance
     * @param string                $key     The key name to push records to
     * @param int                   $level   The minimum logging level at which this handler will be triggered
     * @param bool                  $bubble  Whether the messages that are handled can bubble up the stack or not
     * @param int|false             $capSize Number of entries to limit list size to
     */
    public function __construct($redis, $key, $level = Logger::DEBUG, $bubble = true, $capSize = false)
    {
        if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
            throw new \InvalidArgumentException('Predis\Client or Redis instance required');
        }

        $this->redisClient = $redis;
        $this->redisKey = $key;
        $this->capSize = $capSize;

        parent::__construct($level, $bubble);
    }

    /**
     * {@inheritDoc}
     */
    protected function write(array $record)
    {
        if ($this->capSize) {
            $this->writeCapped($record);
        } else {
            $this->redisClient->rpush($this->redisKey, $record["formatted"]);
        }
    }

    /**
     * Write and cap the collection
     * Writes the record to the redis list and caps its
     *
     * @param  array $record associative record array
     * @return void
     */
    protected function writeCapped(array $record)
    {
        if ($this->redisClient instanceof \Redis) {
            $mode = defined('\Redis::MULTI') ? \Redis::MULTI : 1;
            $this->redisClient->multi($mode)
                ->rpush($this->redisKey, $record["formatted"])
                ->ltrim($this->redisKey, -$this->capSize, -1)
                ->exec();
        } else {
            $redisKey = $this->redisKey;
            $capSize = $this->capSize;
            $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) {
                $tx->rpush($redisKey, $record["formatted"]);
                $tx->ltrim($redisKey, -$capSize, -1);
            });
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultFormatter()
    {
        return new LineFormatter();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Utils;

/**
 * Logs to Cube.
 *
 * @link http://square.github.com/cube/
 * @author Wan Chen <kami@kamisama.me>
 */
class CubeHandler extends AbstractProcessingHandler
{
    private $udpConnection;
    private $httpConnection;
    private $scheme;
    private $host;
    private $port;
    private $acceptedSchemes = array('http', 'udp');

    /**
     * Create a Cube handler
     *
     * @throws \UnexpectedValueException when given url is not a valid url.
     *                                   A valid url must consist of three parts : protocol://host:port
     *                                   Only valid protocols used by Cube are http and udp
     */
    public function __construct($url, $level = Logger::DEBUG, $bubble = true)
    {
        $urlInfo = parse_url($url);

        if (!isset($urlInfo['scheme'], $urlInfo['host'], $urlInfo['port'])) {
            throw new \UnexpectedValueException('URL "'.$url.'" is not valid');
        }

        if (!in_array($urlInfo['scheme'], $this->acceptedSchemes)) {
            throw new \UnexpectedValueException(
                'Invalid protocol (' . $urlInfo['scheme']  . ').'
                . ' Valid options are ' . implode(', ', $this->acceptedSchemes));
        }

        $this->scheme = $urlInfo['scheme'];
        $this->host = $urlInfo['host'];
        $this->port = $urlInfo['port'];

        parent::__construct($level, $bubble);
    }

    /**
     * Establish a connection to an UDP socket
     *
     * @throws \LogicException           when unable to connect to the socket
     * @throws MissingExtensionException when there is no socket extension
     */
    protected function connectUdp()
    {
        if (!extension_loaded('sockets')) {
            throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler');
        }

        $this->udpConnection = socket_create(AF_INET, SOCK_DGRAM, 0);
        if (!$this->udpConnection) {
            throw new \LogicException('Unable to create a socket');
        }

        if (!socket_connect($this->udpConnection, $this->host, $this->port)) {
            throw new \LogicException('Unable to connect to the socket at ' . $this->host . ':' . $this->port);
        }
    }

    /**
     * Establish a connection to a http server
     * @throws \LogicException when no curl extension
     */
    protected function connectHttp()
    {
        if (!extension_loaded('curl')) {
            throw new \LogicException('The curl extension is needed to use http URLs with the CubeHandler');
        }

        $this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put');

        if (!$this->httpConnection) {
            throw new \LogicException('Unable to connect to ' . $this->host . ':' . $this->port);
        }

        curl_setopt($this->httpConnection, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($this->httpConnection, CURLOPT_RETURNTRANSFER, true);
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $date = $record['datetime'];

        $data = array('time' => $date->format('Y-m-d\TH:i:s.uO'));
        unset($record['datetime']);

        if (isset($record['context']['type'])) {
            $data['type'] = $record['context']['type'];
            unset($record['context']['type']);
        } else {
            $data['type'] = $record['channel'];
        }

        $data['data'] = $record['context'];
        $data['data']['level'] = $record['level'];

        if ($this->scheme === 'http') {
            $this->writeHttp(Utils::jsonEncode($data));
        } else {
            $this->writeUdp(Utils::jsonEncode($data));
        }
    }

    private function writeUdp($data)
    {
        if (!$this->udpConnection) {
            $this->connectUdp();
        }

        socket_send($this->udpConnection, $data, strlen($data), 0);
    }

    private function writeHttp($data)
    {
        if (!$this->httpConnection) {
            $this->connectHttp();
        }

        curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']');
        curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen('['.$data.']'),
        ));

        Curl\Util::execute($this->httpConnection, 5, false);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\SyslogUdp;

class UdpSocket
{
    const DATAGRAM_MAX_LENGTH = 65023;

    protected $ip;
    protected $port;
    protected $socket;

    public function __construct($ip, $port = 514)
    {
        $this->ip = $ip;
        $this->port = $port;
        $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    }

    public function write($line, $header = "")
    {
        $this->send($this->assembleMessage($line, $header));
    }

    public function close()
    {
        if (is_resource($this->socket)) {
            socket_close($this->socket);
            $this->socket = null;
        }
    }

    protected function send($chunk)
    {
        if (!is_resource($this->socket)) {
            throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
        }
        socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
    }

    protected function assembleMessage($line, $header)
    {
        $chunkSize = self::DATAGRAM_MAX_LENGTH - strlen($header);

        return $header . substr($line, 0, $chunkSize);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Monolog\Handler\HandlerInterface;
use Monolog\Handler\StreamHandler;
use Psr\Log\LoggerInterface;
use Psr\Log\InvalidArgumentException;
use Exception;

/**
 * Monolog log channel
 *
 * It contains a stack of Handlers and a stack of Processors,
 * and uses them to store records that are added to it.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Logger implements LoggerInterface, ResettableInterface
{
    /**
     * Detailed debug information
     */
    const DEBUG = 100;

    /**
     * Interesting events
     *
     * Examples: User logs in, SQL logs.
     */
    const INFO = 200;

    /**
     * Uncommon events
     */
    const NOTICE = 250;

    /**
     * Exceptional occurrences that are not errors
     *
     * Examples: Use of deprecated APIs, poor use of an API,
     * undesirable things that are not necessarily wrong.
     */
    const WARNING = 300;

    /**
     * Runtime errors
     */
    const ERROR = 400;

    /**
     * Critical conditions
     *
     * Example: Application component unavailable, unexpected exception.
     */
    const CRITICAL = 500;

    /**
     * Action must be taken immediately
     *
     * Example: Entire website down, database unavailable, etc.
     * This should trigger the SMS alerts and wake you up.
     */
    const ALERT = 550;

    /**
     * Urgent alert.
     */
    const EMERGENCY = 600;

    /**
     * Monolog API version
     *
     * This is only bumped when API breaks are done and should
     * follow the major version of the library
     *
     * @var int
     */
    const API = 1;

    /**
     * Logging levels from syslog protocol defined in RFC 5424
     *
     * @var array $levels Logging levels
     */
    protected static $levels = array(
        self::DEBUG     => 'DEBUG',
        self::INFO      => 'INFO',
        self::NOTICE    => 'NOTICE',
        self::WARNING   => 'WARNING',
        self::ERROR     => 'ERROR',
        self::CRITICAL  => 'CRITICAL',
        self::ALERT     => 'ALERT',
        self::EMERGENCY => 'EMERGENCY',
    );

    /**
     * @var \DateTimeZone
     */
    protected static $timezone;

    /**
     * @var string
     */
    protected $name;

    /**
     * The handler stack
     *
     * @var HandlerInterface[]
     */
    protected $handlers;

    /**
     * Processors that will process all log records
     *
     * To process records of a single handler instead, add the processor on that specific handler
     *
     * @var callable[]
     */
    protected $processors;

    /**
     * @var bool
     */
    protected $microsecondTimestamps = true;

    /**
     * @var callable
     */
    protected $exceptionHandler;

    /**
     * @param string             $name       The logging channel
     * @param HandlerInterface[] $handlers   Optional stack of handlers, the first one in the array is called first, etc.
     * @param callable[]         $processors Optional array of processors
     */
    public function __construct($name, array $handlers = array(), array $processors = array())
    {
        $this->name = $name;
        $this->setHandlers($handlers);
        $this->processors = $processors;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Return a new cloned instance with the name changed
     *
     * @return static
     */
    public function withName($name)
    {
        $new = clone $this;
        $new->name = $name;

        return $new;
    }

    /**
     * Pushes a handler on to the stack.
     *
     * @param  HandlerInterface $handler
     * @return $this
     */
    public function pushHandler(HandlerInterface $handler)
    {
        array_unshift($this->handlers, $handler);

        return $this;
    }

    /**
     * Pops a handler from the stack
     *
     * @return HandlerInterface
     */
    public function popHandler()
    {
        if (!$this->handlers) {
            throw new \LogicException('You tried to pop from an empty handler stack.');
        }

        return array_shift($this->handlers);
    }

    /**
     * Set handlers, replacing all existing ones.
     *
     * If a map is passed, keys will be ignored.
     *
     * @param  HandlerInterface[] $handlers
     * @return $this
     */
    public function setHandlers(array $handlers)
    {
        $this->handlers = array();
        foreach (array_reverse($handlers) as $handler) {
            $this->pushHandler($handler);
        }

        return $this;
    }

    /**
     * @return HandlerInterface[]
     */
    public function getHandlers()
    {
        return $this->handlers;
    }

    /**
     * Adds a processor on to the stack.
     *
     * @param  callable $callback
     * @return $this
     */
    public function pushProcessor($callback)
    {
        if (!is_callable($callback)) {
            throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
        }
        array_unshift($this->processors, $callback);

        return $this;
    }

    /**
     * Removes the processor on top of the stack and returns it.
     *
     * @return callable
     */
    public function popProcessor()
    {
        if (!$this->processors) {
            throw new \LogicException('You tried to pop from an empty processor stack.');
        }

        return array_shift($this->processors);
    }

    /**
     * @return callable[]
     */
    public function getProcessors()
    {
        return $this->processors;
    }

    /**
     * Control the use of microsecond resolution timestamps in the 'datetime'
     * member of new records.
     *
     * Generating microsecond resolution timestamps by calling
     * microtime(true), formatting the result via sprintf() and then parsing
     * the resulting string via \DateTime::createFromFormat() can incur
     * a measurable runtime overhead vs simple usage of DateTime to capture
     * a second resolution timestamp in systems which generate a large number
     * of log events.
     *
     * @param bool $micro True to use microtime() to create timestamps
     */
    public function useMicrosecondTimestamps($micro)
    {
        $this->microsecondTimestamps = (bool) $micro;
    }

    /**
     * Adds a log record.
     *
     * @param  int     $level   The logging level
     * @param  string  $message The log message
     * @param  array   $context The log context
     * @return bool Whether the record has been processed
     */
    public function addRecord($level, $message, array $context = array())
    {
        if (!$this->handlers) {
            $this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
        }

        $levelName = static::getLevelName($level);

        // check if any handler will handle this message so we can return early and save cycles
        $handlerKey = null;
        reset($this->handlers);
        while ($handler = current($this->handlers)) {
            if ($handler->isHandling(array('level' => $level))) {
                $handlerKey = key($this->handlers);
                break;
            }

            next($this->handlers);
        }

        if (null === $handlerKey) {
            return false;
        }

        if (!static::$timezone) {
            static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC');
        }

        // php7.1+ always has microseconds enabled, so we do not need this hack
        if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) {
            $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone);
        } else {
            $ts = new \DateTime('now', static::$timezone);
        }
        $ts->setTimezone(static::$timezone);

        $record = array(
            'message' => (string) $message,
            'context' => $context,
            'level' => $level,
            'level_name' => $levelName,
            'channel' => $this->name,
            'datetime' => $ts,
            'extra' => array(),
        );

        try {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }

            while ($handler = current($this->handlers)) {
                if (true === $handler->handle($record)) {
                    break;
                }

                next($this->handlers);
            }
        } catch (Exception $e) {
            $this->handleException($e, $record);
        }

        return true;
    }

    /**
     * Ends a log cycle and frees all resources used by handlers.
     *
     * Closing a Handler means flushing all buffers and freeing any open resources/handles.
     * Handlers that have been closed should be able to accept log records again and re-open
     * themselves on demand, but this may not always be possible depending on implementation.
     *
     * This is useful at the end of a request and will be called automatically on every handler
     * when they get destructed.
     */
    public function close()
    {
        foreach ($this->handlers as $handler) {
            if (method_exists($handler, 'close')) {
                $handler->close();
            }
        }
    }

    /**
     * Ends a log cycle and resets all handlers and processors to their initial state.
     *
     * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
     * state, and getting it back to a state in which it can receive log records again.
     *
     * This is useful in case you want to avoid logs leaking between two requests or jobs when you
     * have a long running process like a worker or an application server serving multiple requests
     * in one process.
     */
    public function reset()
    {
        foreach ($this->handlers as $handler) {
            if ($handler instanceof ResettableInterface) {
                $handler->reset();
            }
        }

        foreach ($this->processors as $processor) {
            if ($processor instanceof ResettableInterface) {
                $processor->reset();
            }
        }
    }

    /**
     * Adds a log record at the DEBUG level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addDebug($message, array $context = array())
    {
        return $this->addRecord(static::DEBUG, $message, $context);
    }

    /**
     * Adds a log record at the INFO level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addInfo($message, array $context = array())
    {
        return $this->addRecord(static::INFO, $message, $context);
    }

    /**
     * Adds a log record at the NOTICE level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addNotice($message, array $context = array())
    {
        return $this->addRecord(static::NOTICE, $message, $context);
    }

    /**
     * Adds a log record at the WARNING level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addWarning($message, array $context = array())
    {
        return $this->addRecord(static::WARNING, $message, $context);
    }

    /**
     * Adds a log record at the ERROR level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addError($message, array $context = array())
    {
        return $this->addRecord(static::ERROR, $message, $context);
    }

    /**
     * Adds a log record at the CRITICAL level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addCritical($message, array $context = array())
    {
        return $this->addRecord(static::CRITICAL, $message, $context);
    }

    /**
     * Adds a log record at the ALERT level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addAlert($message, array $context = array())
    {
        return $this->addRecord(static::ALERT, $message, $context);
    }

    /**
     * Adds a log record at the EMERGENCY level.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function addEmergency($message, array $context = array())
    {
        return $this->addRecord(static::EMERGENCY, $message, $context);
    }

    /**
     * Gets all supported logging levels.
     *
     * @return array Assoc array with human-readable level names => level codes.
     */
    public static function getLevels()
    {
        return array_flip(static::$levels);
    }

    /**
     * Gets the name of the logging level.
     *
     * @param  int    $level
     * @return string
     */
    public static function getLevelName($level)
    {
        if (!isset(static::$levels[$level])) {
            throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
        }

        return static::$levels[$level];
    }

    /**
     * Converts PSR-3 levels to Monolog ones if necessary
     *
     * @param string|int $level Level number (monolog) or name (PSR-3)
     * @return int
     */
    public static function toMonologLevel($level)
    {
        if (is_string($level)) {
            // Contains chars of all log levels and avoids using strtoupper() which may have
            // strange results depending on locale (for example, "i" will become "İ")
            $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY');
            if (defined(__CLASS__.'::'.$upper)) {
                return constant(__CLASS__ . '::' . $upper);
            }
        }

        return $level;
    }

    /**
     * Checks whether the Logger has a handler that listens on the given level
     *
     * @param  int     $level
     * @return bool
     */
    public function isHandling($level)
    {
        $record = array(
            'level' => $level,
        );

        foreach ($this->handlers as $handler) {
            if ($handler->isHandling($record)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Set a custom exception handler
     *
     * @param  callable $callback
     * @return $this
     */
    public function setExceptionHandler($callback)
    {
        if (!is_callable($callback)) {
            throw new \InvalidArgumentException('Exception handler must be valid callable (callback or object with an __invoke method), '.var_export($callback, true).' given');
        }
        $this->exceptionHandler = $callback;

        return $this;
    }

    /**
     * @return callable
     */
    public function getExceptionHandler()
    {
        return $this->exceptionHandler;
    }

    /**
     * Delegates exception management to the custom exception handler,
     * or throws the exception if no custom handler is set.
     */
    protected function handleException(Exception $e, array $record)
    {
        if (!$this->exceptionHandler) {
            throw $e;
        }

        call_user_func($this->exceptionHandler, $e, $record);
    }

    /**
     * Adds a log record at an arbitrary level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  mixed   $level   The log level
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function log($level, $message, array $context = array())
    {
        $level = static::toMonologLevel($level);

        return $this->addRecord($level, $message, $context);
    }

    /**
     * Adds a log record at the DEBUG level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function debug($message, array $context = array())
    {
        return $this->addRecord(static::DEBUG, $message, $context);
    }

    /**
     * Adds a log record at the INFO level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function info($message, array $context = array())
    {
        return $this->addRecord(static::INFO, $message, $context);
    }

    /**
     * Adds a log record at the NOTICE level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function notice($message, array $context = array())
    {
        return $this->addRecord(static::NOTICE, $message, $context);
    }

    /**
     * Adds a log record at the WARNING level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function warn($message, array $context = array())
    {
        return $this->addRecord(static::WARNING, $message, $context);
    }

    /**
     * Adds a log record at the WARNING level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function warning($message, array $context = array())
    {
        return $this->addRecord(static::WARNING, $message, $context);
    }

    /**
     * Adds a log record at the ERROR level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function err($message, array $context = array())
    {
        return $this->addRecord(static::ERROR, $message, $context);
    }

    /**
     * Adds a log record at the ERROR level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function error($message, array $context = array())
    {
        return $this->addRecord(static::ERROR, $message, $context);
    }

    /**
     * Adds a log record at the CRITICAL level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function crit($message, array $context = array())
    {
        return $this->addRecord(static::CRITICAL, $message, $context);
    }

    /**
     * Adds a log record at the CRITICAL level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function critical($message, array $context = array())
    {
        return $this->addRecord(static::CRITICAL, $message, $context);
    }

    /**
     * Adds a log record at the ALERT level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function alert($message, array $context = array())
    {
        return $this->addRecord(static::ALERT, $message, $context);
    }

    /**
     * Adds a log record at the EMERGENCY level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function emerg($message, array $context = array())
    {
        return $this->addRecord(static::EMERGENCY, $message, $context);
    }

    /**
     * Adds a log record at the EMERGENCY level.
     *
     * This method allows for compatibility with common interfaces.
     *
     * @param  string $message The log message
     * @param  array  $context The log context
     * @return bool   Whether the record has been processed
     */
    public function emergency($message, array $context = array())
    {
        return $this->addRecord(static::EMERGENCY, $message, $context);
    }

    /**
     * Set the timezone to be used for the timestamp of log records.
     *
     * This is stored globally for all Logger instances
     *
     * @param \DateTimeZone $tz Timezone object
     */
    public static function setTimezone(\DateTimeZone $tz)
    {
        self::$timezone = $tz;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use InvalidArgumentException;

/**
 * Monolog log registry
 *
 * Allows to get `Logger` instances in the global scope
 * via static method calls on this class.
 *
 * <code>
 * $application = new Monolog\Logger('application');
 * $api = new Monolog\Logger('api');
 *
 * Monolog\Registry::addLogger($application);
 * Monolog\Registry::addLogger($api);
 *
 * function testLogger()
 * {
 *     Monolog\Registry::api()->addError('Sent to $api Logger instance');
 *     Monolog\Registry::application()->addError('Sent to $application Logger instance');
 * }
 * </code>
 *
 * @author Tomas Tatarko <tomas@tatarko.sk>
 */
class Registry
{
    /**
     * List of all loggers in the registry (by named indexes)
     *
     * @var Logger[]
     */
    private static $loggers = array();

    /**
     * Adds new logging channel to the registry
     *
     * @param  Logger                    $logger    Instance of the logging channel
     * @param  string|null               $name      Name of the logging channel ($logger->getName() by default)
     * @param  bool                      $overwrite Overwrite instance in the registry if the given name already exists?
     * @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists
     */
    public static function addLogger(Logger $logger, $name = null, $overwrite = false)
    {
        $name = $name ?: $logger->getName();

        if (isset(self::$loggers[$name]) && !$overwrite) {
            throw new InvalidArgumentException('Logger with the given name already exists');
        }

        self::$loggers[$name] = $logger;
    }

    /**
     * Checks if such logging channel exists by name or instance
     *
     * @param string|Logger $logger Name or logger instance
     */
    public static function hasLogger($logger)
    {
        if ($logger instanceof Logger) {
            $index = array_search($logger, self::$loggers, true);

            return false !== $index;
        } else {
            return isset(self::$loggers[$logger]);
        }
    }

    /**
     * Removes instance from registry by name or instance
     *
     * @param string|Logger $logger Name or logger instance
     */
    public static function removeLogger($logger)
    {
        if ($logger instanceof Logger) {
            if (false !== ($idx = array_search($logger, self::$loggers, true))) {
                unset(self::$loggers[$idx]);
            }
        } else {
            unset(self::$loggers[$logger]);
        }
    }

    /**
     * Clears the registry
     */
    public static function clear()
    {
        self::$loggers = array();
    }

    /**
     * Gets Logger instance from the registry
     *
     * @param  string                    $name Name of the requested Logger instance
     * @throws \InvalidArgumentException If named Logger instance is not in the registry
     * @return Logger                    Requested instance of Logger
     */
    public static function getInstance($name)
    {
        if (!isset(self::$loggers[$name])) {
            throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name));
        }

        return self::$loggers[$name];
    }

    /**
     * Gets Logger instance from the registry via static method call
     *
     * @param  string                    $name      Name of the requested Logger instance
     * @param  array                     $arguments Arguments passed to static method call
     * @throws \InvalidArgumentException If named Logger instance is not in the registry
     * @return Logger                    Requested instance of Logger
     */
    public static function __callStatic($name, $arguments)
    {
        return self::getInstance($name);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\Utils;

/**
 * Processes a record's message according to PSR-3 rules
 *
 * It replaces {foo} with the value from $context['foo']
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class PsrLogMessageProcessor implements ProcessorInterface
{
    const SIMPLE_DATE = "Y-m-d\TH:i:s.uP";

    /** @var string|null */
    private $dateFormat;

    /** @var bool */
    private $removeUsedContextFields;

    /**
     * @param string|null $dateFormat              The format of the timestamp: one supported by DateTime::format
     * @param bool        $removeUsedContextFields If set to true the fields interpolated into message gets unset
     */
    public function __construct($dateFormat = null, $removeUsedContextFields = false)
    {
        $this->dateFormat = $dateFormat;
        $this->removeUsedContextFields = $removeUsedContextFields;
    }

    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        if (false === strpos($record['message'], '{')) {
            return $record;
        }

        $replacements = array();
        foreach ($record['context'] as $key => $val) {
            $placeholder = '{' . $key . '}';
            if (strpos($record['message'], $placeholder) === false) {
                continue;
            }

            if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) {
                $replacements[$placeholder] = $val;
            } elseif ($val instanceof \DateTime) {
                $replacements[$placeholder] = $val->format($this->dateFormat ?: static::SIMPLE_DATE);
            } elseif (is_object($val)) {
                $replacements[$placeholder] = '[object '.Utils::getClass($val).']';
            } elseif (is_array($val)) {
                $replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true);
            } else {
                $replacements[$placeholder] = '['.gettype($val).']';
            }

            if ($this->removeUsedContextFields) {
                unset($record['context'][$key]);
            }
        }

        $record['message'] = strtr($record['message'], $replacements);

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Injects url/method and remote IP of the current web request in all records
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class WebProcessor implements ProcessorInterface
{
    /**
     * @var array|\ArrayAccess
     */
    protected $serverData;

    /**
     * Default fields
     *
     * Array is structured as [key in record.extra => key in $serverData]
     *
     * @var array
     */
    protected $extraFields = array(
        'url'         => 'REQUEST_URI',
        'ip'          => 'REMOTE_ADDR',
        'http_method' => 'REQUEST_METHOD',
        'server'      => 'SERVER_NAME',
        'referrer'    => 'HTTP_REFERER',
    );

    /**
     * @param array|\ArrayAccess $serverData  Array or object w/ ArrayAccess that provides access to the $_SERVER data
     * @param array|null         $extraFields Field names and the related key inside $serverData to be added. If not provided it defaults to: url, ip, http_method, server, referrer
     */
    public function __construct($serverData = null, array $extraFields = null)
    {
        if (null === $serverData) {
            $this->serverData = &$_SERVER;
        } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) {
            $this->serverData = $serverData;
        } else {
            throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.');
        }

        if (isset($this->serverData['UNIQUE_ID'])) {
            $this->extraFields['unique_id'] = 'UNIQUE_ID';
        }

        if (null !== $extraFields) {
            if (isset($extraFields[0])) {
                foreach (array_keys($this->extraFields) as $fieldName) {
                    if (!in_array($fieldName, $extraFields)) {
                        unset($this->extraFields[$fieldName]);
                    }
                }
            } else {
                $this->extraFields = $extraFields;
            }
        }
    }

    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        // skip processing if for some reason request data
        // is not present (CLI or wonky SAPIs)
        if (!isset($this->serverData['REQUEST_URI'])) {
            return $record;
        }

        $record['extra'] = $this->appendExtraFields($record['extra']);

        return $record;
    }

    /**
     * @param  string $extraName
     * @param  string $serverName
     * @return $this
     */
    public function addExtraField($extraName, $serverName)
    {
        $this->extraFields[$extraName] = $serverName;

        return $this;
    }

    /**
     * @param  array $extra
     * @return array
     */
    private function appendExtraFields(array $extra)
    {
        foreach ($this->extraFields as $extraName => $serverName) {
            $extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null;
        }

        return $extra;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Injects memory_get_peak_usage in all records
 *
 * @see Monolog\Processor\MemoryProcessor::__construct() for options
 * @author Rob Jensen
 */
class MemoryPeakUsageProcessor extends MemoryProcessor
{
    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        $bytes = memory_get_peak_usage($this->realUsage);
        $formatted = $this->formatBytes($bytes);

        $record['extra']['memory_peak_usage'] = $formatted;

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Adds value of getmypid into records
 *
 * @author Andreas Hörnicke
 */
class ProcessIdProcessor implements ProcessorInterface
{
    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        $record['extra']['process_id'] = getmypid();

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jonathan A. Schweder <jonathanschweder@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\Logger;

/**
 * Injects Hg branch and Hg revision number in all records
 *
 * @author Jonathan A. Schweder <jonathanschweder@gmail.com>
 */
class MercurialProcessor implements ProcessorInterface
{
    private $level;
    private static $cache;

    public function __construct($level = Logger::DEBUG)
    {
        $this->level = Logger::toMonologLevel($level);
    }

    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        // return if the level is not high enough
        if ($record['level'] < $this->level) {
            return $record;
        }

        $record['extra']['hg'] = self::getMercurialInfo();

        return $record;
    }

    private static function getMercurialInfo()
    {
        if (self::$cache) {
            return self::$cache;
        }

        $result = explode(' ', trim(`hg id -nb`));
        if (count($result) >= 3) {
            return self::$cache = array(
                'branch' => $result[1],
                'revision' => $result[2],
            );
        }

        return self::$cache = array();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Adds a tags array into record
 *
 * @author Martijn Riemers
 */
class TagProcessor implements ProcessorInterface
{
    private $tags;

    public function __construct(array $tags = array())
    {
        $this->setTags($tags);
    }

    public function addTags(array $tags = array())
    {
        $this->tags = array_merge($this->tags, $tags);
    }

    public function setTags(array $tags = array())
    {
        $this->tags = $tags;
    }

    public function __invoke(array $record)
    {
        $record['extra']['tags'] = $this->tags;

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\Logger;

/**
 * Injects Git branch and Git commit SHA in all records
 *
 * @author Nick Otter
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class GitProcessor implements ProcessorInterface
{
    private $level;
    private static $cache;

    public function __construct($level = Logger::DEBUG)
    {
        $this->level = Logger::toMonologLevel($level);
    }

    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        // return if the level is not high enough
        if ($record['level'] < $this->level) {
            return $record;
        }

        $record['extra']['git'] = self::getGitInfo();

        return $record;
    }

    private static function getGitInfo()
    {
        if (self::$cache) {
            return self::$cache;
        }

        $branches = `git branch -v --no-abbrev`;
        if ($branches && preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) {
            return self::$cache = array(
                'branch' => $matches[1],
                'commit' => $matches[2],
            );
        }

        return self::$cache = array();
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Some methods that are common for all memory processors
 *
 * @author Rob Jensen
 */
abstract class MemoryProcessor implements ProcessorInterface
{
    /**
     * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported.
     */
    protected $realUsage;

    /**
     * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size)
     */
    protected $useFormatting;

    /**
     * @param bool $realUsage     Set this to true to get the real size of memory allocated from system.
     * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size)
     */
    public function __construct($realUsage = true, $useFormatting = true)
    {
        $this->realUsage = (bool) $realUsage;
        $this->useFormatting = (bool) $useFormatting;
    }

    /**
     * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
     *
     * @param  int        $bytes
     * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as is
     */
    protected function formatBytes($bytes)
    {
        $bytes = (int) $bytes;

        if (!$this->useFormatting) {
            return $bytes;
        }

        if ($bytes > 1024 * 1024) {
            return round($bytes / 1024 / 1024, 2).' MB';
        } elseif ($bytes > 1024) {
            return round($bytes / 1024, 2).' KB';
        }

        return $bytes . ' B';
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\Logger;

/**
 * Injects line/file:class/function where the log message came from
 *
 * Warning: This only works if the handler processes the logs directly.
 * If you put the processor on a handler that is behind a FingersCrossedHandler
 * for example, the processor will only be called once the trigger level is reached,
 * and all the log records will have the same file/line/.. data from the call that
 * triggered the FingersCrossedHandler.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class IntrospectionProcessor implements ProcessorInterface
{
    private $level;

    private $skipClassesPartials;

    private $skipStackFramesCount;

    private $skipFunctions = array(
        'call_user_func',
        'call_user_func_array',
    );

    public function __construct($level = Logger::DEBUG, array $skipClassesPartials = array(), $skipStackFramesCount = 0)
    {
        $this->level = Logger::toMonologLevel($level);
        $this->skipClassesPartials = array_merge(array('Monolog\\'), $skipClassesPartials);
        $this->skipStackFramesCount = $skipStackFramesCount;
    }

    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        // return if the level is not high enough
        if ($record['level'] < $this->level) {
            return $record;
        }

        /*
        * http://php.net/manual/en/function.debug-backtrace.php
        * As of 5.3.6, DEBUG_BACKTRACE_IGNORE_ARGS option was added.
        * Any version less than 5.3.6 must use the DEBUG_BACKTRACE_IGNORE_ARGS constant value '2'.
        */
        $trace = debug_backtrace((PHP_VERSION_ID < 50306) ? 2 : DEBUG_BACKTRACE_IGNORE_ARGS);

        // skip first since it's always the current method
        array_shift($trace);
        // the call_user_func call is also skipped
        array_shift($trace);

        $i = 0;

        while ($this->isTraceClassOrSkippedFunction($trace, $i)) {
            if (isset($trace[$i]['class'])) {
                foreach ($this->skipClassesPartials as $part) {
                    if (strpos($trace[$i]['class'], $part) !== false) {
                        $i++;
                        continue 2;
                    }
                }
            } elseif (in_array($trace[$i]['function'], $this->skipFunctions)) {
                $i++;
                continue;
            }

            break;
        }

        $i += $this->skipStackFramesCount;

        // we should have the call source now
        $record['extra'] = array_merge(
            $record['extra'],
            array(
                'file'      => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null,
                'line'      => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null,
                'class'     => isset($trace[$i]['class']) ? $trace[$i]['class'] : null,
                'function'  => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
            )
        );

        return $record;
    }

    private function isTraceClassOrSkippedFunction(array $trace, $index)
    {
        if (!isset($trace[$index])) {
            return false;
        }

        return isset($trace[$index]['class']) || in_array($trace[$index]['function'], $this->skipFunctions);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

use Monolog\ResettableInterface;

/**
 * Adds a unique identifier into records
 *
 * @author Simon Mönch <sm@webfactory.de>
 */
class UidProcessor implements ProcessorInterface, ResettableInterface
{
    private $uid;

    public function __construct($length = 7)
    {
        if (!is_int($length) || $length > 32 || $length < 1) {
            throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
        }


        $this->uid = $this->generateUid($length);
    }

    public function __invoke(array $record)
    {
        $record['extra']['uid'] = $this->uid;

        return $record;
    }

    /**
     * @return string
     */
    public function getUid()
    {
        return $this->uid;
    }

    public function reset()
    {
        $this->uid = $this->generateUid(strlen($this->uid));
    }

    private function generateUid($length)
    {
        return substr(hash('md5', uniqid('', true)), 0, $length);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * An optional interface to allow labelling Monolog processors.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
interface ProcessorInterface
{
    /**
     * @return array The processed records
     */
    public function __invoke(array $records);
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Processor;

/**
 * Injects memory_get_usage in all records
 *
 * @see Monolog\Processor\MemoryProcessor::__construct() for options
 * @author Rob Jensen
 */
class MemoryUsageProcessor extends MemoryProcessor
{
    /**
     * @param  array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        $bytes = memory_get_usage($this->realUsage);
        $formatted = $this->formatBytes($bytes);

        $record['extra']['memory_usage'] = $formatted;

        return $record;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

/**
 * Handler or Processor implementing this interface will be reset when Logger::reset() is called.
 *
 * Resetting ends a log cycle gets them back to their initial state.
 *
 * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
 * state, and getting it back to a state in which it can receive log records again.
 *
 * This is useful in case you want to avoid logs leaking between two requests or jobs when you
 * have a long running process like a worker or an application server serving multiple requests
 * in one process.
 *
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
interface ResettableInterface
{
    public function reset();
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use ReflectionExtension;

/**
 * Monolog POSIX signal handler
 *
 * @author Robert Gust-Bardon <robert@gust-bardon.org>
 */
class SignalHandler
{
    private $logger;

    private $previousSignalHandler = array();
    private $signalLevelMap = array();
    private $signalRestartSyscalls = array();

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function registerSignalHandler($signo, $level = LogLevel::CRITICAL, $callPrevious = true, $restartSyscalls = true, $async = true)
    {
        if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) {
            return $this;
        }

        if ($callPrevious) {
            if (function_exists('pcntl_signal_get_handler')) {
                $handler = pcntl_signal_get_handler($signo);
                if ($handler === false) {
                    return $this;
                }
                $this->previousSignalHandler[$signo] = $handler;
            } else {
                $this->previousSignalHandler[$signo] = true;
            }
        } else {
            unset($this->previousSignalHandler[$signo]);
        }
        $this->signalLevelMap[$signo] = $level;
        $this->signalRestartSyscalls[$signo] = $restartSyscalls;

        if (function_exists('pcntl_async_signals') && $async !== null) {
            pcntl_async_signals($async);
        }

        pcntl_signal($signo, array($this, 'handleSignal'), $restartSyscalls);

        return $this;
    }

    public function handleSignal($signo, array $siginfo = null)
    {
        static $signals = array();

        if (!$signals && extension_loaded('pcntl')) {
            $pcntl = new ReflectionExtension('pcntl');
            $constants = $pcntl->getConstants();
            if (!$constants) {
                // HHVM 3.24.2 returns an empty array.
                $constants = get_defined_constants(true);
                $constants = $constants['Core'];
            }
            foreach ($constants as $name => $value) {
                if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && is_int($value)) {
                    $signals[$value] = $name;
                }
            }
            unset($constants);
        }

        $level = isset($this->signalLevelMap[$signo]) ? $this->signalLevelMap[$signo] : LogLevel::CRITICAL;
        $signal = isset($signals[$signo]) ? $signals[$signo] : $signo;
        $context = isset($siginfo) ? $siginfo : array();
        $this->logger->log($level, sprintf('Program received signal %s', $signal), $context);

        if (!isset($this->previousSignalHandler[$signo])) {
            return;
        }

        if ($this->previousSignalHandler[$signo] === true || $this->previousSignalHandler[$signo] === SIG_DFL) {
            if (extension_loaded('pcntl') && function_exists('pcntl_signal') && function_exists('pcntl_sigprocmask') && function_exists('pcntl_signal_dispatch')
                && extension_loaded('posix') && function_exists('posix_getpid') && function_exists('posix_kill')) {
                    $restartSyscalls = isset($this->signalRestartSyscalls[$signo]) ? $this->signalRestartSyscalls[$signo] : true;
                    pcntl_signal($signo, SIG_DFL, $restartSyscalls);
                    pcntl_sigprocmask(SIG_UNBLOCK, array($signo), $oldset);
                    posix_kill(posix_getpid(), $signo);
                    pcntl_signal_dispatch();
                    pcntl_sigprocmask(SIG_SETMASK, $oldset);
                    pcntl_signal($signo, array($this, 'handleSignal'), $restartSyscalls);
                }
        } elseif (is_callable($this->previousSignalHandler[$signo])) {
            if (PHP_VERSION_ID >= 70100) {
                $this->previousSignalHandler[$signo]($signo, $siginfo);
            } else {
                $this->previousSignalHandler[$signo]($signo);
            }
        }
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Elastica\Document;

/**
 * Format a log message into an Elastica Document
 *
 * @author Jelle Vink <jelle.vink@gmail.com>
 */
class ElasticaFormatter extends NormalizerFormatter
{
    /**
     * @var string Elastic search index name
     */
    protected $index;

    /**
     * @var string Elastic search document type
     */
    protected $type;

    /**
     * @param string $index Elastic Search index name
     * @param string $type  Elastic Search document type
     */
    public function __construct($index, $type)
    {
        // elasticsearch requires a ISO 8601 format date with optional millisecond precision.
        parent::__construct('Y-m-d\TH:i:s.uP');

        $this->index = $index;
        $this->type = $type;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $record = parent::format($record);

        return $this->getDocument($record);
    }

    /**
     * Getter index
     * @return string
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * Getter type
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Convert a log message into an Elastica Document
     *
     * @param  array    $record Log message
     * @return Document
     */
    protected function getDocument($record)
    {
        $document = new Document();
        $document->setData($record);
        $document->setType($this->type);
        $document->setIndex($this->index);

        return $document;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Utils;

/**
 * Formats incoming records into a one-line string
 *
 * This is especially useful for logging to files
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Christophe Coevoet <stof@notk.org>
 */
class LineFormatter extends NormalizerFormatter
{
    const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";

    protected $format;
    protected $allowInlineLineBreaks;
    protected $ignoreEmptyContextAndExtra;
    protected $includeStacktraces;

    /**
     * @param string $format                     The format of the message
     * @param string $dateFormat                 The format of the timestamp: one supported by DateTime::format
     * @param bool   $allowInlineLineBreaks      Whether to allow inline line breaks in log entries
     * @param bool   $ignoreEmptyContextAndExtra
     */
    public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false)
    {
        $this->format = $format ?: static::SIMPLE_FORMAT;
        $this->allowInlineLineBreaks = $allowInlineLineBreaks;
        $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
        parent::__construct($dateFormat);
    }

    public function includeStacktraces($include = true)
    {
        $this->includeStacktraces = $include;
        if ($this->includeStacktraces) {
            $this->allowInlineLineBreaks = true;
        }
    }

    public function allowInlineLineBreaks($allow = true)
    {
        $this->allowInlineLineBreaks = $allow;
    }

    public function ignoreEmptyContextAndExtra($ignore = true)
    {
        $this->ignoreEmptyContextAndExtra = $ignore;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $vars = parent::format($record);

        $output = $this->format;

        foreach ($vars['extra'] as $var => $val) {
            if (false !== strpos($output, '%extra.'.$var.'%')) {
                $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output);
                unset($vars['extra'][$var]);
            }
        }


        foreach ($vars['context'] as $var => $val) {
            if (false !== strpos($output, '%context.'.$var.'%')) {
                $output = str_replace('%context.'.$var.'%', $this->stringify($val), $output);
                unset($vars['context'][$var]);
            }
        }

        if ($this->ignoreEmptyContextAndExtra) {
            if (empty($vars['context'])) {
                unset($vars['context']);
                $output = str_replace('%context%', '', $output);
            }

            if (empty($vars['extra'])) {
                unset($vars['extra']);
                $output = str_replace('%extra%', '', $output);
            }
        }

        foreach ($vars as $var => $val) {
            if (false !== strpos($output, '%'.$var.'%')) {
                $output = str_replace('%'.$var.'%', $this->stringify($val), $output);
            }
        }

        // remove leftover %extra.xxx% and %context.xxx% if any
        if (false !== strpos($output, '%')) {
            $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output);
        }

        return $output;
    }

    public function formatBatch(array $records)
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }

        return $message;
    }

    public function stringify($value)
    {
        return $this->replaceNewlines($this->convertToString($value));
    }

    protected function normalizeException($e)
    {
        // TODO 2.0 only check for Throwable
        if (!$e instanceof \Exception && !$e instanceof \Throwable) {
            throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.Utils::getClass($e));
        }

        $previousText = '';
        if ($previous = $e->getPrevious()) {
            do {
                $previousText .= ', '.Utils::getClass($previous).'(code: '.$previous->getCode().'): '.$previous->getMessage().' at '.$previous->getFile().':'.$previous->getLine();
            } while ($previous = $previous->getPrevious());
        }

        $str = '[object] ('.Utils::getClass($e).'(code: '.$e->getCode().'): '.$e->getMessage().' at '.$e->getFile().':'.$e->getLine().$previousText.')';
        if ($this->includeStacktraces) {
            $str .= "\n[stacktrace]\n".$e->getTraceAsString()."\n";
        }

        return $str;
    }

    protected function convertToString($data)
    {
        if (null === $data || is_bool($data)) {
            return var_export($data, true);
        }

        if (is_scalar($data)) {
            return (string) $data;
        }

        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            return $this->toJson($data, true);
        }

        return str_replace('\\/', '/', $this->toJson($data, true));
    }

    protected function replaceNewlines($str)
    {
        if ($this->allowInlineLineBreaks) {
            if (0 === strpos($str, '{')) {
                return str_replace(array('\r', '\n'), array("\r", "\n"), $str);
            }

            return $str;
        }

        return str_replace(array("\r\n", "\r", "\n"), ' ', $str);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Exception;
use Monolog\Utils;
use Throwable;

/**
 * Encodes whatever record data is passed to it as json
 *
 * This can be useful to log to databases or remote APIs
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class JsonFormatter extends NormalizerFormatter
{
    const BATCH_MODE_JSON = 1;
    const BATCH_MODE_NEWLINES = 2;

    protected $batchMode;
    protected $appendNewline;

    /**
     * @var bool
     */
    protected $includeStacktraces = false;

    /**
     * @param int $batchMode
     * @param bool $appendNewline
     * @param int $maxDepth
     */
    public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true, $maxDepth = 9)
    {
        parent::__construct(null, $maxDepth);
        $this->batchMode = $batchMode;
        $this->appendNewline = $appendNewline;
    }

    /**
     * The batch mode option configures the formatting style for
     * multiple records. By default, multiple records will be
     * formatted as a JSON-encoded array. However, for
     * compatibility with some API endpoints, alternative styles
     * are available.
     *
     * @return int
     */
    public function getBatchMode()
    {
        return $this->batchMode;
    }

    /**
     * True if newlines are appended to every formatted record
     *
     * @return bool
     */
    public function isAppendingNewlines()
    {
        return $this->appendNewline;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        return $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : '');
    }

    /**
     * {@inheritdoc}
     */
    public function formatBatch(array $records)
    {
        switch ($this->batchMode) {
            case static::BATCH_MODE_NEWLINES:
                return $this->formatBatchNewlines($records);

            case static::BATCH_MODE_JSON:
            default:
                return $this->formatBatchJson($records);
        }
    }

    /**
     * @param bool $include
     */
    public function includeStacktraces($include = true)
    {
        $this->includeStacktraces = $include;
    }

    /**
     * Return a JSON-encoded array of records.
     *
     * @param  array  $records
     * @return string
     */
    protected function formatBatchJson(array $records)
    {
        return $this->toJson($this->normalize($records), true);
    }

    /**
     * Use new lines to separate records instead of a
     * JSON-encoded array.
     *
     * @param  array  $records
     * @return string
     */
    protected function formatBatchNewlines(array $records)
    {
        $instance = $this;

        $oldNewline = $this->appendNewline;
        $this->appendNewline = false;
        array_walk($records, function (&$value, $key) use ($instance) {
            $value = $instance->format($value);
        });
        $this->appendNewline = $oldNewline;

        return implode("\n", $records);
    }

    /**
     * Normalizes given $data.
     *
     * @param mixed $data
     *
     * @return mixed
     */
    protected function normalize($data, $depth = 0)
    {
        if ($depth > $this->maxDepth) {
            return 'Over '.$this->maxDepth.' levels deep, aborting normalization';
        }

        if (is_array($data)) {
            $normalized = array();

            $count = 1;
            foreach ($data as $key => $value) {
                if ($count++ > 1000) {
                    $normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization';
                    break;
                }

                $normalized[$key] = $this->normalize($value, $depth+1);
            }

            return $normalized;
        }

        if ($data instanceof Exception || $data instanceof Throwable) {
            return $this->normalizeException($data);
        }

        if (is_resource($data)) {
            return parent::normalize($data);
        }

        return $data;
    }

    /**
     * Normalizes given exception with or without its own stack trace based on
     * `includeStacktraces` property.
     *
     * @param Exception|Throwable $e
     *
     * @return array
     */
    protected function normalizeException($e)
    {
        // TODO 2.0 only check for Throwable
        if (!$e instanceof Exception && !$e instanceof Throwable) {
            throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.Utils::getClass($e));
        }

        $data = array(
            'class' => Utils::getClass($e),
            'message' => $e->getMessage(),
            'code' => (int) $e->getCode(),
            'file' => $e->getFile().':'.$e->getLine(),
        );

        if ($this->includeStacktraces) {
            $trace = $e->getTrace();
            foreach ($trace as $frame) {
                if (isset($frame['file'])) {
                    $data['trace'][] = $frame['file'].':'.$frame['line'];
                }
            }
        }

        if ($previous = $e->getPrevious()) {
            $data['previous'] = $this->normalizeException($previous);
        }

        return $data;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * formats the record to be used in the FlowdockHandler
 *
 * @author Dominik Liebler <liebler.dominik@gmail.com>
 */
class FlowdockFormatter implements FormatterInterface
{
    /**
     * @var string
     */
    private $source;

    /**
     * @var string
     */
    private $sourceEmail;

    /**
     * @param string $source
     * @param string $sourceEmail
     */
    public function __construct($source, $sourceEmail)
    {
        $this->source = $source;
        $this->sourceEmail = $sourceEmail;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $tags = array(
            '#logs',
            '#' . strtolower($record['level_name']),
            '#' . $record['channel'],
        );

        foreach ($record['extra'] as $value) {
            $tags[] = '#' . $value;
        }

        $subject = sprintf(
            'in %s: %s - %s',
            $this->source,
            $record['level_name'],
            $this->getShortMessage($record['message'])
        );

        $record['flowdock'] = array(
            'source' => $this->source,
            'from_address' => $this->sourceEmail,
            'subject' => $subject,
            'content' => $record['message'],
            'tags' => $tags,
            'project' => $this->source,
        );

        return $record;
    }

    /**
     * {@inheritdoc}
     */
    public function formatBatch(array $records)
    {
        $formatted = array();

        foreach ($records as $record) {
            $formatted[] = $this->format($record);
        }

        return $formatted;
    }

    /**
     * @param string $message
     *
     * @return string
     */
    public function getShortMessage($message)
    {
        static $hasMbString;

        if (null === $hasMbString) {
            $hasMbString = function_exists('mb_strlen');
        }

        $maxLength = 45;

        if ($hasMbString) {
            if (mb_strlen($message, 'UTF-8') > $maxLength) {
                $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
            }
        } else {
            if (strlen($message) > $maxLength) {
                $message = substr($message, 0, $maxLength - 4) . ' ...';
            }
        }

        return $message;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Interface for formatters
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
interface FormatterInterface
{
    /**
     * Formats a log record.
     *
     * @param  array $record A record to format
     * @return mixed The formatted record
     */
    public function format(array $record);

    /**
     * Formats a set of log records.
     *
     * @param  array $records A set of records to format
     * @return mixed The formatted set of records
     */
    public function formatBatch(array $records);
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Serializes a log message to Logstash Event Format
 *
 * @see http://logstash.net/
 * @see https://github.com/logstash/logstash/blob/master/lib/logstash/event.rb
 *
 * @author Tim Mower <timothy.mower@gmail.com>
 */
class LogstashFormatter extends NormalizerFormatter
{
    const V0 = 0;
    const V1 = 1;

    /**
     * @var string the name of the system for the Logstash log message, used to fill the @source field
     */
    protected $systemName;

    /**
     * @var string an application name for the Logstash log message, used to fill the @type field
     */
    protected $applicationName;

    /**
     * @var string a prefix for 'extra' fields from the Monolog record (optional)
     */
    protected $extraPrefix;

    /**
     * @var string a prefix for 'context' fields from the Monolog record (optional)
     */
    protected $contextPrefix;

    /**
     * @var int logstash format version to use
     */
    protected $version;

    /**
     * @param string $applicationName the application that sends the data, used as the "type" field of logstash
     * @param string $systemName      the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
     * @param string $extraPrefix     prefix for extra keys inside logstash "fields"
     * @param string $contextPrefix   prefix for context keys inside logstash "fields", defaults to ctxt_
     * @param int    $version         the logstash format version to use, defaults to 0
     */
    public function __construct($applicationName, $systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_', $version = self::V0)
    {
        // logstash requires a ISO 8601 format date with optional millisecond precision.
        parent::__construct('Y-m-d\TH:i:s.uP');

        $this->systemName = $systemName ?: gethostname();
        $this->applicationName = $applicationName;
        $this->extraPrefix = $extraPrefix;
        $this->contextPrefix = $contextPrefix;
        $this->version = $version;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $record = parent::format($record);

        if ($this->version === self::V1) {
            $message = $this->formatV1($record);
        } else {
            $message = $this->formatV0($record);
        }

        return $this->toJson($message) . "\n";
    }

    protected function formatV0(array $record)
    {
        if (empty($record['datetime'])) {
            $record['datetime'] = gmdate('c');
        }
        $message = array(
            '@timestamp' => $record['datetime'],
            '@source' => $this->systemName,
            '@fields' => array(),
        );
        if (isset($record['message'])) {
            $message['@message'] = $record['message'];
        }
        if (isset($record['channel'])) {
            $message['@tags'] = array($record['channel']);
            $message['@fields']['channel'] = $record['channel'];
        }
        if (isset($record['level'])) {
            $message['@fields']['level'] = $record['level'];
        }
        if ($this->applicationName) {
            $message['@type'] = $this->applicationName;
        }
        if (isset($record['extra']['server'])) {
            $message['@source_host'] = $record['extra']['server'];
        }
        if (isset($record['extra']['url'])) {
            $message['@source_path'] = $record['extra']['url'];
        }
        if (!empty($record['extra'])) {
            foreach ($record['extra'] as $key => $val) {
                $message['@fields'][$this->extraPrefix . $key] = $val;
            }
        }
        if (!empty($record['context'])) {
            foreach ($record['context'] as $key => $val) {
                $message['@fields'][$this->contextPrefix . $key] = $val;
            }
        }

        return $message;
    }

    protected function formatV1(array $record)
    {
        if (empty($record['datetime'])) {
            $record['datetime'] = gmdate('c');
        }
        $message = array(
            '@timestamp' => $record['datetime'],
            '@version' => 1,
            'host' => $this->systemName,
        );
        if (isset($record['message'])) {
            $message['message'] = $record['message'];
        }
        if (isset($record['channel'])) {
            $message['type'] = $record['channel'];
            $message['channel'] = $record['channel'];
        }
        if (isset($record['level_name'])) {
            $message['level'] = $record['level_name'];
        }
        if ($this->applicationName) {
            $message['type'] = $this->applicationName;
        }
        if (!empty($record['extra'])) {
            foreach ($record['extra'] as $key => $val) {
                $message[$this->extraPrefix . $key] = $val;
            }
        }
        if (!empty($record['context'])) {
            foreach ($record['context'] as $key => $val) {
                $message[$this->contextPrefix . $key] = $val;
            }
        }

        return $message;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Encodes message information into JSON in a format compatible with Loggly.
 *
 * @author Adam Pancutt <adam@pancutt.com>
 */
class LogglyFormatter extends JsonFormatter
{
    /**
     * Overrides the default batch mode to new lines for compatibility with the
     * Loggly bulk API.
     *
     * @param int $batchMode
     */
    public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false)
    {
        parent::__construct($batchMode, $appendNewline);
    }

    /**
     * Appends the 'timestamp' parameter for indexing by Loggly.
     *
     * @see https://www.loggly.com/docs/automated-parsing/#json
     * @see \Monolog\Formatter\JsonFormatter::format()
     */
    public function format(array $record)
    {
        if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
            $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");
            // TODO 2.0 unset the 'datetime' parameter, retained for BC
        }

        return parent::format($record);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

/**
 * Formats data into an associative array of scalar values.
 * Objects and arrays will be JSON encoded.
 *
 * @author Andrew Lawson <adlawson@gmail.com>
 */
class ScalarFormatter extends NormalizerFormatter
{
    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        foreach ($record as $key => $value) {
            $record[$key] = $this->normalizeValue($value);
        }

        return $record;
    }

    /**
     * @param  mixed $value
     * @return mixed
     */
    protected function normalizeValue($value)
    {
        $normalized = $this->normalize($value);

        if (is_array($normalized) || is_object($normalized)) {
            return $this->toJson($normalized, true);
        }

        return $normalized;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Utils;

/**
 * Formats a record for use with the MongoDBHandler.
 *
 * @author Florian Plattner <me@florianplattner.de>
 */
class MongoDBFormatter implements FormatterInterface
{
    private $exceptionTraceAsString;
    private $maxNestingLevel;

    /**
     * @param int  $maxNestingLevel        0 means infinite nesting, the $record itself is level 1, $record['context'] is 2
     * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings
     */
    public function __construct($maxNestingLevel = 3, $exceptionTraceAsString = true)
    {
        $this->maxNestingLevel = max($maxNestingLevel, 0);
        $this->exceptionTraceAsString = (bool) $exceptionTraceAsString;
    }

    /**
     * {@inheritDoc}
     */
    public function format(array $record)
    {
        return $this->formatArray($record);
    }

    /**
     * {@inheritDoc}
     */
    public function formatBatch(array $records)
    {
        foreach ($records as $key => $record) {
            $records[$key] = $this->format($record);
        }

        return $records;
    }

    protected function formatArray(array $record, $nestingLevel = 0)
    {
        if ($this->maxNestingLevel == 0 || $nestingLevel <= $this->maxNestingLevel) {
            foreach ($record as $name => $value) {
                if ($value instanceof \DateTime) {
                    $record[$name] = $this->formatDate($value, $nestingLevel + 1);
                } elseif ($value instanceof \Exception) {
                    $record[$name] = $this->formatException($value, $nestingLevel + 1);
                } elseif (is_array($value)) {
                    $record[$name] = $this->formatArray($value, $nestingLevel + 1);
                } elseif (is_object($value)) {
                    $record[$name] = $this->formatObject($value, $nestingLevel + 1);
                }
            }
        } else {
            $record = '[...]';
        }

        return $record;
    }

    protected function formatObject($value, $nestingLevel)
    {
        $objectVars = get_object_vars($value);
        $objectVars['class'] = Utils::getClass($value);

        return $this->formatArray($objectVars, $nestingLevel);
    }

    protected function formatException(\Exception $exception, $nestingLevel)
    {
        $formattedException = array(
            'class' => Utils::getClass($exception),
            'message' => $exception->getMessage(),
            'code' => (int) $exception->getCode(),
            'file' => $exception->getFile() . ':' . $exception->getLine(),
        );

        if ($this->exceptionTraceAsString === true) {
            $formattedException['trace'] = $exception->getTraceAsString();
        } else {
            $formattedException['trace'] = $exception->getTrace();
        }

        return $this->formatArray($formattedException, $nestingLevel);
    }

    protected function formatDate(\DateTime $value, $nestingLevel)
    {
        return new \MongoDate($value->getTimestamp());
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

/**
 * Formats a log message according to the ChromePHP array format
 *
 * @author Christophe Coevoet <stof@notk.org>
 */
class ChromePHPFormatter implements FormatterInterface
{
    /**
     * Translates Monolog log levels to Wildfire levels.
     */
    private $logLevels = array(
        Logger::DEBUG     => 'log',
        Logger::INFO      => 'info',
        Logger::NOTICE    => 'info',
        Logger::WARNING   => 'warn',
        Logger::ERROR     => 'error',
        Logger::CRITICAL  => 'error',
        Logger::ALERT     => 'error',
        Logger::EMERGENCY => 'error',
    );

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        // Retrieve the line and file if set and remove them from the formatted extra
        $backtrace = 'unknown';
        if (isset($record['extra']['file'], $record['extra']['line'])) {
            $backtrace = $record['extra']['file'].' : '.$record['extra']['line'];
            unset($record['extra']['file'], $record['extra']['line']);
        }

        $message = array('message' => $record['message']);
        if ($record['context']) {
            $message['context'] = $record['context'];
        }
        if ($record['extra']) {
            $message['extra'] = $record['extra'];
        }
        if (count($message) === 1) {
            $message = reset($message);
        }

        return array(
            $record['channel'],
            $message,
            $backtrace,
            $this->logLevels[$record['level']],
        );
    }

    public function formatBatch(array $records)
    {
        $formatted = array();

        foreach ($records as $record) {
            $formatted[] = $this->format($record);
        }

        return $formatted;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Utils;

/**
 * Class FluentdFormatter
 *
 * Serializes a log message to Fluentd unix socket protocol
 *
 * Fluentd config:
 *
 * <source>
 *  type unix
 *  path /var/run/td-agent/td-agent.sock
 * </source>
 *
 * Monolog setup:
 *
 * $logger = new Monolog\Logger('fluent.tag');
 * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock');
 * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter());
 * $logger->pushHandler($fluentHandler);
 *
 * @author Andrius Putna <fordnox@gmail.com>
 */
class FluentdFormatter implements FormatterInterface
{
    /**
     * @var bool $levelTag should message level be a part of the fluentd tag
     */
    protected $levelTag = false;

    public function __construct($levelTag = false)
    {
        if (!function_exists('json_encode')) {
            throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter');
        }

        $this->levelTag = (bool) $levelTag;
    }

    public function isUsingLevelsInTag()
    {
        return $this->levelTag;
    }

    public function format(array $record)
    {
        $tag = $record['channel'];
        if ($this->levelTag) {
            $tag .= '.' . strtolower($record['level_name']);
        }

        $message = array(
            'message' => $record['message'],
            'context' => $record['context'],
            'extra' => $record['extra'],
        );

        if (!$this->levelTag) {
            $message['level'] = $record['level'];
            $message['level_name'] = $record['level_name'];
        }

        return Utils::jsonEncode(array($tag, $record['datetime']->getTimestamp(), $message));
    }

    public function formatBatch(array $records)
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }

        return $message;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;
use Gelf\Message;

/**
 * Serializes a log message to GELF
 * @see http://www.graylog2.org/about/gelf
 *
 * @author Matt Lehner <mlehner@gmail.com>
 */
class GelfMessageFormatter extends NormalizerFormatter
{
    const DEFAULT_MAX_LENGTH = 32766;

    /**
     * @var string the name of the system for the Gelf log message
     */
    protected $systemName;

    /**
     * @var string a prefix for 'extra' fields from the Monolog record (optional)
     */
    protected $extraPrefix;

    /**
     * @var string a prefix for 'context' fields from the Monolog record (optional)
     */
    protected $contextPrefix;

    /**
     * @var int max length per field
     */
    protected $maxLength;

    /**
     * Translates Monolog log levels to Graylog2 log priorities.
     */
    private $logLevels = array(
        Logger::DEBUG     => 7,
        Logger::INFO      => 6,
        Logger::NOTICE    => 5,
        Logger::WARNING   => 4,
        Logger::ERROR     => 3,
        Logger::CRITICAL  => 2,
        Logger::ALERT     => 1,
        Logger::EMERGENCY => 0,
    );

    public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_', $maxLength = null)
    {
        parent::__construct('U.u');

        $this->systemName = $systemName ?: gethostname();

        $this->extraPrefix = $extraPrefix;
        $this->contextPrefix = $contextPrefix;
        $this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        $record = parent::format($record);

        if (!isset($record['datetime'], $record['message'], $record['level'])) {
            throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given');
        }

        $message = new Message();
        $message
            ->setTimestamp($record['datetime'])
            ->setShortMessage((string) $record['message'])
            ->setHost($this->systemName)
            ->setLevel($this->logLevels[$record['level']]);

        // message length + system name length + 200 for padding / metadata 
        $len = 200 + strlen((string) $record['message']) + strlen($this->systemName);

        if ($len > $this->maxLength) {
            $message->setShortMessage(substr($record['message'], 0, $this->maxLength));
        }

        if (isset($record['channel'])) {
            $message->setFacility($record['channel']);
        }
        if (isset($record['extra']['line'])) {
            $message->setLine($record['extra']['line']);
            unset($record['extra']['line']);
        }
        if (isset($record['extra']['file'])) {
            $message->setFile($record['extra']['file']);
            unset($record['extra']['file']);
        }

        foreach ($record['extra'] as $key => $val) {
            $val = is_scalar($val) || null === $val ? $val : $this->toJson($val);
            $len = strlen($this->extraPrefix . $key . $val);
            if ($len > $this->maxLength) {
                $message->setAdditional($this->extraPrefix . $key, substr($val, 0, $this->maxLength));
                break;
            }
            $message->setAdditional($this->extraPrefix . $key, $val);
        }

        foreach ($record['context'] as $key => $val) {
            $val = is_scalar($val) || null === $val ? $val : $this->toJson($val);
            $len = strlen($this->contextPrefix . $key . $val);
            if ($len > $this->maxLength) {
                $message->setAdditional($this->contextPrefix . $key, substr($val, 0, $this->maxLength));
                break;
            }
            $message->setAdditional($this->contextPrefix . $key, $val);
        }

        if (null === $message->getFile() && isset($record['context']['exception']['file'])) {
            if (preg_match("/^(.+):([0-9]+)$/", $record['context']['exception']['file'], $matches)) {
                $message->setFile($matches[1]);
                $message->setLine($matches[2]);
            }
        }

        return $message;
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;

/**
 * Serializes a log message according to Wildfire's header requirements
 *
 * @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com>
 * @author Christophe Coevoet <stof@notk.org>
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class WildfireFormatter extends NormalizerFormatter
{
    const TABLE = 'table';

    /**
     * Translates Monolog log levels to Wildfire levels.
     */
    private $logLevels = array(
        Logger::DEBUG     => 'LOG',
        Logger::INFO      => 'INFO',
        Logger::NOTICE    => 'INFO',
        Logger::WARNING   => 'WARN',
        Logger::ERROR     => 'ERROR',
        Logger::CRITICAL  => 'ERROR',
        Logger::ALERT     => 'ERROR',
        Logger::EMERGENCY => 'ERROR',
    );

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        // Retrieve the line and file if set and remove them from the formatted extra
        $file = $line = '';
        if (isset($record['extra']['file'])) {
            $file = $record['extra']['file'];
            unset($record['extra']['file']);
        }
        if (isset($record['extra']['line'])) {
            $line = $record['extra']['line'];
            unset($record['extra']['line']);
        }

        $record = $this->normalize($record);
        $message = array('message' => $record['message']);
        $handleError = false;
        if ($record['context']) {
            $message['context'] = $record['context'];
            $handleError = true;
        }
        if ($record['extra']) {
            $message['extra'] = $record['extra'];
            $handleError = true;
        }
        if (count($message) === 1) {
            $message = reset($message);
        }

        if (isset($record['context'][self::TABLE])) {
            $type  = 'TABLE';
            $label = $record['channel'] .': '. $record['message'];
            $message = $record['context'][self::TABLE];
        } else {
            $type  = $this->logLevels[$record['level']];
            $label = $record['channel'];
        }

        // Create JSON object describing the appearance of the message in the console
        $json = $this->toJson(array(
            array(
                'Type'  => $type,
                'File'  => $file,
                'Line'  => $line,
                'Label' => $label,
            ),
            $message,
        ), $handleError);

        // The message itself is a serialization of the above JSON object + it's length
        return sprintf(
            '%s|%s|',
            strlen($json),
            $json
        );
    }

    public function formatBatch(array $records)
    {
        throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter');
    }

    protected function normalize($data, $depth = 0)
    {
        if (is_object($data) && !$data instanceof \DateTime) {
            return $data;
        }

        return parent::normalize($data, $depth);
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Exception;
use Monolog\Utils;

/**
 * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class NormalizerFormatter implements FormatterInterface
{
    const SIMPLE_DATE = "Y-m-d H:i:s";

    protected $dateFormat;
    protected $maxDepth;

    /**
     * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
     * @param int $maxDepth
     */
    public function __construct($dateFormat = null, $maxDepth = 9)
    {
        $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
        $this->maxDepth = $maxDepth;
        if (!function_exists('json_encode')) {
            throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $record)
    {
        return $this->normalize($record);
    }

    /**
     * {@inheritdoc}
     */
    public function formatBatch(array $records)
    {
        foreach ($records as $key => $record) {
            $records[$key] = $this->format($record);
        }

        return $records;
    }

    /**
     * @return int
     */
    public function getMaxDepth()
    {
        return $this->maxDepth;
    }

    /**
     * @param int $maxDepth
     */
    public function setMaxDepth($maxDepth)
    {
        $this->maxDepth = $maxDepth;
    }

    protected function normalize($data, $depth = 0)
    {
        if ($depth > $this->maxDepth) {
            return 'Over '.$this->maxDepth.' levels deep, aborting normalization';
        }

        if (null === $data || is_scalar($data)) {
            if (is_float($data)) {
                if (is_infinite($data)) {
                    return ($data > 0 ? '' : '-') . 'INF';
                }
                if (is_nan($data)) {
                    return 'NaN';
                }
            }

            return $data;
        }

        if (is_array($data)) {
            $normalized = array();

            $count = 1;
            foreach ($data as $key => $value) {
                if ($count++ > 1000) {
                    $normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization';
                    break;
                }

                $normalized[$key] = $this->normalize($value, $depth+1);
            }

            return $normalized;
        }

        if ($data instanceof \DateTime) {
            return $data->format($this->dateFormat);
        }

        if (is_object($data)) {
            // TODO 2.0 only check for Throwable
            if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) {
                return $this->normalizeException($data);
            }

            // non-serializable objects that implement __toString stringified
            if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) {
                $value = $data->__toString();
            } else {
                // the rest is json-serialized in some way
                $value = $this->toJson($data, true);
            }

            return sprintf("[object] (%s: %s)", Utils::getClass($data), $value);
        }

        if (is_resource($data)) {
            return sprintf('[resource] (%s)', get_resource_type($data));
        }

        return '[unknown('.gettype($data).')]';
    }

    protected function normalizeException($e)
    {
        // TODO 2.0 only check for Throwable
        if (!$e instanceof Exception && !$e instanceof \Throwable) {
            throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.Utils::getClass($e));
        }

        $data = array(
            'class' => Utils::getClass($e),
            'message' => $e->getMessage(),
            'code' => (int) $e->getCode(),
            'file' => $e->getFile().':'.$e->getLine(),
        );

        if ($e instanceof \SoapFault) {
            if (isset($e->faultcode)) {
                $data['faultcode'] = $e->faultcode;
            }

            if (isset($e->faultactor)) {
                $data['faultactor'] = $e->faultactor;
            }

            if (isset($e->detail)) {
                if  (is_string($e->detail)) {
                    $data['detail'] = $e->detail;
                } elseif (is_object($e->detail) || is_array($e->detail)) {
                    $data['detail'] = $this->toJson($e->detail, true);
                }
            }
        }

        $trace = $e->getTrace();
        foreach ($trace as $frame) {
            if (isset($frame['file'])) {
                $data['trace'][] = $frame['file'].':'.$frame['line'];
            }
        }

        if ($previous = $e->getPrevious()) {
            $data['previous'] = $this->normalizeException($previous);
        }

        return $data;
    }

    /**
     * Return the JSON representation of a value
     *
     * @param  mixed             $data
     * @param  bool              $ignoreErrors
     * @throws \RuntimeException if encoding fails and errors are not ignored
     * @return string
     */
    protected function toJson($data, $ignoreErrors = false)
    {
        return Utils::jsonEncode($data, null, $ignoreErrors);
    }
}<?php
/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Formatter;

use Monolog\Logger;
use Monolog\Utils;

/**
 * Formats incoming records into an HTML table
 *
 * This is especially useful for html email logging
 *
 * @author Tiago Brito <tlfbrito@gmail.com>
 */
class HtmlFormatter extends NormalizerFormatter
{
    /**
     * Translates Monolog log levels to html color priorities.
     */
    protected $logLevels = array(
        Logger::DEBUG     => '#cccccc',
        Logger::INFO      => '#468847',
        Logger::NOTICE    => '#3a87ad',
        Logger::WARNING   => '#c09853',
        Logger::ERROR     => '#f0ad4e',
        Logger::CRITICAL  => '#FF7708',
        Logger::ALERT     => '#C12A19',
        Logger::EMERGENCY => '#000000',
    );

    /**
     * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
     */
    public function __construct($dateFormat = null)
    {
        parent::__construct($dateFormat);
    }

    /**
     * Creates an HTML table row
     *
     * @param  string $th       Row header content
     * @param  string $td       Row standard cell content
     * @param  bool   $escapeTd false if td content must not be html escaped
     * @return string
     */
    protected function addRow($th, $td = ' ', $escapeTd = true)
    {
        $th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
        if ($escapeTd) {
            $td = '<pre>'.htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8').'</pre>';
        }

        return "<tr style=\"padding: 4px;text-align: left;\">\n<th style=\"vertical-align: top;background: #ccc;color: #000\" width=\"100\">$th:</th>\n<td style=\"padding: 4px;text-align: left;vertical-align: top;background: #eee;color: #000\">".$td."</td>\n</tr>";
    }

    /**
     * Create a HTML h1 tag
     *
     * @param  string $title Text to be in the h1
     * @param  int    $level Error level
     * @return string
     */
    protected function addTitle($title, $level)
    {
        $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');

        return '<h1 style="background: '.$this->logLevels[$level].';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>';
    }

    /**
     * Formats a log record.
     *
     * @param  array $record A record to format
     * @return mixed The formatted record
     */
    public function format(array $record)
    {
        $output = $this->addTitle($record['level_name'], $record['level']);
        $output .= '<table cellspacing="1" width="100%" class="monolog-output">';

        $output .= $this->addRow('Message', (string) $record['message']);
        $output .= $this->addRow('Time', $record['datetime']->format($this->dateFormat));
        $output .= $this->addRow('Channel', $record['channel']);
        if ($record['context']) {
            $embeddedTable = '<table cellspacing="1" width="100%">';
            foreach ($record['context'] as $key => $value) {
                $embeddedTable .= $this->addRow($key, $this->convertToString($value));
            }
            $embeddedTable .= '</table>';
            $output .= $this->addRow('Context', $embeddedTable, false);
        }
        if ($record['extra']) {
            $embeddedTable = '<table cellspacing="1" width="100%">';
            foreach ($record['extra'] as $key => $value) {
                $embeddedTable .= $this->addRow($key, $this->convertToString($value));
            }
            $embeddedTable .= '</table>';
            $output .= $this->addRow('Extra', $embeddedTable, false);
        }

        return $output.'</table>';
    }

    /**
     * Formats a set of log records.
     *
     * @param  array $records A set of records to format
     * @return mixed The formatted set of records
     */
    public function formatBatch(array $records)
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }

        return $message;
    }

    protected function convertToString($data)
    {
        if (null === $data || is_scalar($data)) {
            return (string) $data;
        }

        $data = $this->normalize($data);
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            return Utils::jsonEncode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, true);
        }

        return str_replace('\\/', '/', Utils::jsonEncode($data, null, true));
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Monolog\Handler\AbstractHandler;

/**
 * Monolog error handler
 *
 * A facility to enable logging of runtime errors, exceptions and fatal errors.
 *
 * Quick setup: <code>ErrorHandler::register($logger);</code>
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class ErrorHandler
{
    private $logger;

    private $previousExceptionHandler;
    private $uncaughtExceptionLevel;

    private $previousErrorHandler;
    private $errorLevelMap;
    private $handleOnlyReportedErrors;

    private $hasFatalErrorHandler;
    private $fatalLevel;
    private $reservedMemory;
    private $lastFatalTrace;
    private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Registers a new ErrorHandler for a given Logger
     *
     * By default it will handle errors, exceptions and fatal errors
     *
     * @param  LoggerInterface $logger
     * @param  array|false     $errorLevelMap  an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
     * @param  int|false       $exceptionLevel a LogLevel::* constant, or false to disable exception handling
     * @param  int|false       $fatalLevel     a LogLevel::* constant, or false to disable fatal error handling
     * @return ErrorHandler
     */
    public static function register(LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevel = null, $fatalLevel = null)
    {
        //Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929
        class_exists('\\Psr\\Log\\LogLevel', true);

        /** @phpstan-ignore-next-line */
        $handler = new static($logger);
        if ($errorLevelMap !== false) {
            $handler->registerErrorHandler($errorLevelMap);
        }
        if ($exceptionLevel !== false) {
            $handler->registerExceptionHandler($exceptionLevel);
        }
        if ($fatalLevel !== false) {
            $handler->registerFatalHandler($fatalLevel);
        }

        return $handler;
    }

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }

        $this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
        $this->hasFatalErrorHandler = true;
    }

    protected function defaultErrorLevelMap()
    {
        return array(
            E_ERROR             => LogLevel::CRITICAL,
            E_WARNING           => LogLevel::WARNING,
            E_PARSE             => LogLevel::ALERT,
            E_NOTICE            => LogLevel::NOTICE,
            E_CORE_ERROR        => LogLevel::CRITICAL,
            E_CORE_WARNING      => LogLevel::WARNING,
            E_COMPILE_ERROR     => LogLevel::ALERT,
            E_COMPILE_WARNING   => LogLevel::WARNING,
            E_USER_ERROR        => LogLevel::ERROR,
            E_USER_WARNING      => LogLevel::WARNING,
            E_USER_NOTICE       => LogLevel::NOTICE,
            E_STRICT            => LogLevel::NOTICE,
            E_RECOVERABLE_ERROR => LogLevel::ERROR,
            E_DEPRECATED        => LogLevel::NOTICE,
            E_USER_DEPRECATED   => LogLevel::NOTICE,
        );
    }

    /**
     * @private
     */
    public function handleException($e)
    {
        $this->logger->log(
            $this->uncaughtExceptionLevel === null ? LogLevel::ERROR : $this->uncaughtExceptionLevel,
            sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()),
            array('exception' => $e)
        );

        if ($this->previousExceptionHandler) {
            call_user_func($this->previousExceptionHandler, $e);
        }

        exit(255);
    }

    /**
     * @private
     */
    public function handleError($code, $message, $file = '', $line = 0, $context = array())
    {
        if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) {
            return;
        }

        // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
        if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) {
            $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL;
            $this->logger->log($level, self::codeToString($code).': '.$message, array('code' => $code, 'message' => $message, 'file' => $file, 'line' => $line));
        } else {
            // http://php.net/manual/en/function.debug-backtrace.php
            // As of 5.3.6, DEBUG_BACKTRACE_IGNORE_ARGS option was added.
            // Any version less than 5.3.6 must use the DEBUG_BACKTRACE_IGNORE_ARGS constant value '2'.
            $trace = debug_backtrace((PHP_VERSION_ID < 50306) ? 2 : DEBUG_BACKTRACE_IGNORE_ARGS);
            array_shift($trace); // Exclude handleError from trace
            $this->lastFatalTrace = $trace;
        }

        if ($this->previousErrorHandler === true) {
            return false;
        } elseif ($this->previousErrorHandler) {
            return call_user_func($this->previousErrorHandler, $code, $message, $file, $line, $context);
        }
    }

    /**
     * @private
     */
    public function handleFatalError()
    {
        $this->reservedMemory = null;

        $lastError = error_get_last();
        if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) {
            $this->logger->log(
                $this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel,
                'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
                array('code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $this->lastFatalTrace)
            );

            if ($this->logger instanceof Logger) {
                foreach ($this->logger->getHandlers() as $handler) {
                    if ($handler instanceof AbstractHandler) {
                        $handler->close();
                    }
                }
            }
        }
    }

    private static function codeToString($code)
    {
        switch ($code) {
            case E_ERROR:
                return 'E_ERROR';
            case E_WARNING:
                return 'E_WARNING';
            case E_PARSE:
                return 'E_PARSE';
            case E_NOTICE:
                return 'E_NOTICE';
            case E_CORE_ERROR:
                return 'E_CORE_ERROR';
            case E_CORE_WARNING:
                return 'E_CORE_WARNING';
            case E_COMPILE_ERROR:
                return 'E_COMPILE_ERROR';
            case E_COMPILE_WARNING:
                return 'E_COMPILE_WARNING';
            case E_USER_ERROR:
                return 'E_USER_ERROR';
            case E_USER_WARNING:
                return 'E_USER_WARNING';
            case E_USER_NOTICE:
                return 'E_USER_NOTICE';
            case E_STRICT:
                return 'E_STRICT';
            case E_RECOVERABLE_ERROR:
                return 'E_RECOVERABLE_ERROR';
            case E_DEPRECATED:
                return 'E_DEPRECATED';
            case E_USER_DEPRECATED:
                return 'E_USER_DEPRECATED';
        }

        return 'Unknown PHP error';
    }
}
<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog;

class Utils
{
    /**
     * @internal
     */
    public static function getClass($object)
    {
        $class = \get_class($object);

        return 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;
    }

    /**
     * Makes sure if a relative path is passed in it is turned into an absolute path
     *
     * @param string $streamUrl stream URL or path without protocol
     *
     * @return string
     */
    public static function canonicalizePath($streamUrl)
    {
        $prefix = '';
        if ('file://' === substr($streamUrl, 0, 7)) {
            $streamUrl = substr($streamUrl, 7);
            $prefix = 'file://';
        }

        // other type of stream, not supported
        if (false !== strpos($streamUrl, '://')) {
            return $streamUrl;
        }

        // already absolute
        if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') {
            return $prefix.$streamUrl;
        }

        $streamUrl = getcwd() . '/' . $streamUrl;

        return $prefix.$streamUrl;
    }

    /**
     * Return the JSON representation of a value
     *
     * @param  mixed             $data
     * @param  int               $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
     * @param  bool              $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null
     * @throws \RuntimeException if encoding fails and errors are not ignored
     * @return string
     */
    public static function jsonEncode($data, $encodeFlags = null, $ignoreErrors = false)
    {
        if (null === $encodeFlags && version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $encodeFlags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
        }

        if ($ignoreErrors) {
            $json = @json_encode($data, $encodeFlags);
            if (false === $json) {
                return 'null';
            }

            return $json;
        }

        $json = json_encode($data, $encodeFlags);
        if (false === $json) {
            $json = self::handleJsonError(json_last_error(), $data);
        }

        return $json;
    }

    /**
     * Handle a json_encode failure.
     *
     * If the failure is due to invalid string encoding, try to clean the
     * input and encode again. If the second encoding attempt fails, the
     * inital error is not encoding related or the input can't be cleaned then
     * raise a descriptive exception.
     *
     * @param  int               $code return code of json_last_error function
     * @param  mixed             $data data that was meant to be encoded
     * @param  int               $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
     * @throws \RuntimeException if failure can't be corrected
     * @return string            JSON encoded data after error correction
     */
    public static function handleJsonError($code, $data, $encodeFlags = null)
    {
        if ($code !== JSON_ERROR_UTF8) {
            self::throwEncodeError($code, $data);
        }

        if (is_string($data)) {
            self::detectAndCleanUtf8($data);
        } elseif (is_array($data)) {
            array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8'));
        } else {
            self::throwEncodeError($code, $data);
        }

        if (null === $encodeFlags && version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $encodeFlags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
        }

        $json = json_encode($data, $encodeFlags);

        if ($json === false) {
            self::throwEncodeError(json_last_error(), $data);
        }

        return $json;
    }

    /**
     * Throws an exception according to a given code with a customized message
     *
     * @param  int               $code return code of json_last_error function
     * @param  mixed             $data data that was meant to be encoded
     * @throws \RuntimeException
     */
    private static function throwEncodeError($code, $data)
    {
        switch ($code) {
            case JSON_ERROR_DEPTH:
                $msg = 'Maximum stack depth exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $msg = 'Underflow or the modes mismatch';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $msg = 'Unexpected control character found';
                break;
            case JSON_ERROR_UTF8:
                $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
            default:
                $msg = 'Unknown error';
        }

        throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
    }

    /**
     * Detect invalid UTF-8 string characters and convert to valid UTF-8.
     *
     * Valid UTF-8 input will be left unmodified, but strings containing
     * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
     * original encoding of ISO-8859-15. This conversion may result in
     * incorrect output if the actual encoding was not ISO-8859-15, but it
     * will be clean UTF-8 output and will not rely on expensive and fragile
     * detection algorithms.
     *
     * Function converts the input in place in the passed variable so that it
     * can be used as a callback for array_walk_recursive.
     *
     * @param mixed $data Input to check and convert if needed, passed by ref
     * @private
     */
    public static function detectAndCleanUtf8(&$data)
    {
        if (is_string($data) && !preg_match('//u', $data)) {
            $data = preg_replace_callback(
                '/[\x80-\xFF]+/',
                function ($m) { return utf8_encode($m[0]); },
                $data
            );
            $data = str_replace(
                array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
                array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
                $data
            );
        }
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * The EventDispatcherInterface is the central point of Symfony's event listener system.
 * Listeners are registered on the manager and events are dispatched through the
 * manager.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface EventDispatcherInterface
{
    /**
     * Dispatches an event to all registered listeners.
     *
     * @param string $eventName The name of the event to dispatch. The name of
     *                          the event is the name of the method that is
     *                          invoked on listeners.
     * @param Event  $event     The event to pass to the event handlers/listeners
     *                          If not supplied, an empty Event instance is created
     *
     * @return Event
     */
    public function dispatch($eventName, Event $event = null);

    /**
     * Adds an event listener that listens on the specified events.
     *
     * @param string   $eventName The event to listen on
     * @param callable $listener  The listener
     * @param int      $priority  The higher this value, the earlier an event
     *                            listener will be triggered in the chain (defaults to 0)
     */
    public function addListener($eventName, $listener, $priority = 0);

    /**
     * Adds an event subscriber.
     *
     * The subscriber is asked for all the events he is
     * interested in and added as a listener for these events.
     */
    public function addSubscriber(EventSubscriberInterface $subscriber);

    /**
     * Removes an event listener from the specified events.
     *
     * @param string   $eventName The event to remove a listener from
     * @param callable $listener  The listener to remove
     */
    public function removeListener($eventName, $listener);

    public function removeSubscriber(EventSubscriberInterface $subscriber);

    /**
     * Gets the listeners of a specific event or all listeners sorted by descending priority.
     *
     * @param string $eventName The name of the event
     *
     * @return array The event listeners for the specified event, or all event listeners by event name
     */
    public function getListeners($eventName = null);

    /**
     * Checks whether an event has any registered listeners.
     *
     * @param string $eventName The name of the event
     *
     * @return bool true if the specified event has any listeners, false otherwise
     */
    public function hasListeners($eventName = null);
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * Event is the base class for classes containing event data.
 *
 * This class contains no event data. It is used by events that do not pass
 * state information to an event handler when an event is raised.
 *
 * You can call the method stopPropagation() to abort the execution of
 * further listeners in your event listener.
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class Event
{
    /**
     * @var bool Whether no further event listeners should be triggered
     */
    private $propagationStopped = false;

    /**
     * @var EventDispatcherInterface Dispatcher that dispatched this event
     */
    private $dispatcher;

    /**
     * @var string This event's name
     */
    private $name;

    /**
     * Returns whether further event listeners should be triggered.
     *
     * @see Event::stopPropagation()
     *
     * @return bool Whether propagation was already stopped for this event
     */
    public function isPropagationStopped()
    {
        return $this->propagationStopped;
    }

    /**
     * Stops the propagation of the event to further event listeners.
     *
     * If multiple event listeners are connected to the same event, no
     * further event listener will be triggered once any trigger calls
     * stopPropagation().
     */
    public function stopPropagation()
    {
        $this->propagationStopped = true;
    }

    /**
     * Stores the EventDispatcher that dispatches this Event.
     *
     * @param EventDispatcherInterface $dispatcher
     *
     * @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
     */
    public function setDispatcher(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * Returns the EventDispatcher that dispatches this Event.
     *
     * @return EventDispatcherInterface
     *
     * @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
     */
    public function getDispatcher()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event dispatcher instance can be received in the listener call instead.', E_USER_DEPRECATED);

        return $this->dispatcher;
    }

    /**
     * Gets the event's name.
     *
     * @return string
     *
     * @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call.
     */
    public function getName()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event name can be received in the listener call instead.', E_USER_DEPRECATED);

        return $this->name;
    }

    /**
     * Sets the event's name property.
     *
     * @param string $name The event name
     *
     * @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call.
     */
    public function setName($name)
    {
        $this->name = $name;
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Lazily loads listeners and subscribers from the dependency injection
 * container.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bernhard Schussek <bschussek@gmail.com>
 * @author Jordan Alliot <jordan.alliot@gmail.com>
 */
class ContainerAwareEventDispatcher extends EventDispatcher
{
    private $container;

    /**
     * The service IDs of the event listeners and subscribers.
     */
    private $listenerIds = array();

    /**
     * The services registered as listeners.
     */
    private $listeners = array();

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Adds a service as event listener.
     *
     * @param string $eventName Event for which the listener is added
     * @param array  $callback  The service ID of the listener service & the method
     *                          name that has to be called
     * @param int    $priority  The higher this value, the earlier an event listener
     *                          will be triggered in the chain.
     *                          Defaults to 0.
     *
     * @throws \InvalidArgumentException
     */
    public function addListenerService($eventName, $callback, $priority = 0)
    {
        if (!\is_array($callback) || 2 !== \count($callback)) {
            throw new \InvalidArgumentException('Expected an array("service", "method") argument');
        }

        $this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority);
    }

    public function removeListener($eventName, $listener)
    {
        $this->lazyLoad($eventName);

        if (isset($this->listenerIds[$eventName])) {
            foreach ($this->listenerIds[$eventName] as $i => $args) {
                list($serviceId, $method) = $args;
                $key = $serviceId.'.'.$method;
                if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) {
                    unset($this->listeners[$eventName][$key]);
                    if (empty($this->listeners[$eventName])) {
                        unset($this->listeners[$eventName]);
                    }
                    unset($this->listenerIds[$eventName][$i]);
                    if (empty($this->listenerIds[$eventName])) {
                        unset($this->listenerIds[$eventName]);
                    }
                }
            }
        }

        parent::removeListener($eventName, $listener);
    }

    /**
     * {@inheritdoc}
     */
    public function hasListeners($eventName = null)
    {
        if (null === $eventName) {
            return $this->listenerIds || $this->listeners || parent::hasListeners();
        }

        if (isset($this->listenerIds[$eventName])) {
            return true;
        }

        return parent::hasListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function getListeners($eventName = null)
    {
        if (null === $eventName) {
            foreach ($this->listenerIds as $serviceEventName => $args) {
                $this->lazyLoad($serviceEventName);
            }
        } else {
            $this->lazyLoad($eventName);
        }

        return parent::getListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function getListenerPriority($eventName, $listener)
    {
        $this->lazyLoad($eventName);

        return parent::getListenerPriority($eventName, $listener);
    }

    /**
     * Adds a service as event subscriber.
     *
     * @param string $serviceId The service ID of the subscriber service
     * @param string $class     The service's class name (which must implement EventSubscriberInterface)
     */
    public function addSubscriberService($serviceId, $class)
    {
        foreach ($class::getSubscribedEvents() as $eventName => $params) {
            if (\is_string($params)) {
                $this->listenerIds[$eventName][] = array($serviceId, $params, 0);
            } elseif (\is_string($params[0])) {
                $this->listenerIds[$eventName][] = array($serviceId, $params[0], isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

    public function getContainer()
    {
        return $this->container;
    }

    /**
     * Lazily loads listeners for this event from the dependency injection
     * container.
     *
     * @param string $eventName The name of the event to dispatch. The name of
     *                          the event is the name of the method that is
     *                          invoked on listeners.
     */
    protected function lazyLoad($eventName)
    {
        if (isset($this->listenerIds[$eventName])) {
            foreach ($this->listenerIds[$eventName] as $args) {
                list($serviceId, $method, $priority) = $args;
                $listener = $this->container->get($serviceId);

                $key = $serviceId.'.'.$method;
                if (!isset($this->listeners[$eventName][$key])) {
                    $this->addListener($eventName, array($listener, $method), $priority);
                } elseif ($this->listeners[$eventName][$key] !== $listener) {
                    parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method));
                    $this->addListener($eventName, array($listener, $method), $priority);
                }

                $this->listeners[$eventName][$key] = $listener;
            }
        }
    }
}
Copyright (c) 2004-2018 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
CHANGELOG
=========

2.5.0
-----

 * added Debug\TraceableEventDispatcher (originally in HttpKernel)
 * changed Debug\TraceableEventDispatcherInterface to extend EventDispatcherInterface
 * added RegisterListenersPass (originally in HttpKernel)

2.1.0
-----

 * added TraceableEventDispatcherInterface
 * added ContainerAwareEventDispatcher
 * added a reference to the EventDispatcher on the Event
 * added a reference to the Event name on the event
 * added fluid interface to the dispatch() method which now returns the Event
   object
 * added GenericEvent event class
 * added the possibility for subscribers to subscribe several times for the
   same event
 * added ImmutableEventDispatcher
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Test class for Event.
 */
class EventTest extends TestCase
{
    /**
     * @var \Symfony\Component\EventDispatcher\Event
     */
    protected $event;

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcher
     */
    protected $dispatcher;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->event = new Event();
        $this->dispatcher = new EventDispatcher();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
        $this->event = null;
        $this->dispatcher = null;
    }

    public function testIsPropagationStopped()
    {
        $this->assertFalse($this->event->isPropagationStopped());
    }

    public function testStopPropagationAndIsPropagationStopped()
    {
        $this->event->stopPropagation();
        $this->assertTrue($this->event->isPropagationStopped());
    }

    /**
     * @group legacy
     */
    public function testLegacySetDispatcher()
    {
        $this->event->setDispatcher($this->dispatcher);
        $this->assertSame($this->dispatcher, $this->event->getDispatcher());
    }

    /**
     * @group legacy
     */
    public function testLegacyGetDispatcher()
    {
        $this->assertNull($this->event->getDispatcher());
    }

    /**
     * @group legacy
     */
    public function testLegacyGetName()
    {
        $this->assertNull($this->event->getName());
    }

    /**
     * @group legacy
     */
    public function testLegacySetName()
    {
        $this->event->setName('foo');
        $this->assertEquals('foo', $this->event->getName());
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\EventDispatcher;

class EventDispatcherTest extends AbstractEventDispatcherTest
{
    protected function createEventDispatcher()
    {
        return new EventDispatcher();
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

abstract class AbstractEventDispatcherTest extends TestCase
{
    /* Some pseudo events */
    const preFoo = 'pre.foo';
    const postFoo = 'post.foo';
    const preBar = 'pre.bar';
    const postBar = 'post.bar';

    /**
     * @var EventDispatcher
     */
    private $dispatcher;

    private $listener;

    protected function setUp()
    {
        $this->dispatcher = $this->createEventDispatcher();
        $this->listener = new TestEventListener();
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->listener = null;
    }

    abstract protected function createEventDispatcher();

    public function testInitialState()
    {
        $this->assertEquals(array(), $this->dispatcher->getListeners());
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
        $this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testAddListener()
    {
        $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'));
        $this->assertTrue($this->dispatcher->hasListeners());
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
        $this->assertCount(1, $this->dispatcher->getListeners(self::preFoo));
        $this->assertCount(1, $this->dispatcher->getListeners(self::postFoo));
        $this->assertCount(2, $this->dispatcher->getListeners());
    }

    public function testGetListenersSortsByPriority()
    {
        $listener1 = new TestEventListener();
        $listener2 = new TestEventListener();
        $listener3 = new TestEventListener();
        $listener1->name = '1';
        $listener2->name = '2';
        $listener3->name = '3';

        $this->dispatcher->addListener('pre.foo', array($listener1, 'preFoo'), -10);
        $this->dispatcher->addListener('pre.foo', array($listener2, 'preFoo'), 10);
        $this->dispatcher->addListener('pre.foo', array($listener3, 'preFoo'));

        $expected = array(
            array($listener2, 'preFoo'),
            array($listener3, 'preFoo'),
            array($listener1, 'preFoo'),
        );

        $this->assertSame($expected, $this->dispatcher->getListeners('pre.foo'));
    }

    public function testGetAllListenersSortsByPriority()
    {
        $listener1 = new TestEventListener();
        $listener2 = new TestEventListener();
        $listener3 = new TestEventListener();
        $listener4 = new TestEventListener();
        $listener5 = new TestEventListener();
        $listener6 = new TestEventListener();

        $this->dispatcher->addListener('pre.foo', $listener1, -10);
        $this->dispatcher->addListener('pre.foo', $listener2);
        $this->dispatcher->addListener('pre.foo', $listener3, 10);
        $this->dispatcher->addListener('post.foo', $listener4, -10);
        $this->dispatcher->addListener('post.foo', $listener5);
        $this->dispatcher->addListener('post.foo', $listener6, 10);

        $expected = array(
            'pre.foo' => array($listener3, $listener2, $listener1),
            'post.foo' => array($listener6, $listener5, $listener4),
        );

        $this->assertSame($expected, $this->dispatcher->getListeners());
    }

    public function testGetListenerPriority()
    {
        $listener1 = new TestEventListener();
        $listener2 = new TestEventListener();

        $this->dispatcher->addListener('pre.foo', $listener1, -10);
        $this->dispatcher->addListener('pre.foo', $listener2);

        $this->assertSame(-10, $this->dispatcher->getListenerPriority('pre.foo', $listener1));
        $this->assertSame(0, $this->dispatcher->getListenerPriority('pre.foo', $listener2));
        $this->assertNull($this->dispatcher->getListenerPriority('pre.bar', $listener2));
        $this->assertNull($this->dispatcher->getListenerPriority('pre.foo', function () {}));
    }

    public function testDispatch()
    {
        $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'));
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertTrue($this->listener->preFooInvoked);
        $this->assertFalse($this->listener->postFooInvoked);
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch('noevent'));
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo));
        $event = new Event();
        $return = $this->dispatcher->dispatch(self::preFoo, $event);
        $this->assertSame($event, $return);
    }

    /**
     * @group legacy
     */
    public function testLegacyDispatch()
    {
        $event = new Event();
        $this->dispatcher->dispatch(self::preFoo, $event);
        $this->assertEquals('pre.foo', $event->getName());
    }

    public function testDispatchForClosure()
    {
        $invoked = 0;
        $listener = function () use (&$invoked) {
            ++$invoked;
        };
        $this->dispatcher->addListener('pre.foo', $listener);
        $this->dispatcher->addListener('post.foo', $listener);
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertEquals(1, $invoked);
    }

    public function testStopEventPropagation()
    {
        $otherListener = new TestEventListener();

        // postFoo() stops the propagation, so only one listener should
        // be executed
        // Manually set priority to enforce $this->listener to be called first
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'), 10);
        $this->dispatcher->addListener('post.foo', array($otherListener, 'postFoo'));
        $this->dispatcher->dispatch(self::postFoo);
        $this->assertTrue($this->listener->postFooInvoked);
        $this->assertFalse($otherListener->postFooInvoked);
    }

    public function testDispatchByPriority()
    {
        $invoked = array();
        $listener1 = function () use (&$invoked) {
            $invoked[] = '1';
        };
        $listener2 = function () use (&$invoked) {
            $invoked[] = '2';
        };
        $listener3 = function () use (&$invoked) {
            $invoked[] = '3';
        };
        $this->dispatcher->addListener('pre.foo', $listener1, -10);
        $this->dispatcher->addListener('pre.foo', $listener2);
        $this->dispatcher->addListener('pre.foo', $listener3, 10);
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertEquals(array('3', '2', '1'), $invoked);
    }

    public function testRemoveListener()
    {
        $this->dispatcher->addListener('pre.bar', $this->listener);
        $this->assertTrue($this->dispatcher->hasListeners(self::preBar));
        $this->dispatcher->removeListener('pre.bar', $this->listener);
        $this->assertFalse($this->dispatcher->hasListeners(self::preBar));
        $this->dispatcher->removeListener('notExists', $this->listener);
    }

    public function testAddSubscriber()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testAddSubscriberWithPriorities()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $eventSubscriber = new TestEventSubscriberWithPriorities();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $listeners = $this->dispatcher->getListeners('pre.foo');
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $listeners);
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]);
    }

    public function testAddSubscriberWithMultipleListeners()
    {
        $eventSubscriber = new TestEventSubscriberWithMultipleListeners();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $listeners = $this->dispatcher->getListeners('pre.foo');
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $listeners);
        $this->assertEquals('preFoo2', $listeners[0][1]);
    }

    public function testRemoveSubscriber()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
        $this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testRemoveSubscriberWithPriorities()
    {
        $eventSubscriber = new TestEventSubscriberWithPriorities();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
    }

    public function testRemoveSubscriberWithMultipleListeners()
    {
        $eventSubscriber = new TestEventSubscriberWithMultipleListeners();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $this->dispatcher->getListeners(self::preFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
    }

    /**
     * @group legacy
     */
    public function testLegacyEventReceivesTheDispatcherInstance()
    {
        $dispatcher = null;
        $this->dispatcher->addListener('test', function ($event) use (&$dispatcher) {
            $dispatcher = $event->getDispatcher();
        });
        $this->dispatcher->dispatch('test');
        $this->assertSame($this->dispatcher, $dispatcher);
    }

    public function testEventReceivesTheDispatcherInstanceAsArgument()
    {
        $listener = new TestWithDispatcher();
        $this->dispatcher->addListener('test', array($listener, 'foo'));
        $this->assertNull($listener->name);
        $this->assertNull($listener->dispatcher);
        $this->dispatcher->dispatch('test');
        $this->assertEquals('test', $listener->name);
        $this->assertSame($this->dispatcher, $listener->dispatcher);
    }

    /**
     * @see https://bugs.php.net/bug.php?id=62976
     *
     * This bug affects:
     *  - The PHP 5.3 branch for versions < 5.3.18
     *  - The PHP 5.4 branch for versions < 5.4.8
     *  - The PHP 5.5 branch is not affected
     */
    public function testWorkaroundForPhpBug62976()
    {
        $dispatcher = $this->createEventDispatcher();
        $dispatcher->addListener('bug.62976', new CallableClass());
        $dispatcher->removeListener('bug.62976', function () {});
        $this->assertTrue($dispatcher->hasListeners('bug.62976'));
    }

    public function testHasListenersWhenAddedCallbackListenerIsRemoved()
    {
        $listener = function () {};
        $this->dispatcher->addListener('foo', $listener);
        $this->dispatcher->removeListener('foo', $listener);
        $this->assertFalse($this->dispatcher->hasListeners());
    }

    public function testGetListenersWhenAddedCallbackListenerIsRemoved()
    {
        $listener = function () {};
        $this->dispatcher->addListener('foo', $listener);
        $this->dispatcher->removeListener('foo', $listener);
        $this->assertSame(array(), $this->dispatcher->getListeners());
    }

    public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEventHasBeenCalled()
    {
        $this->assertFalse($this->dispatcher->hasListeners('foo'));
        $this->assertFalse($this->dispatcher->hasListeners());
    }
}

class CallableClass
{
    public function __invoke()
    {
    }
}

class TestEventListener
{
    public $preFooInvoked = false;
    public $postFooInvoked = false;

    /* Listener methods */

    public function preFoo(Event $e)
    {
        $this->preFooInvoked = true;
    }

    public function postFoo(Event $e)
    {
        $this->postFooInvoked = true;

        $e->stopPropagation();
    }
}

class TestWithDispatcher
{
    public $name;
    public $dispatcher;

    public function foo(Event $e, $name, $dispatcher)
    {
        $this->name = $name;
        $this->dispatcher = $dispatcher;
    }
}

class TestEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('pre.foo' => 'preFoo', 'post.foo' => 'postFoo');
    }
}

class TestEventSubscriberWithPriorities implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'pre.foo' => array('preFoo', 10),
            'post.foo' => array('postFoo'),
        );
    }
}

class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('pre.foo' => array(
            array('preFoo1'),
            array('preFoo2', 10),
        ));
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * Test class for Event.
 */
class GenericEventTest extends TestCase
{
    /**
     * @var GenericEvent
     */
    private $event;

    private $subject;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        $this->subject = new \stdClass();
        $this->event = new GenericEvent($this->subject, array('name' => 'Event'));
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->subject = null;
        $this->event = null;
    }

    public function testConstruct()
    {
        $this->assertEquals($this->event, new GenericEvent($this->subject, array('name' => 'Event')));
    }

    /**
     * Tests Event->getArgs().
     */
    public function testGetArguments()
    {
        // test getting all
        $this->assertSame(array('name' => 'Event'), $this->event->getArguments());
    }

    public function testSetArguments()
    {
        $result = $this->event->setArguments(array('foo' => 'bar'));
        $this->assertAttributeSame(array('foo' => 'bar'), 'arguments', $this->event);
        $this->assertSame($this->event, $result);
    }

    public function testSetArgument()
    {
        $result = $this->event->setArgument('foo2', 'bar2');
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
        $this->assertEquals($this->event, $result);
    }

    public function testGetArgument()
    {
        // test getting key
        $this->assertEquals('Event', $this->event->getArgument('name'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetArgException()
    {
        $this->event->getArgument('nameNotExist');
    }

    public function testOffsetGet()
    {
        // test getting key
        $this->assertEquals('Event', $this->event['name']);

        // test getting invalid arg
        $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
        $this->assertFalse($this->event['nameNotExist']);
    }

    public function testOffsetSet()
    {
        $this->event['foo2'] = 'bar2';
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
    }

    public function testOffsetUnset()
    {
        unset($this->event['name']);
        $this->assertAttributeSame(array(), 'arguments', $this->event);
    }

    public function testOffsetIsset()
    {
        $this->assertArrayHasKey('name', $this->event);
        $this->assertArrayNotHasKey('nameNotExist', $this->event);
    }

    public function testHasArgument()
    {
        $this->assertTrue($this->event->hasArgument('name'));
        $this->assertFalse($this->event->hasArgument('nameNotExist'));
    }

    public function testGetSubject()
    {
        $this->assertSame($this->subject, $this->event->getSubject());
    }

    public function testHasIterator()
    {
        $data = array();
        foreach ($this->event as $key => $value) {
            $data[$key] = $value;
        }
        $this->assertEquals(array('name' => 'Event'), $data);
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
{
    protected function createEventDispatcher()
    {
        $container = new Container();

        return new ContainerAwareEventDispatcher($container);
    }

    public function testAddAListenerService()
    {
        $event = new Event();

        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->dispatch('onEvent', $event);
    }

    public function testAddASubscriberService()
    {
        $event = new Event();

        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\SubscriberService')->getMock();

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $service
            ->expects($this->once())
            ->method('onEventWithPriority')
            ->with($event)
        ;

        $service
            ->expects($this->once())
            ->method('onEventNested')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.subscriber', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addSubscriberService('service.subscriber', 'Symfony\Component\EventDispatcher\Tests\SubscriberService');

        $dispatcher->dispatch('onEvent', $event);
        $dispatcher->dispatch('onEventWithPriority', $event);
        $dispatcher->dispatch('onEventNested', $event);
    }

    public function testPreventDuplicateListenerService()
    {
        $event = new Event();

        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 5);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 10);

        $dispatcher->dispatch('onEvent', $event);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @group legacy
     */
    public function testTriggerAListenerServiceOutOfScope()
    {
        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $scope = new Scope('scope');
        $container = new Container();
        $container->addScope($scope);
        $container->enterScope('scope');

        $container->set('service.listener', $service, 'scope');

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $container->leaveScope('scope');
        $dispatcher->dispatch('onEvent');
    }

    /**
     * @group legacy
     */
    public function testReEnteringAScope()
    {
        $event = new Event();

        $service1 = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $service1
            ->expects($this->exactly(2))
            ->method('onEvent')
            ->with($event)
        ;

        $scope = new Scope('scope');
        $container = new Container();
        $container->addScope($scope);
        $container->enterScope('scope');

        $container->set('service.listener', $service1, 'scope');

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
        $dispatcher->dispatch('onEvent', $event);

        $service2 = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $service2
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container->enterScope('scope');
        $container->set('service.listener', $service2, 'scope');

        $dispatcher->dispatch('onEvent', $event);

        $container->leaveScope('scope');

        $dispatcher->dispatch('onEvent');
    }

    public function testHasListenersOnLazyLoad()
    {
        $event = new Event();

        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $event->setDispatcher($dispatcher);
        $event->setName('onEvent');

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $this->assertTrue($dispatcher->hasListeners());

        if ($dispatcher->hasListeners('onEvent')) {
            $dispatcher->dispatch('onEvent');
        }
    }

    public function testGetListenersOnLazyLoad()
    {
        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $listeners = $dispatcher->getListeners();

        $this->assertArrayHasKey('onEvent', $listeners);

        $this->assertCount(1, $dispatcher->getListeners('onEvent'));
    }

    public function testRemoveAfterDispatch()
    {
        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->dispatch('onEvent', new Event());
        $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent'));
        $this->assertFalse($dispatcher->hasListeners('onEvent'));
    }

    public function testRemoveBeforeDispatch()
    {
        $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent'));
        $this->assertFalse($dispatcher->hasListeners('onEvent'));
    }
}

class Service
{
    public function onEvent(Event $e)
    {
    }
}

class SubscriberService implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'onEvent' => 'onEvent',
            'onEventWithPriority' => array('onEventWithPriority', 10),
            'onEventNested' => array(array('onEventNested')),
        );
    }

    public function onEvent(Event $e)
    {
    }

    public function onEventWithPriority(Event $e)
    {
    }

    public function onEventNested(Event $e)
    {
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;

class RegisterListenersPassTest extends TestCase
{
    /**
     * Tests that event subscribers not implementing EventSubscriberInterface
     * trigger an exception.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testEventSubscriberWithoutInterface()
    {
        $builder = new ContainerBuilder();
        $builder->register('event_dispatcher');
        $builder->register('my_event_subscriber', 'stdClass')
            ->addTag('kernel.event_subscriber');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($builder);
    }

    public function testValidEventSubscriber()
    {
        $services = array(
            'my_event_subscriber' => array(0 => array()),
        );

        $builder = new ContainerBuilder();
        $eventDispatcherDefinition = $builder->register('event_dispatcher');
        $builder->register('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService')
            ->addTag('kernel.event_subscriber');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($builder);

        $this->assertEquals(array(array('addSubscriberService', array('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'))), $eventDispatcherDefinition->getMethodCalls());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded.
     */
    public function testPrivateEventListener()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded.
     */
    public function testPrivateEventSubscriber()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded.
     */
    public function testAbstractEventListener()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must not be abstract as event subscribers are lazy-loaded.
     */
    public function testAbstractEventSubscriber()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_subscriber', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    public function testEventSubscriberResolvableClassName()
    {
        $container = new ContainerBuilder();

        $container->setParameter('subscriber.class', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService');
        $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);

        $definition = $container->getDefinition('event_dispatcher');
        $expected_calls = array(
            array(
                'addSubscriberService',
                array(
                    'foo',
                    'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService',
                ),
            ),
        );
        $this->assertSame($expected_calls, $definition->getMethodCalls());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage You have requested a non-existent parameter "subscriber.class"
     */
    public function testEventSubscriberUnresolvableClassName()
    {
        $container = new ContainerBuilder();
        $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }
}

class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\ImmutableEventDispatcher;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ImmutableEventDispatcherTest extends TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $innerDispatcher;

    /**
     * @var ImmutableEventDispatcher
     */
    private $dispatcher;

    protected function setUp()
    {
        $this->innerDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
        $this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher);
    }

    public function testDispatchDelegates()
    {
        $event = new Event();

        $this->innerDispatcher->expects($this->once())
            ->method('dispatch')
            ->with('event', $event)
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->dispatch('event', $event));
    }

    public function testGetListenersDelegates()
    {
        $this->innerDispatcher->expects($this->once())
            ->method('getListeners')
            ->with('event')
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->getListeners('event'));
    }

    public function testHasListenersDelegates()
    {
        $this->innerDispatcher->expects($this->once())
            ->method('hasListeners')
            ->with('event')
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->hasListeners('event'));
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testAddListenerDisallowed()
    {
        $this->dispatcher->addListener('event', function () { return 'foo'; });
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testAddSubscriberDisallowed()
    {
        $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock();

        $this->dispatcher->addSubscriber($subscriber);
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testRemoveListenerDisallowed()
    {
        $this->dispatcher->removeListener('event', function () { return 'foo'; });
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testRemoveSubscriberDisallowed()
    {
        $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock();

        $this->dispatcher->removeSubscriber($subscriber);
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests\Debug;

use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\EventDispatcher\Debug\WrappedListener;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Stopwatch\Stopwatch;

class TraceableEventDispatcherTest extends TestCase
{
    public function testAddRemoveListener()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $tdispatcher->addListener('foo', $listener = function () {});
        $listeners = $dispatcher->getListeners('foo');
        $this->assertCount(1, $listeners);
        $this->assertSame($listener, $listeners[0]);

        $tdispatcher->removeListener('foo', $listener);
        $this->assertCount(0, $dispatcher->getListeners('foo'));
    }

    public function testGetListeners()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $tdispatcher->addListener('foo', $listener = function () {});
        $this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo'));
    }

    public function testHasListeners()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $this->assertFalse($dispatcher->hasListeners('foo'));
        $this->assertFalse($tdispatcher->hasListeners('foo'));

        $tdispatcher->addListener('foo', $listener = function () {});
        $this->assertTrue($dispatcher->hasListeners('foo'));
        $this->assertTrue($tdispatcher->hasListeners('foo'));
    }

    public function testGetListenerPriority()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $tdispatcher->addListener('foo', function () {}, 123);

        $listeners = $dispatcher->getListeners('foo');
        $this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0]));

        // Verify that priority is preserved when listener is removed and re-added
        // in preProcess() and postProcess().
        $tdispatcher->dispatch('foo', new Event());
        $listeners = $dispatcher->getListeners('foo');
        $this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0]));
    }

    public function testGetListenerPriorityReturnsZeroWhenWrappedMethodDoesNotExist()
    {
        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
        $traceableEventDispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
        $traceableEventDispatcher->addListener('foo', function () {}, 123);
        $listeners = $traceableEventDispatcher->getListeners('foo');

        $this->assertSame(0, $traceableEventDispatcher->getListenerPriority('foo', $listeners[0]));
    }

    public function testAddRemoveSubscriber()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $subscriber = new EventSubscriber();

        $tdispatcher->addSubscriber($subscriber);
        $listeners = $dispatcher->getListeners('foo');
        $this->assertCount(1, $listeners);
        $this->assertSame(array($subscriber, 'call'), $listeners[0]);

        $tdispatcher->removeSubscriber($subscriber);
        $this->assertCount(0, $dispatcher->getListeners('foo'));
    }

    /**
     * @dataProvider isWrappedDataProvider
     *
     * @param bool $isWrapped
     */
    public function testGetCalledListeners($isWrapped)
    {
        $dispatcher = new EventDispatcher();
        $stopWatch = new Stopwatch();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, $stopWatch);

        $listener = function () {};
        if ($isWrapped) {
            $listener = new WrappedListener($listener, 'foo', $stopWatch, $dispatcher);
        }

        $tdispatcher->addListener('foo', $listener, 5);

        $this->assertEquals(array(), $tdispatcher->getCalledListeners());
        $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure', 'priority' => 5)), $tdispatcher->getNotCalledListeners());

        $tdispatcher->dispatch('foo');

        $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure', 'priority' => 5)), $tdispatcher->getCalledListeners());
        $this->assertEquals(array(), $tdispatcher->getNotCalledListeners());
    }

    public function isWrappedDataProvider()
    {
        return array(
            array(false),
            array(true),
        );
    }

    public function testGetCalledListenersNested()
    {
        $tdispatcher = null;
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $dispatcher->addListener('foo', function (Event $event, $eventName, $dispatcher) use (&$tdispatcher) {
            $tdispatcher = $dispatcher;
            $dispatcher->dispatch('bar');
        });
        $dispatcher->addListener('bar', function (Event $event) {});
        $dispatcher->dispatch('foo');
        $this->assertSame($dispatcher, $tdispatcher);
        $this->assertCount(2, $dispatcher->getCalledListeners());
    }

    public function testLogger()
    {
        $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
        $tdispatcher->addListener('foo', $listener1 = function () {});
        $tdispatcher->addListener('foo', $listener2 = function () {});

        $logger->expects($this->at(0))->method('debug')->with('Notified event "foo" to listener "closure".');
        $logger->expects($this->at(1))->method('debug')->with('Notified event "foo" to listener "closure".');

        $tdispatcher->dispatch('foo');
    }

    public function testLoggerWithStoppedEvent()
    {
        $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
        $tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); });
        $tdispatcher->addListener('foo', $listener2 = function () {});

        $logger->expects($this->at(0))->method('debug')->with('Notified event "foo" to listener "closure".');
        $logger->expects($this->at(1))->method('debug')->with('Listener "closure" stopped propagation of the event "foo".');
        $logger->expects($this->at(2))->method('debug')->with('Listener "closure" was not called for event "foo".');

        $tdispatcher->dispatch('foo');
    }

    public function testDispatchCallListeners()
    {
        $called = array();

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
        $tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo1'; }, 10);
        $tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo2'; }, 20);

        $tdispatcher->dispatch('foo');

        $this->assertSame(array('foo2', 'foo1'), $called);
    }

    public function testDispatchNested()
    {
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $loop = 1;
        $dispatchedEvents = 0;
        $dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) {
            ++$loop;
            if (2 == $loop) {
                $dispatcher->dispatch('foo');
            }
        });
        $dispatcher->addListener('foo', function () use (&$dispatchedEvents) {
            ++$dispatchedEvents;
        });

        $dispatcher->dispatch('foo');

        $this->assertSame(2, $dispatchedEvents);
    }

    public function testDispatchReusedEventNested()
    {
        $nestedCall = false;
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $dispatcher->addListener('foo', function (Event $e) use ($dispatcher) {
            $dispatcher->dispatch('bar', $e);
        });
        $dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) {
            $nestedCall = true;
        });

        $this->assertFalse($nestedCall);
        $dispatcher->dispatch('foo');
        $this->assertTrue($nestedCall);
    }

    public function testListenerCanRemoveItselfWhenExecuted()
    {
        $eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $listener1 = function ($event, $eventName, EventDispatcherInterface $dispatcher) use (&$listener1) {
            $dispatcher->removeListener('foo', $listener1);
        };
        $eventDispatcher->addListener('foo', $listener1);
        $eventDispatcher->addListener('foo', function () {});
        $eventDispatcher->dispatch('foo');

        $this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed');
    }
}

class EventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('foo' => 'call');
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * The EventDispatcherInterface is the central point of Symfony's event listener system.
 *
 * Listeners are registered on the manager and events are dispatched through the
 * manager.
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Bernhard Schussek <bschussek@gmail.com>
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Jordan Alliot <jordan.alliot@gmail.com>
 */
class EventDispatcher implements EventDispatcherInterface
{
    private $listeners = array();
    private $sorted = array();

    /**
     * {@inheritdoc}
     */
    public function dispatch($eventName, Event $event = null)
    {
        if (null === $event) {
            $event = new Event();
        }

        $event->setDispatcher($this);
        $event->setName($eventName);

        if ($listeners = $this->getListeners($eventName)) {
            $this->doDispatch($listeners, $eventName, $event);
        }

        return $event;
    }

    /**
     * {@inheritdoc}
     */
    public function getListeners($eventName = null)
    {
        if (null !== $eventName) {
            if (!isset($this->listeners[$eventName])) {
                return array();
            }

            if (!isset($this->sorted[$eventName])) {
                $this->sortListeners($eventName);
            }

            return $this->sorted[$eventName];
        }

        foreach ($this->listeners as $eventName => $eventListeners) {
            if (!isset($this->sorted[$eventName])) {
                $this->sortListeners($eventName);
            }
        }

        return array_filter($this->sorted);
    }

    /**
     * Gets the listener priority for a specific event.
     *
     * Returns null if the event or the listener does not exist.
     *
     * @param string   $eventName The name of the event
     * @param callable $listener  The listener
     *
     * @return int|null The event listener priority
     */
    public function getListenerPriority($eventName, $listener)
    {
        if (!isset($this->listeners[$eventName])) {
            return;
        }

        foreach ($this->listeners[$eventName] as $priority => $listeners) {
            if (false !== \in_array($listener, $listeners, true)) {
                return $priority;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function hasListeners($eventName = null)
    {
        return (bool) $this->getListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function addListener($eventName, $listener, $priority = 0)
    {
        $this->listeners[$eventName][$priority][] = $listener;
        unset($this->sorted[$eventName]);
    }

    /**
     * {@inheritdoc}
     */
    public function removeListener($eventName, $listener)
    {
        if (!isset($this->listeners[$eventName])) {
            return;
        }

        foreach ($this->listeners[$eventName] as $priority => $listeners) {
            if (false !== ($key = array_search($listener, $listeners, true))) {
                unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (\is_string($params)) {
                $this->addListener($eventName, array($subscriber, $params));
            } elseif (\is_string($params[0])) {
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (\is_array($params) && \is_array($params[0])) {
                foreach ($params as $listener) {
                    $this->removeListener($eventName, array($subscriber, $listener[0]));
                }
            } else {
                $this->removeListener($eventName, array($subscriber, \is_string($params) ? $params : $params[0]));
            }
        }
    }

    /**
     * Triggers the listeners of an event.
     *
     * This method can be overridden to add functionality that is executed
     * for each listener.
     *
     * @param callable[] $listeners The event listeners
     * @param string     $eventName The name of the event to dispatch
     * @param Event      $event     The event object to pass to the event handlers/listeners
     */
    protected function doDispatch($listeners, $eventName, Event $event)
    {
        foreach ($listeners as $listener) {
            if ($event->isPropagationStopped()) {
                break;
            }
            \call_user_func($listener, $event, $eventName, $this);
        }
    }

    /**
     * Sorts the internal list of listeners for the given event by priority.
     *
     * @param string $eventName The name of the event
     */
    private function sortListeners($eventName)
    {
        krsort($this->listeners[$eventName]);
        $this->sorted[$eventName] = \call_user_func_array('array_merge', $this->listeners[$eventName]);
    }
}
EventDispatcher Component
=========================

The EventDispatcher component provides tools that allow your application
components to communicate with each other by dispatching events and listening to
them.

Resources
---------

  * [Documentation](https://symfony.com/doc/current/components/event_dispatcher/index.html)
  * [Contributing](https://symfony.com/doc/current/contributing/index.html)
  * [Report issues](https://github.com/symfony/symfony/issues) and
    [send Pull Requests](https://github.com/symfony/symfony/pulls)
    in the [main Symfony repository](https://github.com/symfony/symfony)
vendor/
composer.lock
phpunit.xml
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * An EventSubscriber knows himself what events he is interested in.
 * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes
 * {@link getSubscribedEvents} and registers the subscriber as a listener for all
 * returned events.
 *
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface EventSubscriberInterface
{
    /**
     * Returns an array of event names this subscriber wants to listen to.
     *
     * The array keys are event names and the value can be:
     *
     *  * The method name to call (priority defaults to 0)
     *  * An array composed of the method name to call and the priority
     *  * An array of arrays composed of the method names to call and respective
     *    priorities, or 0 if unset
     *
     * For instance:
     *
     *  * array('eventName' => 'methodName')
     *  * array('eventName' => array('methodName', $priority))
     *  * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
     *
     * @return array The event names to listen to
     */
    public static function getSubscribedEvents();
}
<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="vendor/autoload.php"
         failOnRisky="true"
         failOnWarning="true"
>
    <php>
        <ini name="error_reporting" value="-1" />
    </php>

    <testsuites>
        <testsuite name="Symfony EventDispatcher Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * A read-only proxy for an event dispatcher.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ImmutableEventDispatcher implements EventDispatcherInterface
{
    private $dispatcher;

    public function __construct(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * {@inheritdoc}
     */
    public function dispatch($eventName, Event $event = null)
    {
        return $this->dispatcher->dispatch($eventName, $event);
    }

    /**
     * {@inheritdoc}
     */
    public function addListener($eventName, $listener, $priority = 0)
    {
        throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
    }

    /**
     * {@inheritdoc}
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
    }

    /**
     * {@inheritdoc}
     */
    public function removeListener($eventName, $listener)
    {
        throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
    }

    /**
     * {@inheritdoc}
     */
    public function removeSubscriber(EventSubscriberInterface $subscriber)
    {
        throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.');
    }

    /**
     * {@inheritdoc}
     */
    public function getListeners($eventName = null)
    {
        return $this->dispatcher->getListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function getListenerPriority($eventName, $listener)
    {
        return $this->dispatcher->getListenerPriority($eventName, $listener);
    }

    /**
     * {@inheritdoc}
     */
    public function hasListeners($eventName = null)
    {
        return $this->dispatcher->hasListeners($eventName);
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher;

/**
 * Event encapsulation class.
 *
 * Encapsulates events thus decoupling the observer from the subject they encapsulate.
 *
 * @author Drak <drak@zikula.org>
 */
class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
{
    protected $subject;
    protected $arguments;

    /**
     * Encapsulate an event with $subject and $args.
     *
     * @param mixed $subject   The subject of the event, usually an object or a callable
     * @param array $arguments Arguments to store in the event
     */
    public function __construct($subject = null, array $arguments = array())
    {
        $this->subject = $subject;
        $this->arguments = $arguments;
    }

    /**
     * Getter for subject property.
     *
     * @return mixed The observer subject
     */
    public function getSubject()
    {
        return $this->subject;
    }

    /**
     * Get argument by key.
     *
     * @param string $key Key
     *
     * @return mixed Contents of array key
     *
     * @throws \InvalidArgumentException if key is not found
     */
    public function getArgument($key)
    {
        if ($this->hasArgument($key)) {
            return $this->arguments[$key];
        }

        throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key));
    }

    /**
     * Add argument to event.
     *
     * @param string $key   Argument name
     * @param mixed  $value Value
     *
     * @return $this
     */
    public function setArgument($key, $value)
    {
        $this->arguments[$key] = $value;

        return $this;
    }

    /**
     * Getter for all arguments.
     *
     * @return array
     */
    public function getArguments()
    {
        return $this->arguments;
    }

    /**
     * Set args property.
     *
     * @param array $args Arguments
     *
     * @return $this
     */
    public function setArguments(array $args = array())
    {
        $this->arguments = $args;

        return $this;
    }

    /**
     * Has argument.
     *
     * @param string $key Key of arguments array
     *
     * @return bool
     */
    public function hasArgument($key)
    {
        return array_key_exists($key, $this->arguments);
    }

    /**
     * ArrayAccess for argument getter.
     *
     * @param string $key Array key
     *
     * @return mixed
     *
     * @throws \InvalidArgumentException if key does not exist in $this->args
     */
    public function offsetGet($key)
    {
        return $this->getArgument($key);
    }

    /**
     * ArrayAccess for argument setter.
     *
     * @param string $key   Array key to set
     * @param mixed  $value Value
     */
    public function offsetSet($key, $value)
    {
        $this->setArgument($key, $value);
    }

    /**
     * ArrayAccess for unset argument.
     *
     * @param string $key Array key
     */
    public function offsetUnset($key)
    {
        if ($this->hasArgument($key)) {
            unset($this->arguments[$key]);
        }
    }

    /**
     * ArrayAccess has argument.
     *
     * @param string $key Array key
     *
     * @return bool
     */
    public function offsetExists($key)
    {
        return $this->hasArgument($key);
    }

    /**
     * IteratorAggregate for iterating over the object like an array.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->arguments);
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Compiler pass to register tagged services for an event dispatcher.
 */
class RegisterListenersPass implements CompilerPassInterface
{
    protected $dispatcherService;
    protected $listenerTag;
    protected $subscriberTag;

    /**
     * @param string $dispatcherService Service name of the event dispatcher in processed container
     * @param string $listenerTag       Tag name used for listener
     * @param string $subscriberTag     Tag name used for subscribers
     */
    public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber')
    {
        $this->dispatcherService = $dispatcherService;
        $this->listenerTag = $listenerTag;
        $this->subscriberTag = $subscriberTag;
    }

    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) {
            return;
        }

        $definition = $container->findDefinition($this->dispatcherService);

        foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) {
            $def = $container->getDefinition($id);
            if (!$def->isPublic()) {
                throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id));
            }

            if ($def->isAbstract()) {
                throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id));
            }

            foreach ($events as $event) {
                $priority = isset($event['priority']) ? $event['priority'] : 0;

                if (!isset($event['event'])) {
                    throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
                }

                if (!isset($event['method'])) {
                    $event['method'] = 'on'.preg_replace_callback(array(
                        '/(?<=\b)[a-z]/i',
                        '/[^a-z0-9]/i',
                    ), function ($matches) { return strtoupper($matches[0]); }, $event['event']);
                    $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
                }

                $definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
            }
        }

        foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) {
            $def = $container->getDefinition($id);
            if (!$def->isPublic()) {
                throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id));
            }

            if ($def->isAbstract()) {
                throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id));
            }

            // We must assume that the class value has been correctly filled, even if the service is created by a factory
            $class = $container->getParameterBag()->resolveValue($def->getClass());
            $interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';

            if (!is_subclass_of($class, $interface)) {
                if (!class_exists($class, false)) {
                    throw new \InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
                }

                throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
            }

            $definition->addMethodCall('addSubscriberService', array($id, $class));
        }
    }
}
{
    "name": "symfony/event-dispatcher",
    "type": "library",
    "description": "Symfony EventDispatcher Component",
    "keywords": [],
    "homepage": "https://symfony.com",
    "license": "MIT",
    "authors": [
        {
            "name": "Fabien Potencier",
            "email": "fabien@symfony.com"
        },
        {
            "name": "Symfony Community",
            "homepage": "https://symfony.com/contributors"
        }
    ],
    "require": {
        "php": ">=5.3.9"
    },
    "require-dev": {
        "symfony/dependency-injection": "~2.6|~3.0.0",
        "symfony/expression-language": "~2.6|~3.0.0",
        "symfony/config": "^2.0.5|~3.0.0",
        "symfony/stopwatch": "~2.3|~3.0.0",
        "psr/log": "~1.0"
    },
    "suggest": {
        "symfony/dependency-injection": "",
        "symfony/http-kernel": ""
    },
    "autoload": {
        "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" },
        "exclude-from-classmap": [
            "/Tests/"
        ]
    },
    "minimum-stability": "dev",
    "extra": {
        "branch-alias": {
            "dev-master": "2.8-dev"
        }
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Debug;

use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Stopwatch\Stopwatch;

/**
 * Collects some data about event listeners.
 *
 * This event dispatcher delegates the dispatching to another one.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class TraceableEventDispatcher implements TraceableEventDispatcherInterface
{
    protected $logger;
    protected $stopwatch;

    private $called;
    private $dispatcher;
    private $wrappedListeners;

    public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null)
    {
        $this->dispatcher = $dispatcher;
        $this->stopwatch = $stopwatch;
        $this->logger = $logger;
        $this->called = array();
        $this->wrappedListeners = array();
    }

    /**
     * {@inheritdoc}
     */
    public function addListener($eventName, $listener, $priority = 0)
    {
        $this->dispatcher->addListener($eventName, $listener, $priority);
    }

    /**
     * {@inheritdoc}
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->dispatcher->addSubscriber($subscriber);
    }

    /**
     * {@inheritdoc}
     */
    public function removeListener($eventName, $listener)
    {
        if (isset($this->wrappedListeners[$eventName])) {
            foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
                if ($wrappedListener->getWrappedListener() === $listener) {
                    $listener = $wrappedListener;
                    unset($this->wrappedListeners[$eventName][$index]);
                    break;
                }
            }
        }

        return $this->dispatcher->removeListener($eventName, $listener);
    }

    /**
     * {@inheritdoc}
     */
    public function removeSubscriber(EventSubscriberInterface $subscriber)
    {
        return $this->dispatcher->removeSubscriber($subscriber);
    }

    /**
     * {@inheritdoc}
     */
    public function getListeners($eventName = null)
    {
        return $this->dispatcher->getListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function getListenerPriority($eventName, $listener)
    {
        if (!method_exists($this->dispatcher, 'getListenerPriority')) {
            return 0;
        }

        return $this->dispatcher->getListenerPriority($eventName, $listener);
    }

    /**
     * {@inheritdoc}
     */
    public function hasListeners($eventName = null)
    {
        return $this->dispatcher->hasListeners($eventName);
    }

    /**
     * {@inheritdoc}
     */
    public function dispatch($eventName, Event $event = null)
    {
        if (null === $event) {
            $event = new Event();
        }

        if (null !== $this->logger && $event->isPropagationStopped()) {
            $this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
        }

        $this->preProcess($eventName);
        $this->preDispatch($eventName, $event);

        $e = $this->stopwatch->start($eventName, 'section');

        $this->dispatcher->dispatch($eventName, $event);

        if ($e->isStarted()) {
            $e->stop();
        }

        $this->postDispatch($eventName, $event);
        $this->postProcess($eventName);

        return $event;
    }

    /**
     * {@inheritdoc}
     */
    public function getCalledListeners()
    {
        $called = array();
        foreach ($this->called as $eventName => $listeners) {
            foreach ($listeners as $listener) {
                $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
                $called[$eventName.'.'.$info['pretty']] = $info;
            }
        }

        return $called;
    }

    /**
     * {@inheritdoc}
     */
    public function getNotCalledListeners()
    {
        try {
            $allListeners = $this->getListeners();
        } catch (\Exception $e) {
            if (null !== $this->logger) {
                $this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e));
            }

            // unable to retrieve the uncalled listeners
            return array();
        }

        $notCalled = array();
        foreach ($allListeners as $eventName => $listeners) {
            foreach ($listeners as $listener) {
                $called = false;
                if (isset($this->called[$eventName])) {
                    foreach ($this->called[$eventName] as $l) {
                        if ($l->getWrappedListener() === $listener) {
                            $called = true;

                            break;
                        }
                    }
                }

                if (!$called) {
                    $info = $this->getListenerInfo($listener, $eventName);
                    $notCalled[$eventName.'.'.$info['pretty']] = $info;
                }
            }
        }

        uasort($notCalled, array($this, 'sortListenersByPriority'));

        return $notCalled;
    }

    /**
     * Proxies all method calls to the original event dispatcher.
     *
     * @param string $method    The method name
     * @param array  $arguments The method arguments
     *
     * @return mixed
     */
    public function __call($method, $arguments)
    {
        return \call_user_func_array(array($this->dispatcher, $method), $arguments);
    }

    /**
     * Called before dispatching the event.
     *
     * @param string $eventName The event name
     * @param Event  $event     The event
     */
    protected function preDispatch($eventName, Event $event)
    {
    }

    /**
     * Called after dispatching the event.
     *
     * @param string $eventName The event name
     * @param Event  $event     The event
     */
    protected function postDispatch($eventName, Event $event)
    {
    }

    private function preProcess($eventName)
    {
        foreach ($this->dispatcher->getListeners($eventName) as $listener) {
            $info = $this->getListenerInfo($listener, $eventName);
            $name = isset($info['class']) ? $info['class'] : $info['type'];
            $wrappedListener = new WrappedListener($listener, $name, $this->stopwatch, $this);
            $this->wrappedListeners[$eventName][] = $wrappedListener;
            $this->dispatcher->removeListener($eventName, $listener);
            $this->dispatcher->addListener($eventName, $wrappedListener, $info['priority']);
        }
    }

    private function postProcess($eventName)
    {
        unset($this->wrappedListeners[$eventName]);
        $skipped = false;
        foreach ($this->dispatcher->getListeners($eventName) as $listener) {
            if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
                continue;
            }
            // Unwrap listener
            $priority = $this->getListenerPriority($eventName, $listener);
            $this->dispatcher->removeListener($eventName, $listener);
            $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);

            $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
            if ($listener->wasCalled()) {
                if (null !== $this->logger) {
                    $this->logger->debug(sprintf('Notified event "%s" to listener "%s".', $eventName, $info['pretty']));
                }

                if (!isset($this->called[$eventName])) {
                    $this->called[$eventName] = new \SplObjectStorage();
                }

                $this->called[$eventName]->attach($listener);
            }

            if (null !== $this->logger && $skipped) {
                $this->logger->debug(sprintf('Listener "%s" was not called for event "%s".', $info['pretty'], $eventName));
            }

            if ($listener->stoppedPropagation()) {
                if (null !== $this->logger) {
                    $this->logger->debug(sprintf('Listener "%s" stopped propagation of the event "%s".', $info['pretty'], $eventName));
                }

                $skipped = true;
            }
        }
    }

    /**
     * Returns information about the listener.
     *
     * @param object $listener  The listener
     * @param string $eventName The event name
     *
     * @return array Information about the listener
     */
    private function getListenerInfo($listener, $eventName)
    {
        $info = array(
            'event' => $eventName,
            'priority' => $this->getListenerPriority($eventName, $listener),
        );

        // unwrap for correct listener info
        if ($listener instanceof WrappedListener) {
            $listener = $listener->getWrappedListener();
        }

        if ($listener instanceof \Closure) {
            $info += array(
                'type' => 'Closure',
                'pretty' => 'closure',
            );
        } elseif (\is_string($listener)) {
            try {
                $r = new \ReflectionFunction($listener);
                $file = $r->getFileName();
                $line = $r->getStartLine();
            } catch (\ReflectionException $e) {
                $file = null;
                $line = null;
            }
            $info += array(
                'type' => 'Function',
                'function' => $listener,
                'file' => $file,
                'line' => $line,
                'pretty' => $listener,
            );
        } elseif (\is_array($listener) || (\is_object($listener) && \is_callable($listener))) {
            if (!\is_array($listener)) {
                $listener = array($listener, '__invoke');
            }
            $class = \is_object($listener[0]) ? \get_class($listener[0]) : $listener[0];
            try {
                $r = new \ReflectionMethod($class, $listener[1]);
                $file = $r->getFileName();
                $line = $r->getStartLine();
            } catch (\ReflectionException $e) {
                $file = null;
                $line = null;
            }
            $info += array(
                'type' => 'Method',
                'class' => $class,
                'method' => $listener[1],
                'file' => $file,
                'line' => $line,
                'pretty' => $class.'::'.$listener[1],
            );
        }

        return $info;
    }

    private function sortListenersByPriority($a, $b)
    {
        if (\is_int($a['priority']) && !\is_int($b['priority'])) {
            return 1;
        }

        if (!\is_int($a['priority']) && \is_int($b['priority'])) {
            return -1;
        }

        if ($a['priority'] === $b['priority']) {
            return 0;
        }

        if ($a['priority'] > $b['priority']) {
            return -1;
        }

        return 1;
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Debug;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class WrappedListener
{
    private $listener;
    private $name;
    private $called;
    private $stoppedPropagation;
    private $stopwatch;
    private $dispatcher;

    public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
    {
        $this->listener = $listener;
        $this->name = $name;
        $this->stopwatch = $stopwatch;
        $this->dispatcher = $dispatcher;
        $this->called = false;
        $this->stoppedPropagation = false;
    }

    public function getWrappedListener()
    {
        return $this->listener;
    }

    public function wasCalled()
    {
        return $this->called;
    }

    public function stoppedPropagation()
    {
        return $this->stoppedPropagation;
    }

    public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher)
    {
        $this->called = true;

        $e = $this->stopwatch->start($this->name, 'event_listener');

        \call_user_func($this->listener, $event, $eventName, $this->dispatcher ?: $dispatcher);

        if ($e->isStarted()) {
            $e->stop();
        }

        if ($event->isPropagationStopped()) {
            $this->stoppedPropagation = true;
        }
    }
}
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Debug;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface TraceableEventDispatcherInterface extends EventDispatcherInterface
{
    /**
     * Gets the called listeners.
     *
     * @return array An array of called listeners
     */
    public function getCalledListeners();

    /**
     * Gets the not called listeners.
     *
     * @return array An array of not called listeners
     */
    public function getNotCalledListeners();
}
Comparator

Copyright (c) 2002-2018, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [3.0.5] - 2022-09-14

### Fixed

* [#102](https://github.com/sebastianbergmann/comparator/pull/102): Fix `float` comparison precision

## [3.0.4] - 2022-09-14

### Fixed

* [#99](https://github.com/sebastianbergmann/comparator/pull/99): Fix weak comparison between `'0'` and `false`

## [3.0.3] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [3.0.2] - 2018-07-12

### Changed

* By default, `MockObjectComparator` is now tried before all other (default) comparators

## [3.0.1] - 2018-06-14

### Fixed

* [#53](https://github.com/sebastianbergmann/comparator/pull/53): `DOMNodeComparator` ignores `$ignoreCase` parameter
* [#58](https://github.com/sebastianbergmann/comparator/pull/58): `ScalarComparator` does not handle extremely ugly string comparison edge cases

## [3.0.0] - 2018-04-18

### Fixed

* [#48](https://github.com/sebastianbergmann/comparator/issues/48): `DateTimeComparator` does not support fractional second deltas

### Removed

* Removed support for PHP 7.0

## [2.1.3] - 2018-02-01

### Changed

* This component is now compatible with version 3 of `sebastian/diff`

## [2.1.2] - 2018-01-12

### Fixed

* Fix comparison of `DateTimeImmutable` objects

## [2.1.1] - 2017-12-22

### Fixed

* [phpunit/#2923](https://github.com/sebastianbergmann/phpunit/issues/2923): Unexpected failed date matching

## [2.1.0] - 2017-11-03

### Added

* Added `SebastianBergmann\Comparator\Factory::reset()` to unregister all non-default comparators
* Added support for `phpunit/phpunit-mock-objects` version `^5.0`

[3.0.5]: https://github.com/sebastianbergmann/comparator/compare/3.0.4...3.0.5
[3.0.4]: https://github.com/sebastianbergmann/comparator/compare/3.0.3...3.0.4
[3.0.3]: https://github.com/sebastianbergmann/comparator/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/sebastianbergmann/comparator/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/comparator/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/comparator/compare/2.1.3...3.0.0
[2.1.3]: https://github.com/sebastianbergmann/comparator/compare/2.1.2...2.1.3
[2.1.2]: https://github.com/sebastianbergmann/comparator/compare/2.1.1...2.1.2
[2.1.1]: https://github.com/sebastianbergmann/comparator/compare/2.1.0...2.1.1
[2.1.0]: https://github.com/sebastianbergmann/comparator/compare/2.0.2...2.1.0
[![Build Status](https://travis-ci.org/sebastianbergmann/comparator.svg?branch=master)](https://travis-ci.org/sebastianbergmann/comparator)

# Comparator

This component provides the functionality to compare PHP values for equality.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/comparator

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/comparator

## Usage

```php
<?php
use SebastianBergmann\Comparator\Factory;
use SebastianBergmann\Comparator\ComparisonFailure;

$date1 = new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York'));
$date2 = new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/Chicago'));

$factory = new Factory;
$comparator = $factory->getComparatorFor($date1, $date2);

try {
    $comparator->assertEquals($date1, $date2);
    print "Dates match";
} catch (ComparisonFailure $failure) {
    print "Dates don't match";
}
```

{
    "name": "sebastian/comparator",
    "description": "Provides the functionality to compare PHP values for equality",
    "keywords": ["comparator","compare","equality"],
    "homepage": "https://github.com/sebastianbergmann/comparator",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        },
        {
            "name": "Jeff Welch",
            "email": "whatthejeff@gmail.com"
        },
        {
            "name": "Volker Dusch",
            "email": "github@wallbash.com"
        },
        {
            "name": "Bernhard Schussek",
            "email": "bschussek@2bepublished.at"
        }
    ],
    "prefer-stable": true,
    "require": {
        "php": ">=7.1",
        "sebastian/diff": "^3.0",
        "sebastian/exporter": "^3.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.5"
    },
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/_fixture"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.0-dev"
        }
    }
}

<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares arrays for equality.
 */
class ArrayComparator extends Comparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return \is_array($expected) && \is_array($actual);
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     * @param array $processed    List of already processed elements (used to prevent infinite recursion)
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = [])
    {
        if ($canonicalize) {
            \sort($expected);
            \sort($actual);
        }

        $remaining        = $actual;
        $actualAsString   = "Array (\n";
        $expectedAsString = "Array (\n";
        $equal            = true;

        foreach ($expected as $key => $value) {
            unset($remaining[$key]);

            if (!\array_key_exists($key, $actual)) {
                $expectedAsString .= \sprintf(
                    "    %s => %s\n",
                    $this->exporter->export($key),
                    $this->exporter->shortenedExport($value)
                );

                $equal = false;

                continue;
            }

            try {
                $comparator = $this->factory->getComparatorFor($value, $actual[$key]);
                $comparator->assertEquals($value, $actual[$key], $delta, $canonicalize, $ignoreCase, $processed);

                $expectedAsString .= \sprintf(
                    "    %s => %s\n",
                    $this->exporter->export($key),
                    $this->exporter->shortenedExport($value)
                );

                $actualAsString .= \sprintf(
                    "    %s => %s\n",
                    $this->exporter->export($key),
                    $this->exporter->shortenedExport($actual[$key])
                );
            } catch (ComparisonFailure $e) {
                $expectedAsString .= \sprintf(
                    "    %s => %s\n",
                    $this->exporter->export($key),
                    $e->getExpectedAsString() ? $this->indent($e->getExpectedAsString()) : $this->exporter->shortenedExport($e->getExpected())
                );

                $actualAsString .= \sprintf(
                    "    %s => %s\n",
                    $this->exporter->export($key),
                    $e->getActualAsString() ? $this->indent($e->getActualAsString()) : $this->exporter->shortenedExport($e->getActual())
                );

                $equal = false;
            }
        }

        foreach ($remaining as $key => $value) {
            $actualAsString .= \sprintf(
                "    %s => %s\n",
                $this->exporter->export($key),
                $this->exporter->shortenedExport($value)
            );

            $equal = false;
        }

        $expectedAsString .= ')';
        $actualAsString .= ')';

        if (!$equal) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                $expectedAsString,
                $actualAsString,
                false,
                'Failed asserting that two arrays are equal.'
            );
        }
    }

    protected function indent($lines)
    {
        return \trim(\str_replace("\n", "\n    ", $lines));
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares values for type equality.
 */
class TypeComparator extends Comparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return true;
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        if (\gettype($expected) != \gettype($actual)) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                // we don't need a diff
                '',
                '',
                false,
                \sprintf(
                    '%s does not match expected type "%s".',
                    $this->exporter->shortenedExport($actual),
                    \gettype($expected)
                )
            );
        }
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Factory for comparators which compare values for equality.
 */
class Factory
{
    /**
     * @var Factory
     */
    private static $instance;

    /**
     * @var Comparator[]
     */
    private $customComparators = [];

    /**
     * @var Comparator[]
     */
    private $defaultComparators = [];

    /**
     * @return Factory
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * Constructs a new factory.
     */
    public function __construct()
    {
        $this->registerDefaultComparators();
    }

    /**
     * Returns the correct comparator for comparing two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return Comparator
     */
    public function getComparatorFor($expected, $actual)
    {
        foreach ($this->customComparators as $comparator) {
            if ($comparator->accepts($expected, $actual)) {
                return $comparator;
            }
        }

        foreach ($this->defaultComparators as $comparator) {
            if ($comparator->accepts($expected, $actual)) {
                return $comparator;
            }
        }
    }

    /**
     * Registers a new comparator.
     *
     * This comparator will be returned by getComparatorFor() if its accept() method
     * returns TRUE for the compared values. It has higher priority than the
     * existing comparators, meaning that its accept() method will be invoked
     * before those of the other comparators.
     *
     * @param Comparator $comparator The comparator to be registered
     */
    public function register(Comparator $comparator)
    {
        \array_unshift($this->customComparators, $comparator);

        $comparator->setFactory($this);
    }

    /**
     * Unregisters a comparator.
     *
     * This comparator will no longer be considered by getComparatorFor().
     *
     * @param Comparator $comparator The comparator to be unregistered
     */
    public function unregister(Comparator $comparator)
    {
        foreach ($this->customComparators as $key => $_comparator) {
            if ($comparator === $_comparator) {
                unset($this->customComparators[$key]);
            }
        }
    }

    /**
     * Unregisters all non-default comparators.
     */
    public function reset()
    {
        $this->customComparators = [];
    }

    private function registerDefaultComparators()
    {
        $this->registerDefaultComparator(new MockObjectComparator);
        $this->registerDefaultComparator(new DateTimeComparator);
        $this->registerDefaultComparator(new DOMNodeComparator);
        $this->registerDefaultComparator(new SplObjectStorageComparator);
        $this->registerDefaultComparator(new ExceptionComparator);
        $this->registerDefaultComparator(new ObjectComparator);
        $this->registerDefaultComparator(new ResourceComparator);
        $this->registerDefaultComparator(new ArrayComparator);
        $this->registerDefaultComparator(new NumericComparator);
        $this->registerDefaultComparator(new ScalarComparator);
        $this->registerDefaultComparator(new TypeComparator);
    }

    private function registerDefaultComparator(Comparator $comparator)
    {
        $this->defaultComparators[] = $comparator;

        $comparator->setFactory($this);
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares resources for equality.
 */
class ResourceComparator extends Comparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return \is_resource($expected) && \is_resource($actual);
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        if ($actual != $expected) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                $this->exporter->export($expected),
                $this->exporter->export($actual)
            );
        }
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares PHPUnit_Framework_MockObject_MockObject instances for equality.
 */
class MockObjectComparator extends ObjectComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return ($expected instanceof \PHPUnit_Framework_MockObject_MockObject || $expected instanceof \PHPUnit\Framework\MockObject\MockObject) &&
               ($actual instanceof \PHPUnit_Framework_MockObject_MockObject || $actual instanceof \PHPUnit\Framework\MockObject\MockObject);
    }

    /**
     * Converts an object to an array containing all of its private, protected
     * and public properties.
     *
     * @param object $object
     *
     * @return array
     */
    protected function toArray($object)
    {
        $array = parent::toArray($object);

        unset($array['__phpunit_invocationMocker']);

        return $array;
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares objects for equality.
 */
class ObjectComparator extends ArrayComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return \is_object($expected) && \is_object($actual);
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     * @param array $processed    List of already processed elements (used to prevent infinite recursion)
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = [])
    {
        if (\get_class($actual) !== \get_class($expected)) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                $this->exporter->export($expected),
                $this->exporter->export($actual),
                false,
                \sprintf(
                    '%s is not instance of expected class "%s".',
                    $this->exporter->export($actual),
                    \get_class($expected)
                )
            );
        }

        // don't compare twice to allow for cyclic dependencies
        if (\in_array([$actual, $expected], $processed, true) ||
            \in_array([$expected, $actual], $processed, true)) {
            return;
        }

        $processed[] = [$actual, $expected];

        // don't compare objects if they are identical
        // this helps to avoid the error "maximum function nesting level reached"
        // CAUTION: this conditional clause is not tested
        if ($actual !== $expected) {
            try {
                parent::assertEquals(
                    $this->toArray($expected),
                    $this->toArray($actual),
                    $delta,
                    $canonicalize,
                    $ignoreCase,
                    $processed
                );
            } catch (ComparisonFailure $e) {
                throw new ComparisonFailure(
                    $expected,
                    $actual,
                    // replace "Array" with "MyClass object"
                    \substr_replace($e->getExpectedAsString(), \get_class($expected) . ' Object', 0, 5),
                    \substr_replace($e->getActualAsString(), \get_class($actual) . ' Object', 0, 5),
                    false,
                    'Failed asserting that two objects are equal.'
                );
            }
        }
    }

    /**
     * Converts an object to an array containing all of its private, protected
     * and public properties.
     *
     * @param object $object
     *
     * @return array
     */
    protected function toArray($object)
    {
        return $this->exporter->toArray($object);
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares numerical values for equality.
 */
class NumericComparator extends ScalarComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        // all numerical values, but not if both of them are strings
        return \is_numeric($expected) && \is_numeric($actual) &&
               !(\is_string($expected) && \is_string($actual));
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        if (\is_infinite($actual) && \is_infinite($expected)) {
            return; // @codeCoverageIgnore
        }

        if ((\is_infinite($actual) xor \is_infinite($expected)) ||
            (\is_nan($actual) || \is_nan($expected)) ||
            \abs($actual - $expected) > $delta) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                '',
                '',
                false,
                \sprintf(
                    'Failed asserting that %s matches expected %s.',
                    $this->exporter->export($actual),
                    $this->exporter->export($expected)
                )
            );
        }
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares DateTimeInterface instances for equality.
 */
class DateTimeComparator extends ObjectComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return ($expected instanceof \DateTime || $expected instanceof \DateTimeInterface) &&
               ($actual instanceof \DateTime || $actual instanceof \DateTimeInterface);
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     * @param array $processed    List of already processed elements (used to prevent infinite recursion)
     *
     * @throws \Exception
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = [])
    {
        /** @var \DateTimeInterface $expected */
        /** @var \DateTimeInterface $actual */
        $absDelta = \abs($delta);
        $delta    = new \DateInterval(\sprintf('PT%dS', $absDelta));
        $delta->f = $absDelta - \floor($absDelta);

        $actualClone = (clone $actual)
            ->setTimezone(new \DateTimeZone('UTC'));

        $expectedLower = (clone $expected)
            ->setTimezone(new \DateTimeZone('UTC'))
            ->sub($delta);

        $expectedUpper = (clone $expected)
            ->setTimezone(new \DateTimeZone('UTC'))
            ->add($delta);

        if ($actualClone < $expectedLower || $actualClone > $expectedUpper) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                $this->dateTimeToString($expected),
                $this->dateTimeToString($actual),
                false,
                'Failed asserting that two DateTime objects are equal.'
            );
        }
    }

    /**
     * Returns an ISO 8601 formatted string representation of a datetime or
     * 'Invalid DateTimeInterface object' if the provided DateTimeInterface was not properly
     * initialized.
     */
    private function dateTimeToString(\DateTimeInterface $datetime): string
    {
        $string = $datetime->format('Y-m-d\TH:i:s.uO');

        return $string ?: 'Invalid DateTimeInterface object';
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares scalar or NULL values for equality.
 */
class ScalarComparator extends Comparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     *
     * @since  Method available since Release 3.6.0
     */
    public function accepts($expected, $actual)
    {
        return ((\is_scalar($expected) xor null === $expected) &&
               (\is_scalar($actual) xor null === $actual))
               // allow comparison between strings and objects featuring __toString()
               || (\is_string($expected) && \is_object($actual) && \method_exists($actual, '__toString'))
               || (\is_object($expected) && \method_exists($expected, '__toString') && \is_string($actual));
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        $expectedToCompare = $expected;
        $actualToCompare   = $actual;

        // always compare as strings to avoid strange behaviour
        // otherwise 0 == 'Foobar'
        if ((\is_string($expected) && !\is_bool($actual)) || (\is_string($actual) && !\is_bool($expected))) {
            $expectedToCompare = (string) $expectedToCompare;
            $actualToCompare   = (string) $actualToCompare;

            if ($ignoreCase) {
                $expectedToCompare = \strtolower($expectedToCompare);
                $actualToCompare   = \strtolower($actualToCompare);
            }
        }

        if ($expectedToCompare !== $actualToCompare && \is_string($expected) && \is_string($actual)) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                $this->exporter->export($expected),
                $this->exporter->export($actual),
                false,
                'Failed asserting that two strings are equal.'
            );
        }

        if ($expectedToCompare != $actualToCompare) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                // no diff is required
                '',
                '',
                false,
                \sprintf(
                    'Failed asserting that %s matches expected %s.',
                    $this->exporter->export($actual),
                    $this->exporter->export($expected)
                )
            );
        }
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares Exception instances for equality.
 */
class ExceptionComparator extends ObjectComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return $expected instanceof \Exception && $actual instanceof \Exception;
    }

    /**
     * Converts an object to an array containing all of its private, protected
     * and public properties.
     *
     * @param object $object
     *
     * @return array
     */
    protected function toArray($object)
    {
        $array = parent::toArray($object);

        unset(
            $array['file'],
            $array['line'],
            $array['trace'],
            $array['string'],
            $array['xdebug_message']
        );

        return $array;
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

use SebastianBergmann\Exporter\Exporter;

/**
 * Abstract base class for comparators which compare values for equality.
 */
abstract class Comparator
{
    /**
     * @var Factory
     */
    protected $factory;

    /**
     * @var Exporter
     */
    protected $exporter;

    public function __construct()
    {
        $this->exporter = new Exporter;
    }

    public function setFactory(Factory $factory)
    {
        $this->factory = $factory;
    }

    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    abstract public function accepts($expected, $actual);

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    abstract public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false);
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares doubles for equality.
 *
 * @deprecated since v3.0.5 and v4.0.8
 */
class DoubleComparator extends NumericComparator
{
    /**
     * Smallest value available in PHP.
     *
     * @var float
     */
    const EPSILON = 0.0000000001;

    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return (\is_float($expected) || \is_float($actual)) && \is_numeric($expected) && \is_numeric($actual);
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        if ($delta == 0) {
            $delta = self::EPSILON;
        }

        parent::assertEquals($expected, $actual, $delta, $canonicalize, $ignoreCase);
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

use DOMDocument;
use DOMNode;

/**
 * Compares DOMNode instances for equality.
 */
class DOMNodeComparator extends ObjectComparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return $expected instanceof DOMNode && $actual instanceof DOMNode;
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     * @param array $processed    List of already processed elements (used to prevent infinite recursion)
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = [])
    {
        $expectedAsString = $this->nodeToText($expected, true, $ignoreCase);
        $actualAsString   = $this->nodeToText($actual, true, $ignoreCase);

        if ($expectedAsString !== $actualAsString) {
            $type = $expected instanceof DOMDocument ? 'documents' : 'nodes';

            throw new ComparisonFailure(
                $expected,
                $actual,
                $expectedAsString,
                $actualAsString,
                false,
                \sprintf("Failed asserting that two DOM %s are equal.\n", $type)
            );
        }
    }

    /**
     * Returns the normalized, whitespace-cleaned, and indented textual
     * representation of a DOMNode.
     */
    private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase): string
    {
        if ($canonicalize) {
            $document = new DOMDocument;
            @$document->loadXML($node->C14N());

            $node = $document;
        }

        $document = $node instanceof DOMDocument ? $node : $node->ownerDocument;

        $document->formatOutput = true;
        $document->normalizeDocument();

        $text = $node instanceof DOMDocument ? $node->saveXML() : $document->saveXML($node);

        return $ignoreCase ? \strtolower($text) : $text;
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;

/**
 * Thrown when an assertion for string equality failed.
 */
class ComparisonFailure extends \RuntimeException
{
    /**
     * Expected value of the retrieval which does not match $actual.
     *
     * @var mixed
     */
    protected $expected;

    /**
     * Actually retrieved value which does not match $expected.
     *
     * @var mixed
     */
    protected $actual;

    /**
     * The string representation of the expected value
     *
     * @var string
     */
    protected $expectedAsString;

    /**
     * The string representation of the actual value
     *
     * @var string
     */
    protected $actualAsString;

    /**
     * @var bool
     */
    protected $identical;

    /**
     * Optional message which is placed in front of the first line
     * returned by toString().
     *
     * @var string
     */
    protected $message;

    /**
     * Initialises with the expected value and the actual value.
     *
     * @param mixed  $expected         expected value retrieved
     * @param mixed  $actual           actual value retrieved
     * @param string $expectedAsString
     * @param string $actualAsString
     * @param bool   $identical
     * @param string $message          a string which is prefixed on all returned lines
     *                                 in the difference output
     */
    public function __construct($expected, $actual, $expectedAsString, $actualAsString, $identical = false, $message = '')
    {
        $this->expected         = $expected;
        $this->actual           = $actual;
        $this->expectedAsString = $expectedAsString;
        $this->actualAsString   = $actualAsString;
        $this->message          = $message;
    }

    public function getActual()
    {
        return $this->actual;
    }

    public function getExpected()
    {
        return $this->expected;
    }

    /**
     * @return string
     */
    public function getActualAsString()
    {
        return $this->actualAsString;
    }

    /**
     * @return string
     */
    public function getExpectedAsString()
    {
        return $this->expectedAsString;
    }

    /**
     * @return string
     */
    public function getDiff()
    {
        if (!$this->actualAsString && !$this->expectedAsString) {
            return '';
        }

        $differ = new Differ(new UnifiedDiffOutputBuilder("\n--- Expected\n+++ Actual\n"));

        return $differ->diff($this->expectedAsString, $this->actualAsString);
    }

    /**
     * @return string
     */
    public function toString()
    {
        return $this->message . $this->getDiff();
    }
}
<?php
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

/**
 * Compares \SplObjectStorage instances for equality.
 */
class SplObjectStorageComparator extends Comparator
{
    /**
     * Returns whether the comparator can compare two values.
     *
     * @param mixed $expected The first value to compare
     * @param mixed $actual   The second value to compare
     *
     * @return bool
     */
    public function accepts($expected, $actual)
    {
        return $expected instanceof \SplObjectStorage && $actual instanceof \SplObjectStorage;
    }

    /**
     * Asserts that two values are equal.
     *
     * @param mixed $expected     First value to compare
     * @param mixed $actual       Second value to compare
     * @param float $delta        Allowed numerical distance between two values to consider them equal
     * @param bool  $canonicalize Arrays are sorted before comparison when set to true
     * @param bool  $ignoreCase   Case is ignored when set to true
     *
     * @throws ComparisonFailure
     */
    public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
    {
        foreach ($actual as $object) {
            if (!$expected->contains($object)) {
                throw new ComparisonFailure(
                    $expected,
                    $actual,
                    $this->exporter->export($expected),
                    $this->exporter->export($actual),
                    false,
                    'Failed asserting that two objects are equal.'
                );
            }
        }

        foreach ($expected as $object) {
            if (!$actual->contains($object)) {
                throw new ComparisonFailure(
                    $expected,
                    $actual,
                    $this->exporter->export($expected),
                    $this->exporter->export($actual),
                    false,
                    'Failed asserting that two objects are equal.'
                );
            }
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.0/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         executionOrder="depends,defects"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>

    <php>
        <const name="GLOBALSTATE_TESTSUITE" value="true"/>
        <ini name="date.timezone" value="Etc/UTC"/>
    </php>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
sebastian/global-state

Copyright (c) 2001-2022, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Changes in sebastian/global-state

All notable changes in `sebastian/global-state` are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.

## [3.0.2] - 2022-02-10

### Fixed

* The `$includeTraits` parameter of `SebastianBergmann\GlobalState\Snapshot::__construct()` is not respected

## [3.0.1] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.2` to `>=7.2`

## [3.0.0] - 2019-02-01

### Changed

* `Snapshot::canBeSerialized()` now recursively checks arrays and object graphs for variables that cannot be serialized

### Removed

* This component is no longer supported on PHP 7.0 and PHP 7.1

[3.0.2]: https://github.com/sebastianbergmann/phpunit/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/phpunit/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/phpunit/compare/2.0.0...3.0.0

<?xml version="1.0" encoding="UTF-8"?>
<project name="global-state" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>
</project>
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\GlobalState\TestFixture\BlacklistedChildClass;
use SebastianBergmann\GlobalState\TestFixture\BlacklistedClass;
use SebastianBergmann\GlobalState\TestFixture\BlacklistedImplementor;
use SebastianBergmann\GlobalState\TestFixture\BlacklistedInterface;

/**
 * @covers \SebastianBergmann\GlobalState\Blacklist
 */
final class BlacklistTest extends TestCase
{
    /**
     * @var \SebastianBergmann\GlobalState\Blacklist
     */
    private $blacklist;

    protected function setUp(): void
    {
        $this->blacklist = new Blacklist;
    }

    public function testGlobalVariableThatIsNotBlacklistedIsNotTreatedAsBlacklisted(): void
    {
        $this->assertFalse($this->blacklist->isGlobalVariableBlacklisted('variable'));
    }

    public function testGlobalVariableCanBeBlacklisted(): void
    {
        $this->blacklist->addGlobalVariable('variable');

        $this->assertTrue($this->blacklist->isGlobalVariableBlacklisted('variable'));
    }

    public function testStaticAttributeThatIsNotBlacklistedIsNotTreatedAsBlacklisted(): void
    {
        $this->assertFalse(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedClass::class,
                'attribute'
            )
        );
    }

    public function testClassCanBeBlacklisted(): void
    {
        $this->blacklist->addClass(BlacklistedClass::class);

        $this->assertTrue(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedClass::class,
                'attribute'
            )
        );
    }

    public function testSubclassesCanBeBlacklisted(): void
    {
        $this->blacklist->addSubclassesOf(BlacklistedClass::class);

        $this->assertTrue(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedChildClass::class,
                'attribute'
            )
        );
    }

    public function testImplementorsCanBeBlacklisted(): void
    {
        $this->blacklist->addImplementorsOf(BlacklistedInterface::class);

        $this->assertTrue(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedImplementor::class,
                'attribute'
            )
        );
    }

    public function testClassNamePrefixesCanBeBlacklisted(): void
    {
        $this->blacklist->addClassNamePrefix('SebastianBergmann\GlobalState');

        $this->assertTrue(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedClass::class,
                'attribute'
            )
        );
    }

    public function testStaticAttributeCanBeBlacklisted(): void
    {
        $this->blacklist->addStaticAttribute(
            BlacklistedClass::class,
            'attribute'
        );

        $this->assertTrue(
            $this->blacklist->isStaticAttributeBlacklisted(
                BlacklistedClass::class,
                'attribute'
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\GlobalState\Restorer
 *
 * @uses \SebastianBergmann\GlobalState\Blacklist
 * @uses \SebastianBergmann\GlobalState\Snapshot
 */
final class RestorerTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        $GLOBALS['varBool'] = false;
        $GLOBALS['varNull'] = null;
        $_GET['varGet']     = 0;
    }

    public function testRestorerGlobalVariable(): void
    {
        $snapshot = new Snapshot(null, true, false, false, false, false, false, false, false, false);
        $restorer = new Restorer;
        $restorer->restoreGlobalVariables($snapshot);

        $this->assertArrayHasKey('varBool', $GLOBALS);
        $this->assertEquals(false, $GLOBALS['varBool']);
        $this->assertArrayHasKey('varNull', $GLOBALS);
        $this->assertEquals(null, $GLOBALS['varNull']);
        $this->assertArrayHasKey('varGet', $_GET);
        $this->assertEquals(0, $_GET['varGet']);
    }

    /**
     * @backupGlobals enabled
     */
    public function testIntegrationRestorerGlobalVariables(): void
    {
        $this->assertArrayHasKey('varBool', $GLOBALS);
        $this->assertEquals(false, $GLOBALS['varBool']);
        $this->assertArrayHasKey('varNull', $GLOBALS);
        $this->assertEquals(null, $GLOBALS['varNull']);
        $this->assertArrayHasKey('varGet', $_GET);
        $this->assertEquals(0, $_GET['varGet']);
    }

    /**
     * @depends testIntegrationRestorerGlobalVariables
     */
    public function testIntegrationRestorerGlobalVariables2(): void
    {
        $this->assertArrayHasKey('varBool', $GLOBALS);
        $this->assertEquals(false, $GLOBALS['varBool']);
        $this->assertArrayHasKey('varNull', $GLOBALS);
        $this->assertEquals(null, $GLOBALS['varNull']);
        $this->assertArrayHasKey('varGet', $_GET);
        $this->assertEquals(0, $_GET['varGet']);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\GlobalState\TestFixture\BlacklistedInterface;
use SebastianBergmann\GlobalState\TestFixture\SnapshotClass;
use SebastianBergmann\GlobalState\TestFixture\SnapshotTrait;

/**
 * @covers \SebastianBergmann\GlobalState\Snapshot
 *
 * @uses \SebastianBergmann\GlobalState\Blacklist
 */
final class SnapshotTest extends TestCase
{
    /**
     * @var Blacklist
     */
    private $blacklist;

    protected function setUp(): void
    {
        $this->blacklist = new Blacklist;
    }

    public function testStaticAttributes(): void
    {
        SnapshotClass::init();

        $this->blacklistAllLoadedClassesExceptSnapshotClass();

        $snapshot = new Snapshot($this->blacklist, false, true, false, false, false, false, false, false, false);

        $expected = [
            SnapshotClass::class => [
                'string'  => 'string',
                'objects' => [new \stdClass],
            ],
        ];

        $this->assertEquals($expected, $snapshot->staticAttributes());
    }

    public function testConstants(): void
    {
        $snapshot = new Snapshot($this->blacklist, false, false, true, false, false, false, false, false, false);

        $this->assertArrayHasKey('GLOBALSTATE_TESTSUITE', $snapshot->constants());
    }

    public function testFunctions(): void
    {
        $snapshot  = new Snapshot($this->blacklist, false, false, false, true, false, false, false, false, false);
        $functions = $snapshot->functions();

        $this->assertContains('sebastianbergmann\globalstate\testfixture\snapshotfunction', $functions);
        $this->assertNotContains('assert', $functions);
    }

    public function testClasses(): void
    {
        $snapshot = new Snapshot($this->blacklist, false, false, false, false, true, false, false, false, false);
        $classes  = $snapshot->classes();

        $this->assertContains(TestCase::class, $classes);
        $this->assertNotContains(Exception::class, $classes);
    }

    public function testInterfaces(): void
    {
        $snapshot   = new Snapshot($this->blacklist, false, false, false, false, false, true, false, false, false);
        $interfaces = $snapshot->interfaces();

        $this->assertContains(BlacklistedInterface::class, $interfaces);
        $this->assertNotContains(\Countable::class, $interfaces);
    }

    public function testTraits(): void
    {
        \spl_autoload_call('SebastianBergmann\GlobalState\TestFixture\SnapshotTrait');

        $snapshot = new Snapshot($this->blacklist, false, false, false, false, false, false, true, false, false);

        $this->assertContains(SnapshotTrait::class, $snapshot->traits());
    }

    public function testIniSettings(): void
    {
        $snapshot    = new Snapshot($this->blacklist, false, false, false, false, false, false, false, true, false);
        $iniSettings = $snapshot->iniSettings();

        $this->assertArrayHasKey('date.timezone', $iniSettings);
        $this->assertEquals('Etc/UTC', $iniSettings['date.timezone']);
    }

    public function testIncludedFiles(): void
    {
        $snapshot = new Snapshot($this->blacklist, false, false, false, false, false, false, false, false, true);
        $this->assertContains(__FILE__, $snapshot->includedFiles());
    }

    private function blacklistAllLoadedClassesExceptSnapshotClass(): void
    {
        foreach (\get_declared_classes() as $class) {
            if ($class === SnapshotClass::class) {
                continue;
            }

            $this->blacklist->addClass($class);
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\GlobalState\CodeExporter
 */
final class CodeExporterTest extends TestCase
{
    /**
     * @runInSeparateProcess
     */
    public function testCanExportGlobalVariablesToCode(): void
    {
        $GLOBALS = ['foo' => 'bar'];

        $snapshot = new Snapshot(null, true, false, false, false, false, false, false, false, false);

        $exporter = new CodeExporter;

        $this->assertEquals(
            '$GLOBALS = [];' . \PHP_EOL . '$GLOBALS[\'foo\'] = \'bar\';' . \PHP_EOL,
            $exporter->globalVariables($snapshot)
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

interface BlacklistedInterface
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

class BlacklistedClass
{
    private static $attribute;
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

trait SnapshotTrait
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

class BlacklistedChildClass extends BlacklistedClass
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

function snapshotFunction(): void
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

class BlacklistedImplementor implements BlacklistedInterface
{
    private static $attribute;
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

class SnapshotClass
{
    private static $string = 'string';

    private static $closures = [];

    private static $files = [];

    private static $resources = [];

    private static $objects = [];

    public static function init(): void
    {
        self::$closures[] = function (): void {
        };

        self::$files[] = new \SplFileInfo(__FILE__);

        self::$resources[] = \fopen('php://memory', 'r');

        self::$objects[] = new \stdClass;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState\TestFixture;

use DomDocument;

class SnapshotDomDocument extends DomDocument
{
}
# global-state

Snapshotting of global state, factored out of PHPUnit into a stand-alone component.

[![Build Status](https://travis-ci.org/sebastianbergmann/global-state.svg?branch=master)](https://travis-ci.org/sebastianbergmann/global-state)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/global-state

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/global-state

/.idea
/.php_cs
/.php_cs.cache
/.phpunit.result.cache
/composer.lock
/vendor
# Configuration for probot-stale - https://github.com/probot/stale

# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale Issue or Pull Request is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 7

# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
  - enhancement

# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false

# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false

# Label to use when marking as stale
staleLabel: stale

# Comment to post when marking as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.

# Comment to post when removing the stale label.
# unmarkComment: >
#   Your comment here.

# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
  This issue has been automatically closed because it has not had activity since it was marked as stale. Thank you for your contributions.

# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

# Limit to only `issues` or `pulls`
only: issues

language: php

php:
  - 7.2
  - 7.3
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "sebastian/global-state",
    "description": "Snapshotting of global state",
    "keywords": ["global state"],
    "homepage": "http://www.github.com/sebastianbergmann/global-state",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "prefer-stable": true,
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "require": {
        "php": ">=7.2",
        "sebastian/object-reflector": "^1.1.1",
        "sebastian/recursion-context": "^3.0"
    },
    "require-dev": {
        "ext-dom": "*",
        "phpunit/phpunit": "^8.0"
    },
    "suggest": {
        "ext-uopz": "*"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/_fixture/"
        ],
        "files": [
            "tests/_fixture/SnapshotFunctions.php"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.0-dev"
        }
    }
}
<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of sebastian/global-state.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => ['groups' => ['simple', 'meta']],
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

/**
 * Restorer of snapshots of global state.
 */
class Restorer
{
    /**
     * Deletes function definitions that are not defined in a snapshot.
     *
     * @throws RuntimeException when the uopz_delete() function is not available
     *
     * @see https://github.com/krakjoe/uopz
     */
    public function restoreFunctions(Snapshot $snapshot): void
    {
        if (!\function_exists('uopz_delete')) {
            throw new RuntimeException('The uopz_delete() function is required for this operation');
        }

        $functions = \get_defined_functions();

        foreach (\array_diff($functions['user'], $snapshot->functions()) as $function) {
            uopz_delete($function);
        }
    }

    /**
     * Restores all global and super-global variables from a snapshot.
     */
    public function restoreGlobalVariables(Snapshot $snapshot): void
    {
        $superGlobalArrays = $snapshot->superGlobalArrays();

        foreach ($superGlobalArrays as $superGlobalArray) {
            $this->restoreSuperGlobalArray($snapshot, $superGlobalArray);
        }

        $globalVariables = $snapshot->globalVariables();

        foreach (\array_keys($GLOBALS) as $key) {
            if ($key !== 'GLOBALS' &&
                !\in_array($key, $superGlobalArrays) &&
                !$snapshot->blacklist()->isGlobalVariableBlacklisted($key)) {
                if (\array_key_exists($key, $globalVariables)) {
                    $GLOBALS[$key] = $globalVariables[$key];
                } else {
                    unset($GLOBALS[$key]);
                }
            }
        }
    }

    /**
     * Restores all static attributes in user-defined classes from this snapshot.
     */
    public function restoreStaticAttributes(Snapshot $snapshot): void
    {
        $current    = new Snapshot($snapshot->blacklist(), false, false, false, false, true, false, false, false, false);
        $newClasses = \array_diff($current->classes(), $snapshot->classes());

        unset($current);

        foreach ($snapshot->staticAttributes() as $className => $staticAttributes) {
            foreach ($staticAttributes as $name => $value) {
                $reflector = new \ReflectionProperty($className, $name);
                $reflector->setAccessible(true);
                $reflector->setValue($value);
            }
        }

        foreach ($newClasses as $className) {
            $class    = new \ReflectionClass($className);
            $defaults = $class->getDefaultProperties();

            foreach ($class->getProperties() as $attribute) {
                if (!$attribute->isStatic()) {
                    continue;
                }

                $name = $attribute->getName();

                if ($snapshot->blacklist()->isStaticAttributeBlacklisted($className, $name)) {
                    continue;
                }

                if (!isset($defaults[$name])) {
                    continue;
                }

                $attribute->setAccessible(true);
                $attribute->setValue($defaults[$name]);
            }
        }
    }

    /**
     * Restores a super-global variable array from this snapshot.
     */
    private function restoreSuperGlobalArray(Snapshot $snapshot, string $superGlobalArray): void
    {
        $superGlobalVariables = $snapshot->superGlobalVariables();

        if (isset($GLOBALS[$superGlobalArray]) &&
            \is_array($GLOBALS[$superGlobalArray]) &&
            isset($superGlobalVariables[$superGlobalArray])) {
            $keys = \array_keys(
                \array_merge(
                    $GLOBALS[$superGlobalArray],
                    $superGlobalVariables[$superGlobalArray]
                )
            );

            foreach ($keys as $key) {
                if (isset($superGlobalVariables[$superGlobalArray][$key])) {
                    $GLOBALS[$superGlobalArray][$key] = $superGlobalVariables[$superGlobalArray][$key];
                } else {
                    unset($GLOBALS[$superGlobalArray][$key]);
                }
            }
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

/**
 * Exports parts of a Snapshot as PHP code.
 */
final class CodeExporter
{
    public function constants(Snapshot $snapshot): string
    {
        $result = '';

        foreach ($snapshot->constants() as $name => $value) {
            $result .= \sprintf(
                'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
                $name,
                $name,
                $this->exportVariable($value)
            );
        }

        return $result;
    }

    public function globalVariables(Snapshot $snapshot): string
    {
        $result = '$GLOBALS = [];' . \PHP_EOL;

        foreach ($snapshot->globalVariables() as $name => $value) {
            $result .= \sprintf(
                '$GLOBALS[%s] = %s;' . \PHP_EOL,
                $this->exportVariable($name),
                $this->exportVariable($value)
            );
        }

        return $result;
    }

    public function iniSettings(Snapshot $snapshot): string
    {
        $result = '';

        foreach ($snapshot->iniSettings() as $key => $value) {
            $result .= \sprintf(
                '@ini_set(%s, %s);' . "\n",
                $this->exportVariable($key),
                $this->exportVariable($value)
            );
        }

        return $result;
    }

    private function exportVariable($variable): string
    {
        if (\is_scalar($variable) || null === $variable ||
            (\is_array($variable) && $this->arrayOnlyContainsScalars($variable))) {
            return \var_export($variable, true);
        }

        return 'unserialize(' . \var_export(\serialize($variable), true) . ')';
    }

    private function arrayOnlyContainsScalars(array $array): bool
    {
        $result = true;

        foreach ($array as $element) {
            if (\is_array($element)) {
                $result = $this->arrayOnlyContainsScalars($element);
            } elseif (!\is_scalar($element) && null !== $element) {
                $result = false;
            }

            if ($result === false) {
                break;
            }
        }

        return $result;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

use SebastianBergmann\ObjectReflector\ObjectReflector;
use SebastianBergmann\RecursionContext\Context;

/**
 * A snapshot of global state.
 */
class Snapshot
{
    /**
     * @var Blacklist
     */
    private $blacklist;

    /**
     * @var array
     */
    private $globalVariables = [];

    /**
     * @var array
     */
    private $superGlobalArrays = [];

    /**
     * @var array
     */
    private $superGlobalVariables = [];

    /**
     * @var array
     */
    private $staticAttributes = [];

    /**
     * @var array
     */
    private $iniSettings = [];

    /**
     * @var array
     */
    private $includedFiles = [];

    /**
     * @var array
     */
    private $constants = [];

    /**
     * @var array
     */
    private $functions = [];

    /**
     * @var array
     */
    private $interfaces = [];

    /**
     * @var array
     */
    private $classes = [];

    /**
     * @var array
     */
    private $traits = [];

    /**
     * Creates a snapshot of the current global state.
     */
    public function __construct(Blacklist $blacklist = null, bool $includeGlobalVariables = true, bool $includeStaticAttributes = true, bool $includeConstants = true, bool $includeFunctions = true, bool $includeClasses = true, bool $includeInterfaces = true, bool $includeTraits = true, bool $includeIniSettings = true, bool $includeIncludedFiles = true)
    {
        if ($blacklist === null) {
            $blacklist = new Blacklist;
        }

        $this->blacklist = $blacklist;

        if ($includeConstants) {
            $this->snapshotConstants();
        }

        if ($includeFunctions) {
            $this->snapshotFunctions();
        }

        if ($includeClasses || $includeStaticAttributes) {
            $this->snapshotClasses();
        }

        if ($includeInterfaces) {
            $this->snapshotInterfaces();
        }

        if ($includeGlobalVariables) {
            $this->setupSuperGlobalArrays();
            $this->snapshotGlobals();
        }

        if ($includeStaticAttributes) {
            $this->snapshotStaticAttributes();
        }

        if ($includeIniSettings) {
            $this->iniSettings = \ini_get_all(null, false);
        }

        if ($includeIncludedFiles) {
            $this->includedFiles = \get_included_files();
        }

        if ($includeTraits) {
            $this->traits = \get_declared_traits();
        }
    }

    public function blacklist(): Blacklist
    {
        return $this->blacklist;
    }

    public function globalVariables(): array
    {
        return $this->globalVariables;
    }

    public function superGlobalVariables(): array
    {
        return $this->superGlobalVariables;
    }

    public function superGlobalArrays(): array
    {
        return $this->superGlobalArrays;
    }

    public function staticAttributes(): array
    {
        return $this->staticAttributes;
    }

    public function iniSettings(): array
    {
        return $this->iniSettings;
    }

    public function includedFiles(): array
    {
        return $this->includedFiles;
    }

    public function constants(): array
    {
        return $this->constants;
    }

    public function functions(): array
    {
        return $this->functions;
    }

    public function interfaces(): array
    {
        return $this->interfaces;
    }

    public function classes(): array
    {
        return $this->classes;
    }

    public function traits(): array
    {
        return $this->traits;
    }

    /**
     * Creates a snapshot user-defined constants.
     */
    private function snapshotConstants(): void
    {
        $constants = \get_defined_constants(true);

        if (isset($constants['user'])) {
            $this->constants = $constants['user'];
        }
    }

    /**
     * Creates a snapshot user-defined functions.
     */
    private function snapshotFunctions(): void
    {
        $functions = \get_defined_functions();

        $this->functions = $functions['user'];
    }

    /**
     * Creates a snapshot user-defined classes.
     */
    private function snapshotClasses(): void
    {
        foreach (\array_reverse(\get_declared_classes()) as $className) {
            $class = new \ReflectionClass($className);

            if (!$class->isUserDefined()) {
                break;
            }

            $this->classes[] = $className;
        }

        $this->classes = \array_reverse($this->classes);
    }

    /**
     * Creates a snapshot user-defined interfaces.
     */
    private function snapshotInterfaces(): void
    {
        foreach (\array_reverse(\get_declared_interfaces()) as $interfaceName) {
            $class = new \ReflectionClass($interfaceName);

            if (!$class->isUserDefined()) {
                break;
            }

            $this->interfaces[] = $interfaceName;
        }

        $this->interfaces = \array_reverse($this->interfaces);
    }

    /**
     * Creates a snapshot of all global and super-global variables.
     */
    private function snapshotGlobals(): void
    {
        $superGlobalArrays = $this->superGlobalArrays();

        foreach ($superGlobalArrays as $superGlobalArray) {
            $this->snapshotSuperGlobalArray($superGlobalArray);
        }

        foreach (\array_keys($GLOBALS) as $key) {
            if ($key !== 'GLOBALS' &&
                !\in_array($key, $superGlobalArrays) &&
                $this->canBeSerialized($GLOBALS[$key]) &&
                !$this->blacklist->isGlobalVariableBlacklisted($key)) {
                /* @noinspection UnserializeExploitsInspection */
                $this->globalVariables[$key] = \unserialize(\serialize($GLOBALS[$key]));
            }
        }
    }

    /**
     * Creates a snapshot a super-global variable array.
     */
    private function snapshotSuperGlobalArray(string $superGlobalArray): void
    {
        $this->superGlobalVariables[$superGlobalArray] = [];

        if (isset($GLOBALS[$superGlobalArray]) && \is_array($GLOBALS[$superGlobalArray])) {
            foreach ($GLOBALS[$superGlobalArray] as $key => $value) {
                /* @noinspection UnserializeExploitsInspection */
                $this->superGlobalVariables[$superGlobalArray][$key] = \unserialize(\serialize($value));
            }
        }
    }

    /**
     * Creates a snapshot of all static attributes in user-defined classes.
     */
    private function snapshotStaticAttributes(): void
    {
        foreach ($this->classes as $className) {
            $class    = new \ReflectionClass($className);
            $snapshot = [];

            foreach ($class->getProperties() as $attribute) {
                if ($attribute->isStatic()) {
                    $name = $attribute->getName();

                    if ($this->blacklist->isStaticAttributeBlacklisted($className, $name)) {
                        continue;
                    }

                    $attribute->setAccessible(true);
                    $value = $attribute->getValue();

                    if ($this->canBeSerialized($value)) {
                        /* @noinspection UnserializeExploitsInspection */
                        $snapshot[$name] = \unserialize(\serialize($value));
                    }
                }
            }

            if (!empty($snapshot)) {
                $this->staticAttributes[$className] = $snapshot;
            }
        }
    }

    /**
     * Returns a list of all super-global variable arrays.
     */
    private function setupSuperGlobalArrays(): void
    {
        $this->superGlobalArrays = [
            '_ENV',
            '_POST',
            '_GET',
            '_COOKIE',
            '_SERVER',
            '_FILES',
            '_REQUEST',
        ];
    }

    private function canBeSerialized($variable): bool
    {
        if (\is_scalar($variable) || $variable === null) {
            return true;
        }

        if (\is_resource($variable)) {
            return false;
        }

        foreach ($this->enumerateObjectsAndResources($variable) as $value) {
            if (\is_resource($value)) {
                return false;
            }

            if (\is_object($value)) {
                $class = new \ReflectionClass($value);

                if ($class->isAnonymous()) {
                    return false;
                }

                try {
                    @\serialize($value);
                } catch (\Throwable $t) {
                    return false;
                }
            }
        }

        return true;
    }

    private function enumerateObjectsAndResources($variable): array
    {
        if (isset(\func_get_args()[1])) {
            $processed = \func_get_args()[1];
        } else {
            $processed = new Context;
        }

        $result = [];

        if ($processed->contains($variable)) {
            return $result;
        }

        $array = $variable;
        $processed->add($variable);

        if (\is_array($variable)) {
            foreach ($array as $element) {
                if (!\is_array($element) && !\is_object($element) && !\is_resource($element)) {
                    continue;
                }

                if (!\is_resource($element)) {
                    /** @noinspection SlowArrayOperationsInLoopInspection */
                    $result = \array_merge(
                        $result,
                        $this->enumerateObjectsAndResources($element, $processed)
                    );
                } else {
                    $result[] = $element;
                }
            }
        } else {
            $result[] = $variable;

            foreach ((new ObjectReflector)->getAttributes($variable) as $value) {
                if (!\is_array($value) && !\is_object($value) && !\is_resource($value)) {
                    continue;
                }

                if (!\is_resource($value)) {
                    /** @noinspection SlowArrayOperationsInLoopInspection */
                    $result = \array_merge(
                        $result,
                        $this->enumerateObjectsAndResources($value, $processed)
                    );
                } else {
                    $result[] = $value;
                }
            }
        }

        return $result;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

/**
 * A blacklist for global state elements that should not be snapshotted.
 */
final class Blacklist
{
    /**
     * @var array
     */
    private $globalVariables = [];

    /**
     * @var string[]
     */
    private $classes = [];

    /**
     * @var string[]
     */
    private $classNamePrefixes = [];

    /**
     * @var string[]
     */
    private $parentClasses = [];

    /**
     * @var string[]
     */
    private $interfaces = [];

    /**
     * @var array
     */
    private $staticAttributes = [];

    public function addGlobalVariable(string $variableName): void
    {
        $this->globalVariables[$variableName] = true;
    }

    public function addClass(string $className): void
    {
        $this->classes[] = $className;
    }

    public function addSubclassesOf(string $className): void
    {
        $this->parentClasses[] = $className;
    }

    public function addImplementorsOf(string $interfaceName): void
    {
        $this->interfaces[] = $interfaceName;
    }

    public function addClassNamePrefix(string $classNamePrefix): void
    {
        $this->classNamePrefixes[] = $classNamePrefix;
    }

    public function addStaticAttribute(string $className, string $attributeName): void
    {
        if (!isset($this->staticAttributes[$className])) {
            $this->staticAttributes[$className] = [];
        }

        $this->staticAttributes[$className][$attributeName] = true;
    }

    public function isGlobalVariableBlacklisted(string $variableName): bool
    {
        return isset($this->globalVariables[$variableName]);
    }

    public function isStaticAttributeBlacklisted(string $className, string $attributeName): bool
    {
        if (\in_array($className, $this->classes)) {
            return true;
        }

        foreach ($this->classNamePrefixes as $prefix) {
            if (\strpos($className, $prefix) === 0) {
                return true;
            }
        }

        $class = new \ReflectionClass($className);

        foreach ($this->parentClasses as $type) {
            if ($class->isSubclassOf($type)) {
                return true;
            }
        }

        foreach ($this->interfaces as $type) {
            if ($class->implementsInterface($type)) {
                return true;
            }
        }

        if (isset($this->staticAttributes[$className][$attributeName])) {
            return true;
        }

        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

final class RuntimeException extends \RuntimeException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/global-state.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\GlobalState;

interface Exception
{
}
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->files()
    ->in('src')
    ->in('tests')
    ->name('*.php');

return Symfony\CS\Config\Config::create()
    ->level(\Symfony\CS\FixerInterface::NONE_LEVEL)
    ->fixers(
        array(
            'align_double_arrow',
            'align_equals',
            'braces',
            'concat_with_spaces',
            'duplicate_semicolon',
            'elseif',
            'empty_return',
            'encoding',
            'eof_ending',
            'extra_empty_lines',
            'function_call_space',
            'function_declaration',
            'indentation',
            'join_function',
            'line_after_namespace',
            'linefeed',
            'list_commas',
            'lowercase_constants',
            'lowercase_keywords',
            'method_argument_space',
            'multiple_use',
            'namespace_no_leading_whitespace',
            'no_blank_lines_after_class_opening',
            'no_empty_lines_after_phpdocs',
            'parenthesis',
            'php_closing_tag',
            'phpdoc_indent',
            'phpdoc_no_access',
            'phpdoc_no_empty_return',
            'phpdoc_no_package',
            'phpdoc_params',
            'phpdoc_scalar',
            'phpdoc_separation',
            'phpdoc_to_comment',
            'phpdoc_trim',
            'phpdoc_types',
            'phpdoc_var_without_name',
            'remove_lines_between_uses',
            'return',
            'self_accessor',
            'short_array_syntax',
            'short_tag',
            'single_line_after_imports',
            'single_quote',
            'spaces_before_semicolon',
            'spaces_cast',
            'ternary_spaces',
            'trailing_spaces',
            'trim_array_spaces',
            'unused_use',
            'visibility',
            'whitespacy_lines'
        )
    )
    ->finder($finder);

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/5.7/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         backupGlobals="false"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuite>
        <directory suffix="Test.php">tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
Object Enumerator

Copyright (c) 2016-2017, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Change Log

All notable changes to `sebastianbergmann/object-enumerator` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [3.0.4] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.0` to `>=7.0`

## [3.0.3] - 2017-08-03

### Changed

* Bumped required version of `sebastian/object-reflector`

## [3.0.2] - 2017-03-12

### Changed

* `sebastian/object-reflector` is now a dependency

## [3.0.1] - 2017-03-12

### Fixed

* Objects aggregated in inherited attributes are not enumerated

## [3.0.0] - 2017-03-03

### Removed

* This component is no longer supported on PHP 5.6

## [2.0.1] - 2017-02-18

### Fixed

* Fixed [#2](https://github.com/sebastianbergmann/phpunit/pull/2): Exceptions in `ReflectionProperty::getValue()` are not handled

## [2.0.0] - 2016-11-19

### Changed

* This component is now compatible with `sebastian/recursion-context: ~1.0.4`

## 1.0.0 - 2016-02-04

### Added

* Initial release

[3.0.4]: https://github.com/sebastianbergmann/object-enumerator/compare/3.0.3...3.0.4
[3.0.3]: https://github.com/sebastianbergmann/object-enumerator/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/sebastianbergmann/object-enumerator/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/object-enumerator/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/object-enumerator/compare/2.0...3.0.0
[2.0.1]: https://github.com/sebastianbergmann/object-enumerator/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/object-enumerator/compare/1.0...2.0.0

<?xml version="1.0" encoding="UTF-8"?>
<project name="object-enumerator" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
            <arg value="--optimize-autoloader"/>
            <arg value="--prefer-stable"/>
        </exec>
    </target>
</project>

<?php
/*
 * This file is part of Object Enumerator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\ObjectEnumerator;

use SebastianBergmann\ObjectEnumerator\Fixtures\ExceptionThrower;
use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\ObjectEnumerator\Enumerator
 */
class EnumeratorTest extends TestCase
{
    /**
     * @var Enumerator
     */
    private $enumerator;

    protected function setUp()
    {
        $this->enumerator = new Enumerator;
    }

    public function testEnumeratesSingleObject()
    {
        $a = new \stdClass;

        $objects = $this->enumerator->enumerate($a);

        $this->assertCount(1, $objects);
        $this->assertSame($a, $objects[0]);
    }

    public function testEnumeratesArrayWithSingleObject()
    {
        $a = new \stdClass;

        $objects = $this->enumerator->enumerate([$a]);

        $this->assertCount(1, $objects);
        $this->assertSame($a, $objects[0]);
    }

    public function testEnumeratesArrayWithTwoReferencesToTheSameObject()
    {
        $a = new \stdClass;

        $objects = $this->enumerator->enumerate([$a, $a]);

        $this->assertCount(1, $objects);
        $this->assertSame($a, $objects[0]);
    }

    public function testEnumeratesArrayOfObjects()
    {
        $a = new \stdClass;
        $b = new \stdClass;

        $objects = $this->enumerator->enumerate([$a, $b, null]);

        $this->assertCount(2, $objects);
        $this->assertSame($a, $objects[0]);
        $this->assertSame($b, $objects[1]);
    }

    public function testEnumeratesObjectWithAggregatedObject()
    {
        $a = new \stdClass;
        $b = new \stdClass;

        $a->b = $b;
        $a->c = null;

        $objects = $this->enumerator->enumerate($a);

        $this->assertCount(2, $objects);
        $this->assertSame($a, $objects[0]);
        $this->assertSame($b, $objects[1]);
    }

    public function testEnumeratesObjectWithAggregatedObjectsInArray()
    {
        $a = new \stdClass;
        $b = new \stdClass;

        $a->b = [$b];

        $objects = $this->enumerator->enumerate($a);

        $this->assertCount(2, $objects);
        $this->assertSame($a, $objects[0]);
        $this->assertSame($b, $objects[1]);
    }

    public function testEnumeratesObjectsWithCyclicReferences()
    {
        $a = new \stdClass;
        $b = new \stdClass;

        $a->b = $b;
        $b->a = $a;

        $objects = $this->enumerator->enumerate([$a, $b]);

        $this->assertCount(2, $objects);
        $this->assertSame($a, $objects[0]);
        $this->assertSame($b, $objects[1]);
    }

    public function testEnumeratesClassThatThrowsException()
    {
        $thrower = new ExceptionThrower();

        $objects = $this->enumerator->enumerate($thrower);

        $this->assertSame($thrower, $objects[0]);
    }

    public function testExceptionIsRaisedForInvalidArgument()
    {
        $this->expectException(InvalidArgumentException::class);

        $this->enumerator->enumerate(null);
    }

    public function testExceptionIsRaisedForInvalidArgument2()
    {
        $this->expectException(InvalidArgumentException::class);

        $this->enumerator->enumerate([], '');
    }
}
<?php
/*
 * This file is part of Object Enumerator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\ObjectEnumerator\Fixtures;

use RuntimeException;

class ExceptionThrower
{
    private $property;

    public function __construct()
    {
        unset($this->property);
    }

    public function __get($property)
    {
        throw new RuntimeException;
    }
}
# Object Enumerator

Traverses array structures and object graphs to enumerate all referenced objects.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/object-enumerator

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/object-enumerator

.idea
composer.lock
composer.phar
vendor/
cache.properties
build/LICENSE
build/README.md
build/*.tgz
language: php

php:
  - 7.0
  - 7.0snapshot
  - 7.1
  - 7.1snapshot
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "sebastian/object-enumerator",
    "description": "Traverses array structures and object graphs to enumerate all referenced objects",
    "homepage": "https://github.com/sebastianbergmann/object-enumerator/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "require": {
        "php": ">=7.0",
        "sebastian/object-reflector": "^1.1.1",
        "sebastian/recursion-context": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/_fixture/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.0.x-dev"
        }
    }
}
<?php
/*
 * This file is part of Object Enumerator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\ObjectEnumerator;

class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
/*
 * This file is part of Object Enumerator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\ObjectEnumerator;

use SebastianBergmann\ObjectReflector\ObjectReflector;
use SebastianBergmann\RecursionContext\Context;

/**
 * Traverses array structures and object graphs
 * to enumerate all referenced objects.
 */
class Enumerator
{
    /**
     * Returns an array of all objects referenced either
     * directly or indirectly by a variable.
     *
     * @param array|object $variable
     *
     * @return object[]
     */
    public function enumerate($variable)
    {
        if (!is_array($variable) && !is_object($variable)) {
            throw new InvalidArgumentException;
        }

        if (isset(func_get_args()[1])) {
            if (!func_get_args()[1] instanceof Context) {
                throw new InvalidArgumentException;
            }

            $processed = func_get_args()[1];
        } else {
            $processed = new Context;
        }

        $objects = [];

        if ($processed->contains($variable)) {
            return $objects;
        }

        $array = $variable;
        $processed->add($variable);

        if (is_array($variable)) {
            foreach ($array as $element) {
                if (!is_array($element) && !is_object($element)) {
                    continue;
                }

                $objects = array_merge(
                    $objects,
                    $this->enumerate($element, $processed)
                );
            }
        } else {
            $objects[] = $variable;

            $reflector = new ObjectReflector;

            foreach ($reflector->getAttributes($variable) as $value) {
                if (!is_array($value) && !is_object($value)) {
                    continue;
                }

                $objects = array_merge(
                    $objects,
                    $this->enumerate($value, $processed)
                );
            }
        }

        return $objects;
    }
}
<?php
/*
 * This file is part of Object Enumerator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\ObjectEnumerator;

interface Exception
{
}
<?php
$header = <<<'EOF'
This file is part of object-reflector.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'align_double_arrow' => true,
                'align_equals' => true
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_return' => true,
            'braces' => true,
            'cast_spaces' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_strict_types' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            #'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'line_ending' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'method_argument_space' => true,
            'no_alias_functions' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_closing_tag' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_consecutive_blank_lines' => true,
            'no_leading_namespace_whitespace' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_whitespace' => true,
            'no_unused_imports' => true,
            'no_whitespace_in_blank_line' => true,
            'phpdoc_align' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_types' => true,
            'phpdoc_var_without_name' => true,
            'self_accessor' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'ternary_operator_spaces' => true,
            'trim_array_spaces' => true,
            'visibility_required' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
        ->name('*.php')
    );
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuite>
        <directory suffix="Test.php">tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
Object Reflector

Copyright (c) 2017, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Change Log

All notable changes to `sebastianbergmann/object-reflector` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## 1.1.2 - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.0` to `>=7.1`

## 1.1.1 - 2017-03-29

* Fixed [#1](https://github.com/sebastianbergmann/object-reflector/issues/1): Attributes that with non-string names are not handled correctly

## 1.1.0 - 2017-03-16

### Changed

* Changed implementation of `ObjectReflector::getattributes()` to use `(array)` cast instead of `ReflectionObject`

## 1.0.0 - 2017-03-12

* Initial release

[1.1.2]: https://github.com/sebastianbergmann/object-enumerator/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/sebastianbergmann/object-enumerator/compare/1.1.0...1.1.1
[1.1.0]: https://github.com/sebastianbergmann/object-enumerator/compare/1.0.0...1.1.0
<?xml version="1.0" encoding="UTF-8"?>
<project name="object-reflector" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
            <arg value="--optimize-autoloader"/>
            <arg value="--prefer-stable"/>
        </exec>
    </target>
</project>

<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\ObjectReflector\TestFixture\ChildClass;
use SebastianBergmann\ObjectReflector\TestFixture\ClassWithIntegerAttributeName;

/**
 * @covers SebastianBergmann\ObjectReflector\ObjectReflector
 */
class ObjectReflectorTest extends TestCase
{
    /**
     * @var ObjectReflector
     */
    private $objectReflector;

    protected function setUp()/*: void */
    {
        $this->objectReflector = new ObjectReflector;
    }

    public function testReflectsAttributesOfObject()/*: void */
    {
        $o = new ChildClass;

        $this->assertEquals(
            [
                'privateInChild' => 'private',
                'protectedInChild' => 'protected',
                'publicInChild' => 'public',
                'undeclared' => 'undeclared',
                'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::privateInParent' => 'private',
                'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::protectedInParent' => 'protected',
                'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::publicInParent' => 'public',
            ],
            $this->objectReflector->getAttributes($o)
        );
    }

    public function testReflectsAttributeWithIntegerName()/*: void */
    {
        $o = new ClassWithIntegerAttributeName;

        $this->assertEquals(
            [
                1 => 2
            ],
            $this->objectReflector->getAttributes($o)
        );
    }

    public function testRaisesExceptionWhenPassedArgumentIsNotAnObject()/*: void */
    {
        $this->expectException(InvalidArgumentException::class);

        $this->objectReflector->getAttributes(null);
    }
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector\TestFixture;

class ClassWithIntegerAttributeName
{
    public function __construct()
    {
        $i        = 1;
        $this->$i = 2;
    }
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector\TestFixture;

class ChildClass extends ParentClass
{
    private $privateInChild = 'private';
    private $protectedInChild = 'protected';
    private $publicInChild = 'public';

    public function __construct()
    {
        $this->undeclared = 'undeclared';
    }
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector\TestFixture;

class ParentClass
{
    private $privateInParent = 'private';
    private $protectedInParent = 'protected';
    private $publicInParent = 'public';
}
# Object Reflector

Allows reflection of object attributes, including inherited and non-public ones.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/object-reflector

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/object-reflector

/.idea
/.php_cs.cache
/composer.lock
/vendor
language: php

php:
  - 7.0
  - 7.0snapshot
  - 7.1
  - 7.1snapshot
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "sebastian/object-reflector",
    "description": "Allows reflection of object attributes, including inherited and non-public ones",
    "homepage": "https://github.com/sebastianbergmann/object-reflector/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "require": {
        "php": ">=7.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/_fixture/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.1-dev"
        }
    }
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector;

class ObjectReflector
{
    /**
     * @param object $object
     *
     * @return array
     *
     * @throws InvalidArgumentException
     */
    public function getAttributes($object): array
    {
        if (!is_object($object)) {
            throw new InvalidArgumentException;
        }

        $attributes = [];
        $className  = get_class($object);

        foreach ((array) $object as $name => $value) {
            $name = explode("\0", (string) $name);

            if (count($name) === 1) {
                $name = $name[0];
            } else {
                if ($name[1] !== $className) {
                    $name = $name[1] . '::' . $name[2];
                } else {
                    $name = $name[2];
                }
            }

            $attributes[$name] = $value;
        }

        return $attributes;
    }
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector;

class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
/*
 * This file is part of object-reflector.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace SebastianBergmann\ObjectReflector;

interface Exception
{
}
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->files()
    ->in('src')
    ->in('tests')
    ->name('*.php');

return Symfony\CS\Config\Config::create()
    ->level(\Symfony\CS\FixerInterface::NONE_LEVEL)
    ->fixers(
        array(
            'align_double_arrow',
            'align_equals',
            'braces',
            'concat_with_spaces',
            'duplicate_semicolon',
            'elseif',
            'empty_return',
            'encoding',
            'eof_ending',
            'extra_empty_lines',
            'function_call_space',
            'function_declaration',
            'indentation',
            'join_function',
            'line_after_namespace',
            'linefeed',
            'list_commas',
            'lowercase_constants',
            'lowercase_keywords',
            'method_argument_space',
            'multiple_use',
            'namespace_no_leading_whitespace',
            'no_blank_lines_after_class_opening',
            'no_empty_lines_after_phpdocs',
            'parenthesis',
            'php_closing_tag',
            'phpdoc_indent',
            'phpdoc_no_access',
            'phpdoc_no_empty_return',
            'phpdoc_no_package',
            'phpdoc_params',
            'phpdoc_scalar',
            'phpdoc_separation',
            'phpdoc_to_comment',
            'phpdoc_trim',
            'phpdoc_types',
            'phpdoc_var_without_name',
            'remove_lines_between_uses',
            'return',
            'self_accessor',
            'short_array_syntax',
            'short_tag',
            'single_line_after_imports',
            'single_quote',
            'spaces_before_semicolon',
            'spaces_cast',
            'ternary_spaces',
            'trailing_spaces',
            'trim_array_spaces',
            'unused_use',
            'visibility',
            'whitespacy_lines'
        )
    )
    ->finder($finder);

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/5.4/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuite>
        <directory suffix="Test.php">tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
code-unit-reverse-lookup

Copyright (c) 2016-2017, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Change Log

All notable changes to `sebastianbergmann/code-unit-reverse-lookup` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [1.0.2] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^5.6 || ^7.0` to `>=5.6`

## 1.0.0 - 2016-02-13

* Initial release

[1.0.2]: https://github.com/sebastianbergmann/code-unit-reverse-lookup/compare/1.0.1...1.0.2
<?xml version="1.0" encoding="UTF-8"?>
<project name="code-unit-reverse-lookup" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
            <arg value="--optimize-autoloader"/>
            <arg value="--prefer-stable"/>
        </exec>
    </target>
</project>

<?php
/*
 * This file is part of code-unit-reverse-lookup.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\CodeUnitReverseLookup;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\CodeUnitReverseLookup\Wizard
 */
class WizardTest extends TestCase
{
    /**
     * @var Wizard
     */
    private $wizard;

    protected function setUp(): void
    {
        $this->wizard = new Wizard;
    }

    public function testMethodCanBeLookedUp()
    {
        $this->assertEquals(
            __METHOD__,
            $this->wizard->lookup(__FILE__, __LINE__)
        );
    }

    public function testReturnsFilenameAndLineNumberAsStringWhenNotInCodeUnit()
    {
        $this->assertEquals(
            'file.php:1',
            $this->wizard->lookup('file.php', 1)
        );
    }
}
# code-unit-reverse-lookup

Looks up which function or method a line of code belongs to.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/code-unit-reverse-lookup

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/code-unit-reverse-lookup

/.idea
/composer.lock
/vendor

language: php

php:
  - 5.6
  - 7.0
  - 7.0snapshot
  - 7.1
  - 7.1snapshot
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable

script:
  - ./vendor/bin/phpunit

notifications:
  email: false

{
    "name": "sebastian/code-unit-reverse-lookup",
    "description": "Looks up which function or method a line of code belongs to",
    "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "require": {
        "php": ">=5.6"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.5"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    }
}
<?php
/*
 * This file is part of code-unit-reverse-lookup.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\CodeUnitReverseLookup;

/**
 * @since Class available since Release 1.0.0
 */
class Wizard
{
    /**
     * @var array
     */
    private $lookupTable = [];

    /**
     * @var array
     */
    private $processedClasses = [];

    /**
     * @var array
     */
    private $processedFunctions = [];

    /**
     * @param string $filename
     * @param int    $lineNumber
     *
     * @return string
     */
    public function lookup($filename, $lineNumber)
    {
        if (!isset($this->lookupTable[$filename][$lineNumber])) {
            $this->updateLookupTable();
        }

        if (isset($this->lookupTable[$filename][$lineNumber])) {
            return $this->lookupTable[$filename][$lineNumber];
        } else {
            return $filename . ':' . $lineNumber;
        }
    }

    private function updateLookupTable()
    {
        $this->processClassesAndTraits();
        $this->processFunctions();
    }

    private function processClassesAndTraits()
    {
        foreach (array_merge(get_declared_classes(), get_declared_traits()) as $classOrTrait) {
            if (isset($this->processedClasses[$classOrTrait])) {
                continue;
            }

            $reflector = new \ReflectionClass($classOrTrait);

            foreach ($reflector->getMethods() as $method) {
                $this->processFunctionOrMethod($method);
            }

            $this->processedClasses[$classOrTrait] = true;
        }
    }

    private function processFunctions()
    {
        foreach (get_defined_functions()['user'] as $function) {
            if (isset($this->processedFunctions[$function])) {
                continue;
            }

            $this->processFunctionOrMethod(new \ReflectionFunction($function));

            $this->processedFunctions[$function] = true;
        }
    }

    /**
     * @param \ReflectionFunctionAbstract $functionOrMethod
     */
    private function processFunctionOrMethod(\ReflectionFunctionAbstract $functionOrMethod)
    {
        if ($functionOrMethod->isInternal()) {
            return;
        }

        $name = $functionOrMethod->getName();

        if ($functionOrMethod instanceof \ReflectionMethod) {
            $name = $functionOrMethod->getDeclaringClass()->getName() . '::' . $name;
        }

        if (!isset($this->lookupTable[$functionOrMethod->getFileName()])) {
            $this->lookupTable[$functionOrMethod->getFileName()] = [];
        }

        foreach (range($functionOrMethod->getStartLine(), $functionOrMethod->getEndLine()) as $line) {
            $this->lookupTable[$functionOrMethod->getFileName()][$line] = $name;
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.2/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
sebastian/diff

Copyright (c) 2002-2019, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [3.0.3] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [3.0.2] - 2019-02-04

### Changed

* `Chunk::setLines()` now ensures that the `$lines` array only contains `Line` objects

## [3.0.1] - 2018-06-10

### Fixed

* Removed `"minimum-stability": "dev",` from `composer.json`

## [3.0.0] - 2018-02-01

* The `StrictUnifiedDiffOutputBuilder` implementation of the `DiffOutputBuilderInterface` was added

### Changed

* The default `DiffOutputBuilderInterface` implementation now generates context lines (unchanged lines)

### Removed

* Removed support for PHP 7.0

### Fixed

* Fixed [#70](https://github.com/sebastianbergmann/diff/issues/70): Diffing of arrays no longer works

## [2.0.1] - 2017-08-03

### Fixed

* Fixed [#66](https://github.com/sebastianbergmann/diff/pull/66): Restored backwards compatibility for PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3

## [2.0.0] - 2017-07-11 [YANKED]

### Added

* Implemented [#64](https://github.com/sebastianbergmann/diff/pull/64): Show line numbers for chunks of a diff

### Removed

* This component is no longer supported on PHP 5.6

[3.0.3]: https://github.com/sebastianbergmann/diff/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/sebastianbergmann/diff/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/diff/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/diff/compare/2.0...3.0.0
[2.0.1]: https://github.com/sebastianbergmann/diff/compare/c341c98ce083db77f896a0aa64f5ee7652915970...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.4...c341c98ce083db77f896a0aa64f5ee7652915970
<?xml version="1.0" encoding="UTF-8"?>
<project name="diff" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
            <arg value="--optimize-autoloader"/>
            <arg value="--prefer-stable"/>
        </exec>
    </target>
</project>

<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\Diff
 *
 * @uses SebastianBergmann\Diff\Chunk
 */
final class DiffTest extends TestCase
{
    public function testGettersAfterConstructionWithDefault(): void
    {
        $from = 'line1a';
        $to   = 'line2a';
        $diff = new Diff($from, $to);

        $this->assertSame($from, $diff->getFrom());
        $this->assertSame($to, $diff->getTo());
        $this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');
    }

    public function testGettersAfterConstructionWithChunks(): void
    {
        $from   = 'line1b';
        $to     = 'line2b';
        $chunks = [new Chunk(), new Chunk(2, 3)];

        $diff = new Diff($from, $to, $chunks);

        $this->assertSame($from, $diff->getFrom());
        $this->assertSame($to, $diff->getTo());
        $this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.');
    }

    public function testSetChunksAfterConstruction(): void
    {
        $diff = new Diff('line1c', 'line2c');
        $this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');

        $chunks = [new Chunk(), new Chunk(2, 3)];
        $diff->setChunks($chunks);
        $this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.');
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;

/**
 * @covers SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 * @uses SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 */
final class AbstractChunkOutputBuilderTest extends TestCase
{
    /**
     * @param array  $expected
     * @param string $from
     * @param string $to
     * @param int    $lineThreshold
     *
     * @dataProvider provideGetCommonChunks
     */
    public function testGetCommonChunks(array $expected, string $from, string $to, int $lineThreshold = 5): void
    {
        $output = new class extends AbstractChunkOutputBuilder {
            public function getDiff(array $diff): string
            {
                return '';
            }

            public function getChunks(array $diff, $lineThreshold)
            {
                return $this->getCommonChunks($diff, $lineThreshold);
            }
        };

        $this->assertSame(
            $expected,
            $output->getChunks((new Differ)->diffToArray($from, $to), $lineThreshold)
        );
    }

    public function provideGetCommonChunks(): array
    {
        return[
            'same (with default threshold)' => [
                [],
                'A',
                'A',
            ],
            'same (threshold 0)' => [
                [0 => 0],
                'A',
                'A',
                0,
            ],
            'empty' => [
                [],
                '',
                '',
            ],
            'single line diff' => [
                [],
                'A',
                'B',
            ],
            'below threshold I' => [
                [],
                "A\nX\nC",
                "A\nB\nC",
            ],
            'below threshold II' => [
                [],
                "A\n\n\n\nX\nC",
                "A\n\n\n\nB\nC",
            ],
            'below threshold III' => [
                [0 => 5],
                "A\n\n\n\n\n\nB",
                "A\n\n\n\n\n\nA",
            ],
            'same start' => [
                [0 => 5],
                "A\n\n\n\n\n\nX\nC",
                "A\n\n\n\n\n\nB\nC",
            ],
            'same start long' => [
                [0 => 13],
                "\n\n\n\n\n\n\n\n\n\n\n\n\n\nA",
                "\n\n\n\n\n\n\n\n\n\n\n\n\n\nB",
            ],
            'same part in between' => [
                [2 => 8],
                "A\n\n\n\n\n\n\nX\nY\nZ\n\n",
                "B\n\n\n\n\n\n\nX\nA\nZ\n\n",
            ],
            'same trailing' => [
                [2 => 14],
                "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
                "B\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
            ],
            'same part in between, same trailing' => [
                [2 => 7, 10 => 15],
                "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\n",
                "B\n\n\n\n\n\n\nB\n\n\n\n\n\n\n",
            ],
            'below custom threshold I' => [
                [],
                "A\n\nB",
                "A\n\nD",
                2,
            ],
            'custom threshold I' => [
                [0 => 1],
                "A\n\nB",
                "A\n\nD",
                1,
            ],
            'custom threshold II' => [
                [],
                "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
                "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
                19,
            ],
            [
                [3 => 9],
                "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk",
                "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk",
            ],
            [
                [0 => 5, 8 => 13],
                "A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC",
                "A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC",
            ],
            [
                [0 => 5, 8 => 13],
                "A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC\nX",
                "A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC\nY",
            ],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;

/**
 * @covers SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 */
final class DiffOnlyOutputBuilderTest extends TestCase
{
    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param string $header
     *
     * @dataProvider textForNoNonDiffLinesProvider
     */
    public function testDiffDoNotShowNonDiffLines(string $expected, string $from, string $to, string $header = ''): void
    {
        $differ = new Differ(new DiffOnlyOutputBuilder($header));

        $this->assertSame($expected, $differ->diff($from, $to));
    }

    public function textForNoNonDiffLinesProvider(): array
    {
        return [
            [
                " #Warning: Strings contain different line endings!\n-A\r\n+B\n",
                "A\r\n",
                "B\n",
            ],
            [
                "-A\n+B\n",
                "\nA",
                "\nB",
            ],
            [
                '',
                'a',
                'a',
            ],
            [
                "-A\n+C\n",
                "A\n\n\nB",
                "C\n\n\nB",
            ],
            [
                "header\n",
                'a',
                'a',
                'header',
            ],
            [
                "header\n",
                'a',
                'a',
                "header\n",
            ],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\ConfigurationException;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;

/**
 * @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 */
final class StrictUnifiedDiffOutputBuilderTest extends TestCase
{
    use UnifiedDiffAssertTrait;

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param array  $options
     *
     * @dataProvider provideOutputBuildingCases
     */
    public function testOutputBuilding(string $expected, string $from, string $to, array $options): void
    {
        $diff = $this->getDiffer($options)->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param array  $options
     *
     * @dataProvider provideSample
     */
    public function testSample(string $expected, string $from, string $to, array $options): void
    {
        $diff = $this->getDiffer($options)->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    /**
     * {@inheritdoc}
     */
    public function assertValidDiffFormat(string $diff): void
    {
        $this->assertValidUnifiedDiffFormat($diff);
    }

    /**
     * {@inheritdoc}
     */
    public function provideOutputBuildingCases(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
    }

    /**
     * {@inheritdoc}
     */
    public function provideSample(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider provideBasicDiffGeneration
     */
    public function testBasicDiffGeneration(string $expected, string $from, string $to): void
    {
        $diff = $this->getDiffer([
            'fromFile' => 'input.txt',
            'toFile'   => 'output.txt',
        ])->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    public function provideBasicDiffGeneration(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param array  $config
     *
     * @dataProvider provideConfiguredDiffGeneration
     */
    public function testConfiguredDiffGeneration(string $expected, string $from, string $to, array $config = []): void
    {
        $diff = $this->getDiffer(\array_merge([
            'fromFile' => 'input.txt',
            'toFile'   => 'output.txt',
        ], $config))->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    public function provideConfiguredDiffGeneration(): array
    {
        return [
            [
                '--- input.txt
+++ output.txt
@@ -1 +1 @@
-a
\ No newline at end of file
+b
\ No newline at end of file
',
                'a',
                'b',
            ],
            [
                '',
                "1\n2",
                "1\n2",
            ],
            [
                '',
                "1\n",
                "1\n",
            ],
            [
'--- input.txt
+++ output.txt
@@ -4 +4 @@
-X
+4
',
                "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
                "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
                [
                    'contextLines' => 0,
                ],
            ],
            [
'--- input.txt
+++ output.txt
@@ -3,3 +3,3 @@
 3
-X
+4
 5
',
                "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
                "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
                [
                    'contextLines' => 1,
                ],
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,10 +1,10 @@
 1
 2
 3
-X
+4
 5
 6
 7
 8
 9
 0
',
                "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
                "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
                [
                    'contextLines' => 999,
                ],
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,0 +1,2 @@
+
+A
',
                '',
                "\nA\n",
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,2 +1,0 @@
-
-A
',
                "\nA\n",
                '',
            ],
            [
                '--- input.txt
+++ output.txt
@@ -1,5 +1,5 @@
 1
-X
+2
 3
-Y
+4
 5
@@ -8,3 +8,3 @@
 8
-X
+9
 0
',
                "1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
                "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
                [
                    'commonLineThreshold' => 2,
                    'contextLines'        => 1,
                ],
            ],
            [
                '--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+2
@@ -4 +4 @@
-Y
+4
@@ -9 +9 @@
-X
+9
',
                "1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
                "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
                [
                    'commonLineThreshold' => 1,
                    'contextLines'        => 0,
                ],
            ],
        ];
    }

    public function testReUseBuilder(): void
    {
        $differ = $this->getDiffer([
            'fromFile' => 'input.txt',
            'toFile'   => 'output.txt',
        ]);

        $diff = $differ->diff("A\nB\n", "A\nX\n");
        $this->assertSame(
'--- input.txt
+++ output.txt
@@ -1,2 +1,2 @@
 A
-B
+X
',
            $diff
        );

        $diff = $differ->diff("A\n", "A\n");
        $this->assertSame(
            '',
            $diff
        );
    }

    public function testEmptyDiff(): void
    {
        $builder = new StrictUnifiedDiffOutputBuilder([
            'fromFile' => 'input.txt',
            'toFile'   => 'output.txt',
        ]);

        $this->assertSame(
            '',
            $builder->getDiff([])
        );
    }

    /**
     * @param array  $options
     * @param string $message
     *
     * @dataProvider provideInvalidConfiguration
     */
    public function testInvalidConfiguration(array $options, string $message): void
    {
        $this->expectException(ConfigurationException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote($message, '#')));

        new StrictUnifiedDiffOutputBuilder($options);
    }

    public function provideInvalidConfiguration(): array
    {
        $time = \time();

        return [
            [
                ['collapseRanges' => 1],
                'Option "collapseRanges" must be a bool, got "integer#1".',
            ],
            [
                ['contextLines' => 'a'],
                'Option "contextLines" must be an int >= 0, got "string#a".',
            ],
            [
                ['commonLineThreshold' => -2],
                'Option "commonLineThreshold" must be an int > 0, got "integer#-2".',
            ],
            [
                ['commonLineThreshold' => 0],
                'Option "commonLineThreshold" must be an int > 0, got "integer#0".',
            ],
            [
                ['fromFile' => new \SplFileInfo(__FILE__)],
                'Option "fromFile" must be a string, got "SplFileInfo".',
            ],
            [
                ['fromFile' => null],
                'Option "fromFile" must be a string, got "<null>".',
            ],
            [
                [
                    'fromFile' => __FILE__,
                    'toFile'   => 1,
                ],
                'Option "toFile" must be a string, got "integer#1".',
            ],
            [
                [
                    'fromFile'   => __FILE__,
                    'toFile'     => __FILE__,
                    'toFileDate' => $time,
                ],
                'Option "toFileDate" must be a string or <null>, got "integer#' . $time . '".',
            ],
            [
                [],
                'Option "fromFile" must be a string, got "<null>".',
            ],
        ];
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param int    $threshold
     *
     * @dataProvider provideCommonLineThresholdCases
     */
    public function testCommonLineThreshold(string $expected, string $from, string $to, int $threshold): void
    {
        $diff = $this->getDiffer([
            'fromFile'            => 'input.txt',
            'toFile'              => 'output.txt',
            'commonLineThreshold' => $threshold,
            'contextLines'        => 0,
        ])->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    public function provideCommonLineThresholdCases(): array
    {
        return [
            [
'--- input.txt
+++ output.txt
@@ -2,3 +2,3 @@
-X
+B
 C12
-Y
+D
@@ -7 +7 @@
-X
+Z
',
                "A\nX\nC12\nY\nA\nA\nX\n",
                "A\nB\nC12\nD\nA\nA\nZ\n",
                2,
            ],
            [
'--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+B
@@ -4 +4 @@
-Y
+D
',
                "A\nX\nV\nY\n",
                "A\nB\nV\nD\n",
                1,
            ],
        ];
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param int    $contextLines
     * @param int    $commonLineThreshold
     *
     * @dataProvider provideContextLineConfigurationCases
     */
    public function testContextLineConfiguration(string $expected, string $from, string $to, int $contextLines, int $commonLineThreshold = 6): void
    {
        $diff = $this->getDiffer([
            'fromFile'            => 'input.txt',
            'toFile'              => 'output.txt',
            'contextLines'        => $contextLines,
            'commonLineThreshold' => $commonLineThreshold,
        ])->diff($from, $to);

        $this->assertValidDiffFormat($diff);
        $this->assertSame($expected, $diff);
    }

    public function provideContextLineConfigurationCases(): array
    {
        $from = "A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n";
        $to   = "A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n";

        return [
            'EOF 0' => [
                "--- input.txt\n+++ output.txt\n@@ -3 +3 @@
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
                "A\nB\nX",
                "A\nB\nY",
                0,
            ],
            'EOF 1' => [
                "--- input.txt\n+++ output.txt\n@@ -2,2 +2,2 @@
 B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
                "A\nB\nX",
                "A\nB\nY",
                1,
],
            'EOF 2' => [
                "--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
 A
 B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
                "A\nB\nX",
                "A\nB\nY",
                2,
            ],
            'EOF 200' => [
                "--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
 A
 B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
                "A\nB\nX",
                "A\nB\nY",
                200,
            ],
            'n/a 0' => [
                "--- input.txt\n+++ output.txt\n@@ -7 +7 @@\n-X\n+Y\n",
                $from,
                $to,
                0,
            ],
            'G' => [
                "--- input.txt\n+++ output.txt\n@@ -6,3 +6,3 @@\n F\n-X\n+Y\n G\n",
                $from,
                $to,
                1,
            ],
            'H' => [
                "--- input.txt\n+++ output.txt\n@@ -5,5 +5,5 @@\n E\n F\n-X\n+Y\n G\n H\n",
                $from,
                $to,
                2,
            ],
            'I' => [
                "--- input.txt\n+++ output.txt\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
                $from,
                $to,
                3,
            ],
            'J' => [
                "--- input.txt\n+++ output.txt\n@@ -3,9 +3,9 @@\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n",
                $from,
                $to,
                4,
            ],
            'K' => [
                "--- input.txt\n+++ output.txt\n@@ -2,11 +2,11 @@\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n",
                $from,
                $to,
                5,
            ],
            'L' => [
                "--- input.txt\n+++ output.txt\n@@ -1,13 +1,13 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n",
                $from,
                $to,
                6,
            ],
            'M' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
                $from,
                $to,
                7,
            ],
            'M no linebreak EOF .1' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n+M\n\\ No newline at end of file\n",
                $from,
                \substr($to, 0, -1),
                7,
            ],
            'M no linebreak EOF .2' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n\\ No newline at end of file\n+M\n",
                \substr($from, 0, -1),
                $to,
                7,
            ],
            'M no linebreak EOF .3' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
                \substr($from, 0, -1),
                \substr($to, 0, -1),
                7,
            ],
            'M no linebreak EOF .4' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n\\ No newline at end of file\n",
                \substr($from, 0, -1),
                \substr($to, 0, -1),
                10000,
                10000,
            ],
            'M+1' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
                $from,
                $to,
                8,
            ],
            'M+100' => [
                "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
                $from,
                $to,
                107,
            ],
            '0 II' => [
                "--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
                0,
                999,
            ],
            '0\' II' => [
                "--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\nA\nA\nA\nA\nA\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\nA\nA\nA\nA\nA\n",
                0,
                999,
            ],
            '0\'\' II' => [
                "--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-M\n\\ No newline at end of file\n+Y\n+M\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
                0,
            ],
            '0\'\'\' II' => [
                "--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-X1\n+Y\n+Y2\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nX1\nM\nA\nA\nA\nA\nA\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nY2\nM\nA\nA\nA\nA\nA\n",
                0,
                999,
            ],
            '1 II' => [
                "--- input.txt\n+++ output.txt\n@@ -11,3 +11,3 @@\n K\n-X\n+Y\n M\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
                1,
            ],
            '5 II' => [
                "--- input.txt\n+++ output.txt\n@@ -7,7 +7,7 @@\n G\n H\n I\n J\n K\n-X\n+Y\n M\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
                "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
                5,
            ],
            [
                '--- input.txt
+++ output.txt
@@ -1,28 +1,28 @@
 A
-X
+B
 V
-Y
+D
 1
 A
 2
 A
 3
 A
 4
 A
 8
 A
 9
 A
 5
 A
 A
 A
 A
 A
 A
 A
 A
 A
 A
 A
',
                "A\nX\nV\nY\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
                "A\nB\nV\nD\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
                9999,
                99999,
            ],
        ];
    }

    /**
     * Returns a new instance of a Differ with a new instance of the class (DiffOutputBuilderInterface) under test.
     *
     * @param array $options
     *
     * @return Differ
     */
    private function getDiffer(array $options = []): Differ
    {
        return new Differ(new StrictUnifiedDiffOutputBuilder($options));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

final class StrictUnifiedDiffOutputBuilderDataProvider
{
    public static function provideOutputBuildingCases(): array
    {
        return [
            [
'--- input.txt
+++ output.txt
@@ -1,3 +1,4 @@
+b
 ' . '
 ' . '
 ' . '
@@ -16,5 +17,4 @@
 ' . '
 ' . '
 ' . '
-
-B
+A
',
                "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nB\n",
                "b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nA\n",
                [
                    'fromFile' => 'input.txt',
                    'toFile'   => 'output.txt',
                ],
            ],
            [
'--- ' . __FILE__ . "\t2017-10-02 17:38:11.586413675 +0100
+++ output1.txt\t2017-10-03 12:09:43.086719482 +0100
@@ -1,1 +1,1 @@
-B
+X
",
                "B\n",
                "X\n",
                [
                    'fromFile'       => __FILE__,
                    'fromFileDate'   => '2017-10-02 17:38:11.586413675 +0100',
                    'toFile'         => 'output1.txt',
                    'toFileDate'     => '2017-10-03 12:09:43.086719482 +0100',
                    'collapseRanges' => false,
                ],
            ],
            [
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-B
+X
',
                "B\n",
                "X\n",
                [
                    'fromFile'       => 'input.txt',
                    'toFile'         => 'output.txt',
                    'collapseRanges' => true,
                ],
            ],
        ];
    }

    public static function provideSample(): array
    {
        return [
            [
'--- input.txt
+++ output.txt
@@ -1,6 +1,6 @@
 1
 2
 3
-4
+X
 5
 6
',
                "1\n2\n3\n4\n5\n6\n",
                "1\n2\n3\nX\n5\n6\n",
                [
                    'fromFile' => 'input.txt',
                    'toFile'   => 'output.txt',
                ],
            ],
        ];
    }

    public static function provideBasicDiffGeneration(): array
    {
        return [
            [
"--- input.txt
+++ output.txt
@@ -1,2 +1 @@
-A
-B
+A\rB
",
                "A\nB\n",
                "A\rB\n",
            ],
            [
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-
+\r
\\ No newline at end of file
",
                "\n",
                "\r",
            ],
            [
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-\r
\\ No newline at end of file
+
",
                "\r",
                "\n",
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
 X
 A
-A
+B
',
                "X\nA\nA\n",
                "X\nA\nB\n",
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
 X
 A
-A
\ No newline at end of file
+B
',
                "X\nA\nA",
                "X\nA\nB\n",
            ],
            [
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
 A
 A
-A
+B
\ No newline at end of file
',
                "A\nA\nA\n",
                "A\nA\nB",
            ],
            [
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-A
\ No newline at end of file
+B
\ No newline at end of file
',
                'A',
                'B',
            ],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;

/**
 * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 *
 * @requires OS Linux
 */
final class UnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
    use UnifiedDiffAssertTrait;

    private $dir;

    private $fileFrom;

    private $filePatch;

    protected function setUp(): void
    {
        $this->dir       = \realpath(__DIR__ . '/../../fixtures/out/') . '/';
        $this->fileFrom  = $this->dir . 'from.txt';
        $this->filePatch = $this->dir . 'patch.txt';

        $this->cleanUpTempFiles();
    }

    protected function tearDown(): void
    {
        $this->cleanUpTempFiles();
    }

    /**
     * @dataProvider provideDiffWithLineNumbers
     *
     * @param mixed $expected
     * @param mixed $from
     * @param mixed $to
     */
    public function testDiffWithLineNumbersPath($expected, $from, $to): void
    {
        $this->doIntegrationTestPatch($expected, $from, $to);
    }

    /**
     * @dataProvider provideDiffWithLineNumbers
     *
     * @param mixed $expected
     * @param mixed $from
     * @param mixed $to
     */
    public function testDiffWithLineNumbersGitApply($expected, $from, $to): void
    {
        $this->doIntegrationTestGitApply($expected, $from, $to);
    }

    public function provideDiffWithLineNumbers()
    {
        return \array_filter(
            UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers(),
            static function ($key) {
                return !\is_string($key) || false === \strpos($key, 'non_patch_compat');
            },
            ARRAY_FILTER_USE_KEY
        );
    }

    private function doIntegrationTestPatch(string $diff, string $from, string $to): void
    {
        $this->assertNotSame('', $diff);
        $this->assertValidUnifiedDiffFormat($diff);

        $diff = self::setDiffFileHeader($diff, $this->fileFrom);

        $this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
        $this->assertNotFalse(\file_put_contents($this->filePatch, $diff));

        $command = \sprintf(
            'patch -u --verbose --posix  %s < %s', // --posix
            \escapeshellarg($this->fileFrom),
            \escapeshellarg($this->filePatch)
        );

        $p = new Process($command);
        $p->run();

        $this->assertProcessSuccessful($p);

        $this->assertStringEqualsFile(
            $this->fileFrom,
            $to,
            \sprintf('Patch command "%s".', $command)
        );
    }

    private function doIntegrationTestGitApply(string $diff, string $from, string $to): void
    {
        $this->assertNotSame('', $diff);
        $this->assertValidUnifiedDiffFormat($diff);

        $diff = self::setDiffFileHeader($diff, $this->fileFrom);

        $this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
        $this->assertNotFalse(\file_put_contents($this->filePatch, $diff));

        $command = \sprintf(
            'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
            \escapeshellarg($this->dir),
            \escapeshellarg($this->filePatch)
        );

        $p = new Process($command);
        $p->run();

        $this->assertProcessSuccessful($p);
    }

    private function assertProcessSuccessful(Process $p): void
    {
        $this->assertTrue(
            $p->isSuccessful(),
            \sprintf(
                "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
                $p->getCommandLine(),
                $p->getOutput(),
                $p->getErrorOutput(),
                $p->getExitCode()
            )
        );
    }

    private function cleanUpTempFiles(): void
    {
        @\unlink($this->fileFrom . '.orig');
        @\unlink($this->fileFrom);
        @\unlink($this->filePatch);
    }

    private static function setDiffFileHeader(string $diff, string $file): string
    {
        $diffLines    = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
        $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);

        return \implode('', $diffLines);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\FileUtils;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;

/**
 * @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 *
 * @requires OS Linux
 */
final class StrictUnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
    use UnifiedDiffAssertTrait;

    private $dir;

    private $fileFrom;

    private $fileTo;

    private $filePatch;

    protected function setUp(): void
    {
        $this->dir       = \realpath(__DIR__ . '/../../fixtures/out') . '/';
        $this->fileFrom  = $this->dir . 'from.txt';
        $this->fileTo    = $this->dir . 'to.txt';
        $this->filePatch = $this->dir . 'diff.patch';

        if (!\is_dir($this->dir)) {
            throw new \RuntimeException('Integration test working directory not found.');
        }

        $this->cleanUpTempFiles();
    }

    protected function tearDown(): void
    {
        $this->cleanUpTempFiles();
    }

    /**
     * Integration test
     *
     * - get a file pair
     * - create a `diff` between the files
     * - test applying the diff using `git apply`
     * - test applying the diff using `patch`
     *
     * @param string $fileFrom
     * @param string $fileTo
     *
     * @dataProvider provideFilePairs
     */
    public function testIntegrationUsingPHPFileInVendorGitApply(string $fileFrom, string $fileTo): void
    {
        $from = FileUtils::getFileContent($fileFrom);
        $to   = FileUtils::getFileContent($fileTo);

        $diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);

        if ('' === $diff && $from === $to) {
            // odd case: test after executing as it is more efficient than to read the files and check the contents every time
            $this->addToAssertionCount(1);

            return;
        }

        $this->doIntegrationTestGitApply($diff, $from, $to);
    }

    /**
     * Integration test
     *
     * - get a file pair
     * - create a `diff` between the files
     * - test applying the diff using `git apply`
     * - test applying the diff using `patch`
     *
     * @param string $fileFrom
     * @param string $fileTo
     *
     * @dataProvider provideFilePairs
     */
    public function testIntegrationUsingPHPFileInVendorPatch(string $fileFrom, string $fileTo): void
    {
        $from = FileUtils::getFileContent($fileFrom);
        $to   = FileUtils::getFileContent($fileTo);

        $diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);

        if ('' === $diff && $from === $to) {
            // odd case: test after executing as it is more efficient than to read the files and check the contents every time
            $this->addToAssertionCount(1);

            return;
        }

        $this->doIntegrationTestPatch($diff, $from, $to);
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider provideOutputBuildingCases
     * @dataProvider provideSample
     * @dataProvider provideBasicDiffGeneration
     */
    public function testIntegrationOfUnitTestCasesGitApply(string $expected, string $from, string $to): void
    {
        $this->doIntegrationTestGitApply($expected, $from, $to);
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider provideOutputBuildingCases
     * @dataProvider provideSample
     * @dataProvider provideBasicDiffGeneration
     */
    public function testIntegrationOfUnitTestCasesPatch(string $expected, string $from, string $to): void
    {
        $this->doIntegrationTestPatch($expected, $from, $to);
    }

    public function provideOutputBuildingCases(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
    }

    public function provideSample(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
    }

    public function provideBasicDiffGeneration(): array
    {
        return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
    }

    public function provideFilePairs(): array
    {
        $cases     = [];
        $fromFile  = __FILE__;
        $vendorDir = \realpath(__DIR__ . '/../../../vendor');

        $fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($vendorDir, \RecursiveDirectoryIterator::SKIP_DOTS));

        /** @var \SplFileInfo $file */
        foreach ($fileIterator as $file) {
            if ('php' !== $file->getExtension()) {
                continue;
            }

            $toFile                                                                                         = $file->getPathname();
            $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \realpath($fromFile), \realpath($toFile))] = [$fromFile, $toFile];
            $fromFile                                                                                       = $toFile;
        }

        return $cases;
    }

    /**
     * Compare diff create by builder and against one create by `diff` command.
     *
     * @param string $diff
     * @param string $from
     * @param string $to
     *
     * @dataProvider provideBasicDiffGeneration
     */
    public function testIntegrationDiffOutputBuilderVersusDiffCommand(string $diff, string $from, string $to): void
    {
        $this->assertNotSame('', $diff);
        $this->assertValidUnifiedDiffFormat($diff);

        $this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
        $this->assertNotFalse(\file_put_contents($this->fileTo, $to));

        $p = new Process(\sprintf('diff -u %s %s', \escapeshellarg($this->fileFrom), \escapeshellarg($this->fileTo)));
        $p->run();
        $this->assertSame(1, $p->getExitCode()); // note: Process assumes exit code 0 for `isSuccessful`, however `diff` uses the exit code `1` for success with diff

        $output = $p->getOutput();

        $diffLines    = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $diffLines[0], 1);
        $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $diffLines[1], 1);
        $diff         = \implode('', $diffLines);

        $outputLines    = \preg_split('/(.*\R)/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $outputLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $outputLines[0], 1);
        $outputLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $outputLines[1], 1);
        $output         = \implode('', $outputLines);

        $this->assertSame($diff, $output);
    }

    private function doIntegrationTestGitApply(string $diff, string $from, string $to): void
    {
        $this->assertNotSame('', $diff);
        $this->assertValidUnifiedDiffFormat($diff);

        $diff = self::setDiffFileHeader($diff, $this->fileFrom);

        $this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
        $this->assertNotFalse(\file_put_contents($this->filePatch, $diff));

        $p = new Process(\sprintf(
            'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
            \escapeshellarg($this->dir),
            \escapeshellarg($this->filePatch)
        ));

        $p->run();

        $this->assertProcessSuccessful($p);
    }

    private function doIntegrationTestPatch(string $diff, string $from, string $to): void
    {
        $this->assertNotSame('', $diff);
        $this->assertValidUnifiedDiffFormat($diff);

        $diff = self::setDiffFileHeader($diff, $this->fileFrom);

        $this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
        $this->assertNotFalse(\file_put_contents($this->filePatch, $diff));

        $command = \sprintf(
            'patch -u --verbose --posix %s < %s',
            \escapeshellarg($this->fileFrom),
            \escapeshellarg($this->filePatch)
        );

        $p = new Process($command);
        $p->run();

        $this->assertProcessSuccessful($p);

        $this->assertStringEqualsFile(
            $this->fileFrom,
            $to,
            \sprintf('Patch command "%s".', $command)
        );
    }

    private function assertProcessSuccessful(Process $p): void
    {
        $this->assertTrue(
            $p->isSuccessful(),
            \sprintf(
                "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
                $p->getCommandLine(),
                $p->getOutput(),
                $p->getErrorOutput(),
                $p->getExitCode()
            )
        );
    }

    private function cleanUpTempFiles(): void
    {
        @\unlink($this->fileFrom . '.orig');
        @\unlink($this->fileFrom . '.rej');
        @\unlink($this->fileFrom);
        @\unlink($this->fileTo);
        @\unlink($this->filePatch);
    }

    private static function setDiffFileHeader(string $diff, string $file): string
    {
        $diffLines    = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
        $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);

        return \implode('', $diffLines);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;

/**
 * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
 *
 * @uses SebastianBergmann\Diff\Differ
 * @uses SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 */
final class UnifiedDiffOutputBuilderTest extends TestCase
{
    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     * @param string $header
     *
     * @dataProvider headerProvider
     */
    public function testCustomHeaderCanBeUsed(string $expected, string $from, string $to, string $header): void
    {
        $differ = new Differ(new UnifiedDiffOutputBuilder($header));

        $this->assertSame(
            $expected,
            $differ->diff($from, $to)
        );
    }

    public function headerProvider(): array
    {
        return [
            [
                "CUSTOM HEADER\n@@ @@\n-a\n+b\n",
                'a',
                'b',
                'CUSTOM HEADER',
            ],
            [
                "CUSTOM HEADER\n@@ @@\n-a\n+b\n",
                'a',
                'b',
                "CUSTOM HEADER\n",
            ],
            [
                "CUSTOM HEADER\n\n@@ @@\n-a\n+b\n",
                'a',
                'b',
                "CUSTOM HEADER\n\n",
            ],
            [
                "@@ @@\n-a\n+b\n",
                'a',
                'b',
                '',
            ],
        ];
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider provideDiffWithLineNumbers
     */
    public function testDiffWithLineNumbers($expected, $from, $to): void
    {
        $differ = new Differ(new UnifiedDiffOutputBuilder("--- Original\n+++ New\n", true));
        $this->assertSame($expected, $differ->diff($from, $to));
    }

    public function provideDiffWithLineNumbers(): array
    {
        return UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers();
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

final class UnifiedDiffOutputBuilderDataProvider
{
    public static function provideDiffWithLineNumbers(): array
    {
        return [
            'diff line 1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1 @@
-AA
+BA
',
                'AA',
                'BA',
            ],
            'diff line +1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1,2 @@
-AZ
+
+B
',
                'AZ',
                "\nB",
            ],
            'diff line -1 non_patch_compat' => [
'--- Original
+++ New
@@ -1,2 +1 @@
-
-AF
+B
',
                "\nAF",
                'B',
            ],
            'II non_patch_compat' => [
'--- Original
+++ New
@@ -1,4 +1,2 @@
-
-
 A
 1
',
                "\n\nA\n1",
                "A\n1",
            ],
            'diff last line II - no trailing linebreak non_patch_compat' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
 ' . '
 ' . '
 ' . '
-E
+B
',
                "A\n\n\n\n\n\n\nE",
                "A\n\n\n\n\n\n\nB",
            ],
            [
                "--- Original\n+++ New\n@@ -1,2 +1 @@\n \n-\n",
                "\n\n",
                "\n",
            ],
            'diff line endings non_patch_compat' => [
                "--- Original\n+++ New\n@@ -1 +1 @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n",
                "<?php\r\n",
                "<?php\n",
            ],
        'same non_patch_compat' => [
'--- Original
+++ New
',
                "AT\n",
                "AT\n",
            ],
            [
'--- Original
+++ New
@@ -1,4 +1,4 @@
-b
+a
 ' . '
 ' . '
 ' . '
',
                "b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
                "a\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
            ],
            'diff line @1' => [
'--- Original
+++ New
@@ -1,2 +1,2 @@
 ' . '
-AG
+B
',
                "\nAG\n",
                "\nB\n",
            ],
            'same multiple lines' => [
'--- Original
+++ New
@@ -1,4 +1,4 @@
 ' . '
 ' . '
-V
+B
 C213
',
                "\n\nV\nC213",
                "\n\nB\nC213",
            ],
            'diff last line I' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
 ' . '
 ' . '
 ' . '
-E
+B
',
                "A\n\n\n\n\n\n\nE\n",
                "A\n\n\n\n\n\n\nB\n",
            ],
            'diff line middle' => [
'--- Original
+++ New
@@ -5,7 +5,7 @@
 ' . '
 ' . '
 ' . '
-X
+Z
 ' . '
 ' . '
 ' . '
',
                "A\n\n\n\n\n\n\nX\n\n\n\n\n\n\nAY",
                "A\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nAY",
            ],
            'diff last line III' => [
'--- Original
+++ New
@@ -12,4 +12,4 @@
 ' . '
 ' . '
 ' . '
-A
+B
',
                "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nA\n",
                "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nB\n",
            ],
            [
'--- Original
+++ New
@@ -1,8 +1,8 @@
 A
-B
+B1
 D
 E
 EE
 F
-G
+G1
 H
',
                "A\nB\nD\nE\nEE\nF\nG\nH",
                "A\nB1\nD\nE\nEE\nF\nG1\nH",
            ],
            [
'--- Original
+++ New
@@ -1,4 +1,5 @@
 Z
+
 a
 b
 c
@@ -7,5 +8,5 @@
 f
 g
 h
-i
+x
 j
',
'Z
a
b
c
d
e
f
g
h
i
j
',
'Z

a
b
c
d
e
f
g
h
x
j
',
            ],
            [
'--- Original
+++ New
@@ -1,7 +1,5 @@
-
-a
+b
 A
-X
-
+Y
 ' . '
 A
',
                "\na\nA\nX\n\n\nA\n",
                "b\nA\nY\n\nA\n",
            ],
            [
<<<EOF
--- Original
+++ New
@@ -1,7 +1,5 @@
-
-
 a
-b
+p
 c
 d
 e
@@ -9,5 +7,5 @@
 g
 h
 i
-j
+w
 k

EOF
                ,
                "\n\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
                "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
            ],
            [
'--- Original
+++ New
@@ -8,7 +8,7 @@
 ' . '
 ' . '
 ' . '
-A
+C
 ' . '
 ' . '
 ' . '
',
                "E\n\n\n\n\nB\n\n\n\n\nA\n\n\n\n\n\n\n\n\nD1",
                "E\n\n\n\n\nB\n\n\n\n\nC\n\n\n\n\n\n\n\n\nD1",
            ],
            [
'--- Original
+++ New
@@ -5,7 +5,7 @@
 ' . '
 ' . '
 ' . '
-Z
+U
 ' . '
 ' . '
 ' . '
@@ -12,7 +12,7 @@
 ' . '
 ' . '
 ' . '
-X
+V
 ' . '
 ' . '
 ' . '
@@ -19,7 +19,7 @@
 ' . '
 ' . '
 ' . '
-Y
+W
 ' . '
 ' . '
 ' . '
@@ -26,7 +26,7 @@
 ' . '
 ' . '
 ' . '
-W
+X
 ' . '
 ' . '
 ' . '
@@ -33,7 +33,7 @@
 ' . '
 ' . '
 ' . '
-V
+Y
 ' . '
 ' . '
 ' . '
@@ -40,4 +40,4 @@
 ' . '
 ' . '
 ' . '
-U
+Z
',
                "\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nW\n\n\n\n\n\n\nV\n\n\n\n\n\n\nU\n",
                "\n\n\n\n\n\n\nU\n\n\n\n\n\n\nV\n\n\n\n\n\n\nW\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nZ\n",
            ],
            [
<<<EOF
--- Original
+++ New
@@ -1,5 +1,5 @@
 a
-b
+p
 c
 d
 e
@@ -7,5 +7,5 @@
 g
 h
 i
-j
+w
 k

EOF
                ,
                "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
                "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
            ],
            [
<<<EOF
--- Original
+++ New
@@ -1,4 +1,4 @@
-A
+B
 1
 2
 3

EOF
                ,
                "A\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
                "B\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
            ],
            [
                "--- Original\n+++ New\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
                "A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n",
                "A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n",
            ],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Utils;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait
 */
final class UnifiedDiffAssertTraitTest extends TestCase
{
    use UnifiedDiffAssertTrait;

    /**
     * @param string $diff
     *
     * @dataProvider provideValidCases
     */
    public function testValidCases(string $diff): void
    {
        $this->assertValidUnifiedDiffFormat($diff);
    }

    public function provideValidCases(): array
    {
        return [
            [
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
',
            ],
            [
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
@@ -15 +15 @@
-X
+V
',
            ],
            'empty diff. is valid' => [
                '',
            ],
        ];
    }

    public function testNoLinebreakEnd(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected diff to end with a line break, got "C".', '#')));

        $this->assertValidUnifiedDiffFormat("A\nB\nC");
    }

    public function testInvalidStartWithoutHeader(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"A\n\". Line 1.", '#')));

        $this->assertValidUnifiedDiffFormat("A\n");
    }

    public function testInvalidStartHeader1(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"--- A\n\"\nLine 2: \"+ 1\n\".", '#')));

        $this->assertValidUnifiedDiffFormat("--- A\n+ 1\n");
    }

    public function testInvalidStartHeader2(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Header line does not match expected pattern, got \"+++ file	X\n\". Line 2.", '#')));

        $this->assertValidUnifiedDiffFormat("--- A\n+++ file\tX\n");
    }

    public function testInvalidStartHeader3(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Date of header line does not match expected pattern, got "[invalid date]". Line 1.', '#')));

        $this->assertValidUnifiedDiffFormat(
"--- Original\t[invalid date]
+++ New
@@ -1,2 +1,2 @@
-A
+B
 " . '
'
        );
    }

    public function testInvalidStartHeader4(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected header line to start with \"+++  \", got \"+++INVALID\n\". Line 2.", '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++INVALID
@@ -1,2 +1,2 @@
-A
+B
 ' . '
'
        );
    }

    public function testInvalidLine1(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"1\n\". Line 5.", '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
1
+U
'
        );
    }

    public function testInvalidLine2(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected string length of minimal 2, got 1. Line 4.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@


'
        );
    }

    public function testHunkInvalidFormat(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Hunk header line does not match expected pattern, got \"@@ INVALID -1,1 +1,1 @@\n\". Line 3.", '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ INVALID -1,1 +1,1 @@
-Z
+U
'
        );
    }

    public function testHunkOverlapFrom(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -7,1 +9,1 @@
-Z
+U
'
        );
    }

    public function testHunkOverlapTo(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -17,1 +7,1 @@
-Z
+U
'
        );
    }

    public function testExpectHunk1(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected hunk start (\'@\'), got "+". Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
+O
'
        );
    }

    public function testExpectHunk2(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected hunk start (\'@\'). Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
 ' . '
 ' . '
@@ -38,12 +48,12 @@
'
        );
    }

    public function testMisplacedLineAfterComments1(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 8.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
\ No newline at end of file
+U
\ No newline at end of file
+A
'
        );
    }

    public function testMisplacedLineAfterComments2(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
'
        );
    }

    public function testMisplacedLineAfterComments3(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
+A
'
        );
    }

    public function testMisplacedComment(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line 1.', '#')));

        $this->assertValidUnifiedDiffFormat(
'\ No newline at end of file
'
        );
    }

    public function testUnexpectedDuplicateNoNewLineEOF(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\\ No newline at end of file", "\\" was already closed. Line 8.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
 ' . '
 ' . '
\ No newline at end of file
 ' . '
\ No newline at end of file
'
        );
    }

    public function testFromAfterClose(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected from (\'-\'), already closed by "\ No newline at end of file". Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
-A
\ No newline at end of file
'
        );
    }

    public function testSameAfterFromClose(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'-\' already closed by "\ No newline at end of file". Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
            '--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
 A
\ No newline at end of file
'
        );
    }

    public function testToAfterClose(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected to (\'+\'), already closed by "\ No newline at end of file". Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
            '--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
+A
\ No newline at end of file
'
        );
    }

    public function testSameAfterToClose(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'+\' already closed by "\ No newline at end of file". Line 6.', '#')));

        $this->assertValidUnifiedDiffFormat(
            '--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
 A
\ No newline at end of file
'
        );
    }

    public function testUnexpectedEOFFromMissingLines(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line 7.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,19 +7,2 @@
-A
+B
 ' . '
'
        );
    }

    public function testUnexpectedEOFToMissingLines(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line 7.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,2 +7,3 @@
-A
+B
 ' . '
'
        );
    }

    public function testUnexpectedEOFBothFromAndToMissingLines(): void
    {
        $this->expectException(\UnexpectedValueException::class);
        $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line 7.', '#')));

        $this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -1,12 +1,14 @@
-A
+B
 ' . '
'
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Utils;

final class FileUtils
{
    public static function getFileContent(string $file): string
    {
        $content = @\file_get_contents($file);

        if (false === $content) {
            $error = \error_get_last();

            throw new \RuntimeException(\sprintf(
                'Failed to read content of file "%s".%s',
                $file,
                $error ? ' ' . $error['message'] : ''
            ));
        }

        return $content;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Utils;

trait UnifiedDiffAssertTrait
{
    /**
     * @param string $diff
     *
     * @throws \UnexpectedValueException
     */
    public function assertValidUnifiedDiffFormat(string $diff): void
    {
        if ('' === $diff) {
            $this->addToAssertionCount(1);

            return;
        }

        // test diff ends with a line break
        $last = \substr($diff, -1);

        if ("\n" !== $last && "\r" !== $last) {
            throw new \UnexpectedValueException(\sprintf('Expected diff to end with a line break, got "%s".', $last));
        }

        $lines            = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $lineCount        = \count($lines);
        $lineNumber       = $diffLineFromNumber       = $diffLineToNumber       = 1;
        $fromStart        = $fromTillOffset        = $toStart        = $toTillOffset        = -1;
        $expectHunkHeader = true;

        // check for header
        if ($lineCount > 1) {
            $this->unifiedDiffAssertLinePrefix($lines[0], 'Line 1.');
            $this->unifiedDiffAssertLinePrefix($lines[1], 'Line 2.');

            if ('---' === \substr($lines[0], 0, 3)) {
                if ('+++' !== \substr($lines[1], 0, 3)) {
                    throw new \UnexpectedValueException(\sprintf("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"%s\"\nLine 2: \"%s\".", $lines[0], $lines[1]));
                }

                $this->unifiedDiffAssertHeaderLine($lines[0], '--- ', 'Line 1.');
                $this->unifiedDiffAssertHeaderLine($lines[1], '+++ ', 'Line 2.');

                $lineNumber = 3;
            }
        }

        $endOfLineTypes = [];
        $diffClosed     = false;

        // assert format of lines, get all hunks, test the line numbers
        for (; $lineNumber <= $lineCount; ++$lineNumber) {
            if ($diffClosed) {
                throw new \UnexpectedValueException(\sprintf('Unexpected line as 2 "No newline" markers have found, ". Line %d.', $lineNumber));
            }

            $line = $lines[$lineNumber - 1]; // line numbers start by 1, array index at 0
            $type = $this->unifiedDiffAssertLinePrefix($line, \sprintf('Line %d.', $lineNumber));

            if ($expectHunkHeader && '@' !== $type && '\\' !== $type) {
                throw new \UnexpectedValueException(\sprintf('Expected hunk start (\'@\'), got "%s". Line %d.', $type, $lineNumber));
            }

            if ('@' === $type) {
                if (!$expectHunkHeader) {
                    throw new \UnexpectedValueException(\sprintf('Unexpected hunk start (\'@\'). Line %d.', $lineNumber));
                }

                $previousHunkFromEnd = $fromStart + $fromTillOffset;
                $previousHunkTillEnd = $toStart + $toTillOffset;

                [$fromStart, $fromTillOffset, $toStart, $toTillOffset] = $this->unifiedDiffAssertHunkHeader($line, \sprintf('Line %d.', $lineNumber));

                // detect overlapping hunks
                if ($fromStart < $previousHunkFromEnd) {
                    throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line %d.', $lineNumber));
                }

                if ($toStart < $previousHunkTillEnd) {
                    throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line %d.', $lineNumber));
                }

                /* valid states; hunks touches against each other:
                    $fromStart === $previousHunkFromEnd
                    $toStart === $previousHunkTillEnd
                */

                $diffLineFromNumber = $fromStart;
                $diffLineToNumber   = $toStart;
                $expectHunkHeader   = false;

                continue;
            }

            if ('-' === $type) {
                if (isset($endOfLineTypes['-'])) {
                    throw new \UnexpectedValueException(\sprintf('Not expected from (\'-\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
                }

                ++$diffLineFromNumber;
            } elseif ('+' === $type) {
                if (isset($endOfLineTypes['+'])) {
                    throw new \UnexpectedValueException(\sprintf('Not expected to (\'+\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
                }

                ++$diffLineToNumber;
            } elseif (' ' === $type) {
                if (isset($endOfLineTypes['-'])) {
                    throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'-\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
                }

                if (isset($endOfLineTypes['+'])) {
                    throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'+\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
                }

                ++$diffLineFromNumber;
                ++$diffLineToNumber;
            } elseif ('\\' === $type) {
                if (!isset($lines[$lineNumber - 2])) {
                    throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line %d.', $lineNumber));
                }

                $previousType = $this->unifiedDiffAssertLinePrefix($lines[$lineNumber - 2], \sprintf('Preceding line of "\\ No newline at end of file" of unexpected format. Line %d.', $lineNumber));

                if (isset($endOfLineTypes[$previousType])) {
                    throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", "%s" was already closed. Line %d.', $type, $lineNumber));
                }

                $endOfLineTypes[$previousType] = true;
                $diffClosed                    = \count($endOfLineTypes) > 1;
            } else {
                // internal state error
                throw new \RuntimeException(\sprintf('Unexpected line type "%s" Line %d.', $type, $lineNumber));
            }

            $expectHunkHeader =
                $diffLineFromNumber === ($fromStart + $fromTillOffset)
                && $diffLineToNumber === ($toStart + $toTillOffset)
            ;
        }

        if (
            $diffLineFromNumber !== ($fromStart + $fromTillOffset)
            && $diffLineToNumber !== ($toStart + $toTillOffset)
        ) {
            throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line %d.', $lineNumber));
        }

        if ($diffLineFromNumber !== ($fromStart + $fromTillOffset)) {
            throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line %d.', $lineNumber));
        }

        if ($diffLineToNumber !== ($toStart + $toTillOffset)) {
            throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line %d.', $lineNumber));
        }

        $this->addToAssertionCount(1);
    }

    /**
     * @param string $line
     * @param string $message
     *
     * @return string '+', '-', '@', ' ' or '\'
     */
    private function unifiedDiffAssertLinePrefix(string $line, string $message): string
    {
        $this->unifiedDiffAssertStrLength($line, 2, $message); // 2: line type indicator ('+', '-', ' ' or '\') and a line break
        $firstChar = $line[0];

        if ('+' === $firstChar || '-' === $firstChar || '@' === $firstChar || ' ' === $firstChar) {
            return $firstChar;
        }

        if ("\\ No newline at end of file\n" === $line) {
            return '\\';
        }

        throw new \UnexpectedValueException(\sprintf('Expected line to start with \'@\', \'-\' or \'+\', got "%s". %s', $line, $message));
    }

    private function unifiedDiffAssertStrLength(string $line, int $min, string $message): void
    {
        $length = \strlen($line);

        if ($length < $min) {
            throw new \UnexpectedValueException(\sprintf('Expected string length of minimal %d, got %d. %s', $min, $length, $message));
        }
    }

    /**
     * Assert valid unified diff header line
     *
     * Samples:
     * - "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200"
     * - "+++ from1.txt"
     *
     * @param string $line
     * @param string $start
     * @param string $message
     */
    private function unifiedDiffAssertHeaderLine(string $line, string $start, string $message): void
    {
        if (0 !== \strpos($line, $start)) {
            throw new \UnexpectedValueException(\sprintf('Expected header line to start with "%s", got "%s". %s', $start . ' ', $line, $message));
        }

        // sample "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200\n"
        $match = \preg_match(
            "/^([^\t]*)(?:[\t]([\\S].*[\\S]))?\n$/",
            \substr($line, 4), // 4 === string length of "+++ " / "--- "
            $matches
        );

        if (1 !== $match) {
            throw new \UnexpectedValueException(\sprintf('Header line does not match expected pattern, got "%s". %s', $line, $message));
        }

        // $file = $matches[1];

        if (\count($matches) > 2) {
            $this->unifiedDiffAssertHeaderDate($matches[2], $message);
        }
    }

    private function unifiedDiffAssertHeaderDate(string $date, string $message): void
    {
        // sample "2017-08-24 19:51:29.383985722 +0200"
        $match = \preg_match(
            '/^([\d]{4})-([01]?[\d])-([0123]?[\d])(:? [\d]{1,2}:[\d]{1,2}(?::[\d]{1,2}(:?\.[\d]+)?)?(?: ([\+\-][\d]{4}))?)?$/',
            $date,
            $matches
        );

        if (1 !== $match || ($matchesCount = \count($matches)) < 4) {
            throw new \UnexpectedValueException(\sprintf('Date of header line does not match expected pattern, got "%s". %s', $date, $message));
        }

        // [$full, $year, $month, $day, $time] = $matches;
    }

    /**
     * @param string $line
     * @param string $message
     *
     * @return int[]
     */
    private function unifiedDiffAssertHunkHeader(string $line, string $message): array
    {
        if (1 !== \preg_match('#^@@ -([\d]+)((?:,[\d]+)?) \+([\d]+)((?:,[\d]+)?) @@\n$#', $line, $matches)) {
            throw new \UnexpectedValueException(
                \sprintf(
                    'Hunk header line does not match expected pattern, got "%s". %s',
                    $line,
                    $message
                )
            );
        }

        return [
            (int) $matches[1],
            empty($matches[2]) ? 1 : (int) \substr($matches[2], 1),
            (int) $matches[3],
            empty($matches[4]) ? 1 : (int) \substr($matches[4], 1),
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Utils;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;

/**
 * @requires OS Linux
 *
 * @coversNothing
 */
final class UnifiedDiffAssertTraitIntegrationTest extends TestCase
{
    use UnifiedDiffAssertTrait;

    private $filePatch;

    protected function setUp(): void
    {
        $this->filePatch = __DIR__ . '/../fixtures/out/patch.txt';

        $this->cleanUpTempFiles();
    }

    protected function tearDown(): void
    {
        $this->cleanUpTempFiles();
    }

    /**
     * @param string $fileFrom
     * @param string $fileTo
     *
     * @dataProvider provideFilePairsCases
     */
    public function testValidPatches(string $fileFrom, string $fileTo): void
    {
        $command = \sprintf(
            'diff -u %s %s > %s',
            \escapeshellarg(\realpath($fileFrom)),
            \escapeshellarg(\realpath($fileTo)),
            \escapeshellarg($this->filePatch)
        );

        $p = new Process($command);
        $p->run();

        $exitCode = $p->getExitCode();

        if (0 === $exitCode) {
            // odd case when two files have the same content. Test after executing as it is more efficient than to read the files and check the contents every time.
            $this->addToAssertionCount(1);

            return;
        }

        $this->assertSame(
            1, // means `diff` found a diff between the files we gave it
            $exitCode,
            \sprintf(
                "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
                $command,
                $p->getOutput(),
                $p->getErrorOutput(),
                $p->getExitCode()
            )
        );

        $this->assertValidUnifiedDiffFormat(FileUtils::getFileContent($this->filePatch));
    }

    /**
     * @return array<string, array<string, string>>
     */
    public function provideFilePairsCases(): array
    {
        $cases = [];

        // created cases based on dedicated fixtures
        $dir       = \realpath(__DIR__ . '/../fixtures/UnifiedDiffAssertTraitIntegrationTest');
        $dirLength = \strlen($dir);

        for ($i = 1;; ++$i) {
            $fromFile = \sprintf('%s/%d_a.txt', $dir, $i);
            $toFile   = \sprintf('%s/%d_b.txt', $dir, $i);

            if (!\file_exists($fromFile)) {
                break;
            }

            $this->assertFileExists($toFile);
            $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
        }

        // create cases based on PHP files within the vendor directory for integration testing
        $dir       = \realpath(__DIR__ . '/../../vendor');
        $dirLength = \strlen($dir);

        $fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS));
        $fromFile     = __FILE__;

        /** @var \SplFileInfo $file */
        foreach ($fileIterator as $file) {
            if ('php' !== $file->getExtension()) {
                continue;
            }

            $toFile                                                                                                                                   = $file->getPathname();
            $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
            $fromFile                                                                                                                                 = $toFile;
        }

        return $cases;
    }

    private function cleanUpTempFiles(): void
    {
        @\unlink($this->filePatch);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Utils\FileUtils;

/**
 * @covers SebastianBergmann\Diff\Parser
 *
 * @uses SebastianBergmann\Diff\Chunk
 * @uses SebastianBergmann\Diff\Diff
 * @uses SebastianBergmann\Diff\Line
 */
final class ParserTest extends TestCase
{
    /**
     * @var Parser
     */
    private $parser;

    protected function setUp(): void
    {
        $this->parser = new Parser;
    }

    public function testParse(): void
    {
        $content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch.txt');

        $diffs = $this->parser->parse($content);

        $this->assertContainsOnlyInstancesOf(Diff::class, $diffs);
        $this->assertCount(1, $diffs);

        $chunks = $diffs[0]->getChunks();
        $this->assertContainsOnlyInstancesOf(Chunk::class, $chunks);

        $this->assertCount(1, $chunks);

        $this->assertSame(20, $chunks[0]->getStart());

        $this->assertCount(4, $chunks[0]->getLines());
    }

    public function testParseWithMultipleChunks(): void
    {
        $content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch2.txt');

        $diffs = $this->parser->parse($content);

        $this->assertCount(1, $diffs);

        $chunks = $diffs[0]->getChunks();
        $this->assertCount(3, $chunks);

        $this->assertSame(20, $chunks[0]->getStart());
        $this->assertSame(320, $chunks[1]->getStart());
        $this->assertSame(600, $chunks[2]->getStart());

        $this->assertCount(5, $chunks[0]->getLines());
        $this->assertCount(5, $chunks[1]->getLines());
        $this->assertCount(4, $chunks[2]->getLines());
    }

    public function testParseWithRemovedLines(): void
    {
        $content = <<<END
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
+++ b/Test.txt
@@ -49,9 +49,8 @@
 A
-B
END;
        $diffs = $this->parser->parse($content);
        $this->assertContainsOnlyInstancesOf(Diff::class, $diffs);
        $this->assertCount(1, $diffs);

        $chunks = $diffs[0]->getChunks();

        $this->assertContainsOnlyInstancesOf(Chunk::class, $chunks);
        $this->assertCount(1, $chunks);

        $chunk = $chunks[0];
        $this->assertSame(49, $chunk->getStart());
        $this->assertSame(49, $chunk->getEnd());
        $this->assertSame(9, $chunk->getStartRange());
        $this->assertSame(8, $chunk->getEndRange());

        $lines = $chunk->getLines();
        $this->assertContainsOnlyInstancesOf(Line::class, $lines);
        $this->assertCount(2, $lines);

        /** @var Line $line */
        $line = $lines[0];
        $this->assertSame('A', $line->getContent());
        $this->assertSame(Line::UNCHANGED, $line->getType());

        $line = $lines[1];
        $this->assertSame('B', $line->getContent());
        $this->assertSame(Line::REMOVED, $line->getType());
    }

    public function testParseDiffForMulitpleFiles(): void
    {
        $content = <<<END
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
+++ b/Test.txt
@@ -1,3 +1,2 @@
 A
-B

diff --git a/Test123.txt b/Test123.txt
index abcdefg..abcdefh 100644
--- a/Test2.txt
+++ b/Test2.txt
@@ -1,2 +1,3 @@
 A
+B
END;
        $diffs = $this->parser->parse($content);
        $this->assertCount(2, $diffs);

        /** @var Diff $diff */
        $diff = $diffs[0];
        $this->assertSame('a/Test.txt', $diff->getFrom());
        $this->assertSame('b/Test.txt', $diff->getTo());
        $this->assertCount(1, $diff->getChunks());

        $diff = $diffs[1];
        $this->assertSame('a/Test2.txt', $diff->getFrom());
        $this->assertSame('b/Test2.txt', $diff->getTo());
        $this->assertCount(1, $diff->getChunks());
    }

    /**
     * @param string $diff
     * @param Diff[] $expected
     *
     * @dataProvider diffProvider
     */
    public function testParser(string $diff, array $expected): void
    {
        $result = $this->parser->parse($diff);

        $this->assertEquals($expected, $result);
    }

    public function diffProvider(): array
    {
        return [
            [
                "--- old.txt	2014-11-04 08:51:02.661868729 +0300\n+++ new.txt	2014-11-04 08:51:02.665868730 +0300\n@@ -1,3 +1,4 @@\n+2222111\n 1111111\n 1111111\n 1111111\n@@ -5,10 +6,8 @@\n 1111111\n 1111111\n 1111111\n +1121211\n 1111111\n -1111111\n -1111111\n -2222222\n 2222222\n 2222222\n 2222222\n@@ -17,5 +16,6 @@\n 2222222\n 2222222\n 2222222\n +2122212\n 2222222\n 2222222\n",
                \unserialize(FileUtils::getFileContent(__DIR__ . '/fixtures/serialized_diff.bin')),
            ],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

/**
 * @covers SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 */
final class TimeEfficientImplementationTest extends LongestCommonSubsequenceTest
{
    protected function createImplementation(): LongestCommonSubsequenceCalculator
    {
        return new TimeEfficientLongestCommonSubsequenceCalculator;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\Line
 */
final class LineTest extends TestCase
{
    /**
     * @var Line
     */
    private $line;

    protected function setUp(): void
    {
        $this->line = new Line;
    }

    public function testCanBeCreatedWithoutArguments(): void
    {
        $this->assertInstanceOf(Line::class, $this->line);
    }

    public function testTypeCanBeRetrieved(): void
    {
        $this->assertSame(Line::UNCHANGED, $this->line->getType());
    }

    public function testContentCanBeRetrieved(): void
    {
        $this->assertSame('', $this->line->getContent());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

/**
 * @covers SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator
 */
final class MemoryEfficientImplementationTest extends LongestCommonSubsequenceTest
{
    protected function createImplementation(): LongestCommonSubsequenceCalculator
    {
        return new MemoryEfficientLongestCommonSubsequenceCalculator;
    }
}
a
a
a
a
a
a
a
a
a
a
b
a
a
a
a
a
a
ca
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
aaroot = true
# reset all ignore rules to create sandbox for integration test
!/**root = true
diff --git a/Foo.php b/Foo.php
index abcdefg..abcdefh 100644
--- a/Foo.php
+++ b/Foo.php
@@ -20,4 +20,5 @@ class Foo
     const ONE = 1;
     const TWO = 2;
+    const THREE = 3;
     const FOUR = 4;

@@ -320,4 +320,5 @@ class Foo
     const A = 'A';
     const B = 'B';
+    const C = 'C';
     const D = 'D';

@@ -600,4 +600,5 @@ class Foo
     public function doSomething() {

+        return 'foo';
     }
diff --git a/Foo.php b/Foo.php
index abcdefg..abcdefh 100644
--- a/Foo.php
+++ b/Foo.php
@@ -20,4 +20,5 @@ class Foo
     const ONE = 1;
     const TWO = 2;
+    const THREE = 3;
     const FOUR = 4;
a:1:{i:0;O:27:"SebastianBergmann\Diff\Diff":3:{s:33:"SebastianBergmann\Diff\Difffrom";s:7:"old.txt";s:31:"SebastianBergmann\Diff\Diffto";s:7:"new.txt";s:35:"SebastianBergmann\Diff\Diffchunks";a:3:{i:0;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:1;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:3;s:33:"SebastianBergmann\Diff\Chunkend";i:1;s:38:"SebastianBergmann\Diff\ChunkendRange";i:4;s:35:"SebastianBergmann\Diff\Chunklines";a:4:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:1;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222111";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}}}i:1;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:5;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:10;s:33:"SebastianBergmann\Diff\Chunkend";i:6;s:38:"SebastianBergmann\Diff\ChunkendRange";i:8;s:35:"SebastianBergmann\Diff\Chunklines";a:11:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"+1121211";}i:4;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:5;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-1111111";}i:6;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-1111111";}i:7;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-2222222";}i:8;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:9;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:10;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}}}i:2;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:17;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:5;s:33:"SebastianBergmann\Diff\Chunkend";i:16;s:38:"SebastianBergmann\Diff\ChunkendRange";i:6;s:35:"SebastianBergmann\Diff\Chunklines";a:6:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"+2122212";}i:4;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:5;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}}}}}}<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\Chunk
 */
final class ChunkTest extends TestCase
{
    /**
     * @var Chunk
     */
    private $chunk;

    protected function setUp(): void
    {
        $this->chunk = new Chunk;
    }

    public function testHasInitiallyNoLines(): void
    {
        $this->assertSame([], $this->chunk->getLines());
    }

    public function testCanBeCreatedWithoutArguments(): void
    {
        $this->assertInstanceOf(Chunk::class, $this->chunk);
    }

    public function testStartCanBeRetrieved(): void
    {
        $this->assertSame(0, $this->chunk->getStart());
    }

    public function testStartRangeCanBeRetrieved(): void
    {
        $this->assertSame(1, $this->chunk->getStartRange());
    }

    public function testEndCanBeRetrieved(): void
    {
        $this->assertSame(0, $this->chunk->getEnd());
    }

    public function testEndRangeCanBeRetrieved(): void
    {
        $this->assertSame(1, $this->chunk->getEndRange());
    }

    public function testLinesCanBeRetrieved(): void
    {
        $this->assertSame([], $this->chunk->getLines());
    }

    public function testLinesCanBeSet(): void
    {
        $lines = [new Line(Line::ADDED, 'added'), new Line(Line::REMOVED, 'removed')];

        $this->chunk->setLines($lines);

        $this->assertSame($lines, $this->chunk->getLines());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\InvalidArgumentException
 */
final class InvalidArgumentExceptionTest extends TestCase
{
    public function testInvalidArgumentException(): void
    {
        $previousException = new \LogicException();
        $message           = 'test';
        $code              = 123;

        $exception = new InvalidArgumentException($message, $code, $previousException);

        $this->assertInstanceOf(Exception::class, $exception);
        $this->assertSame($message, $exception->getMessage());
        $this->assertSame($code, $exception->getCode());
        $this->assertSame($previousException, $exception->getPrevious());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\Diff\ConfigurationException
 */
final class ConfigurationExceptionTest extends TestCase
{
    public function testConstructWithDefaults(): void
    {
        $e = new ConfigurationException('test', 'A', 'B');

        $this->assertSame(0, $e->getCode());
        $this->assertNull($e->getPrevious());
        $this->assertSame('Option "test" must be A, got "string#B".', $e->getMessage());
    }

    public function testConstruct(): void
    {
        $e = new ConfigurationException(
            'test',
            'integer',
            new \SplFileInfo(__FILE__),
            789,
            new \BadMethodCallException(__METHOD__)
        );

        $this->assertSame('Option "test" must be integer, got "SplFileInfo".', $e->getMessage());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;

/**
 * @covers SebastianBergmann\Diff\Differ
 * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
 *
 * @uses SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator
 * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
 * @uses SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder
 */
final class DifferTest extends TestCase
{
    /**
     * @var Differ
     */
    private $differ;

    protected function setUp(): void
    {
        $this->differ = new Differ;
    }

    /**
     * @param array        $expected
     * @param array|string $from
     * @param array|string $to
     *
     * @dataProvider arrayProvider
     */
    public function testArrayRepresentationOfDiffCanBeRenderedUsingTimeEfficientLcsImplementation(array $expected, $from, $to): void
    {
        $this->assertSame($expected, $this->differ->diffToArray($from, $to, new TimeEfficientLongestCommonSubsequenceCalculator));
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider textProvider
     */
    public function testTextRepresentationOfDiffCanBeRenderedUsingTimeEfficientLcsImplementation(string $expected, string $from, string $to): void
    {
        $this->assertSame($expected, $this->differ->diff($from, $to, new TimeEfficientLongestCommonSubsequenceCalculator));
    }

    /**
     * @param array        $expected
     * @param array|string $from
     * @param array|string $to
     *
     * @dataProvider arrayProvider
     */
    public function testArrayRepresentationOfDiffCanBeRenderedUsingMemoryEfficientLcsImplementation(array $expected, $from, $to): void
    {
        $this->assertSame($expected, $this->differ->diffToArray($from, $to, new MemoryEfficientLongestCommonSubsequenceCalculator));
    }

    /**
     * @param string $expected
     * @param string $from
     * @param string $to
     *
     * @dataProvider textProvider
     */
    public function testTextRepresentationOfDiffCanBeRenderedUsingMemoryEfficientLcsImplementation(string $expected, string $from, string $to): void
    {
        $this->assertSame($expected, $this->differ->diff($from, $to, new MemoryEfficientLongestCommonSubsequenceCalculator));
    }

    public function testTypesOtherThanArrayAndStringCanBePassed(): void
    {
        $this->assertSame(
            "--- Original\n+++ New\n@@ @@\n-1\n+2\n",
            $this->differ->diff(1, 2)
        );
    }

    public function testArrayDiffs(): void
    {
        $this->assertSame(
            '--- Original
+++ New
@@ @@
-one
+two
',
            $this->differ->diff(['one'], ['two'])
        );
    }

    public function arrayProvider(): array
    {
        return [
            [
                [
                    ['a', Differ::REMOVED],
                    ['b', Differ::ADDED],
                ],
                'a',
                'b',
            ],
            [
                [
                    ['ba', Differ::REMOVED],
                    ['bc', Differ::ADDED],
                ],
                'ba',
                'bc',
            ],
            [
                [
                    ['ab', Differ::REMOVED],
                    ['cb', Differ::ADDED],
                ],
                'ab',
                'cb',
            ],
            [
                [
                    ['abc', Differ::REMOVED],
                    ['adc', Differ::ADDED],
                ],
                'abc',
                'adc',
            ],
            [
                [
                    ['ab', Differ::REMOVED],
                    ['abc', Differ::ADDED],
                ],
                'ab',
                'abc',
            ],
            [
                [
                    ['bc', Differ::REMOVED],
                    ['abc', Differ::ADDED],
                ],
                'bc',
                'abc',
            ],
            [
                [
                    ['abc', Differ::REMOVED],
                    ['abbc', Differ::ADDED],
                ],
                'abc',
                'abbc',
            ],
            [
                [
                    ['abcdde', Differ::REMOVED],
                    ['abcde', Differ::ADDED],
                ],
                'abcdde',
                'abcde',
            ],
            'same start' => [
                [
                    [17, Differ::OLD],
                    ['b', Differ::REMOVED],
                    ['d', Differ::ADDED],
                ],
                [30 => 17, 'a' => 'b'],
                [30 => 17, 'c' => 'd'],
            ],
            'same end' => [
                [
                    [1, Differ::REMOVED],
                    [2, Differ::ADDED],
                    ['b', Differ::OLD],
                ],
                [1 => 1, 'a' => 'b'],
                [1 => 2, 'a' => 'b'],
            ],
            'same start (2), same end (1)' => [
                [
                    [17, Differ::OLD],
                    [2, Differ::OLD],
                    [4, Differ::REMOVED],
                    ['a', Differ::ADDED],
                    [5, Differ::ADDED],
                    ['x', Differ::OLD],
                ],
                [30 => 17, 1 => 2, 2 => 4, 'z' => 'x'],
                [30 => 17, 1 => 2, 3 => 'a', 2 => 5, 'z' => 'x'],
            ],
            'same' => [
                [
                    ['x', Differ::OLD],
                ],
                ['z' => 'x'],
                ['z' => 'x'],
            ],
            'diff' => [
                [
                    ['y', Differ::REMOVED],
                    ['x', Differ::ADDED],
                ],
                ['x' => 'y'],
                ['z' => 'x'],
            ],
            'diff 2' => [
                [
                    ['y', Differ::REMOVED],
                    ['b', Differ::REMOVED],
                    ['x', Differ::ADDED],
                    ['d', Differ::ADDED],
                ],
                ['x' => 'y', 'a' => 'b'],
                ['z' => 'x', 'c' => 'd'],
            ],
            'test line diff detection' => [
                [
                    [
                        "#Warning: Strings contain different line endings!\n",
                        Differ::DIFF_LINE_END_WARNING,
                    ],
                    [
                        "<?php\r\n",
                        Differ::REMOVED,
                    ],
                    [
                        "<?php\n",
                        Differ::ADDED,
                    ],
                ],
                "<?php\r\n",
                "<?php\n",
            ],
            'test line diff detection in array input' => [
                [
                    [
                        "#Warning: Strings contain different line endings!\n",
                        Differ::DIFF_LINE_END_WARNING,
                    ],
                    [
                        "<?php\r\n",
                        Differ::REMOVED,
                    ],
                    [
                        "<?php\n",
                        Differ::ADDED,
                    ],
                ],
                ["<?php\r\n"],
                ["<?php\n"],
            ],
        ];
    }

    public function textProvider(): array
    {
        return [
            [
                "--- Original\n+++ New\n@@ @@\n-a\n+b\n",
                'a',
                'b',
            ],
            [
                "--- Original\n+++ New\n@@ @@\n-A\n+A1\n B\n",
                "A\nB",
                "A1\nB",
            ],
            [
                <<<EOF
--- Original
+++ New
@@ @@
 a
-b
+p
 c
 d
 e
@@ @@
 g
 h
 i
-j
+w
 k

EOF
            ,
                "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
                "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
            ],
            [
                <<<EOF
--- Original
+++ New
@@ @@
-A
+B
 1
 2
 3

EOF
            ,
                "A\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",
                "B\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",
            ],
            [
                "--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n A\n",
                "<?php\r\nA\n",
                "<?php\nA\n",
            ],
            [
                "--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-a\r\n+\n+c\r\n",
                "a\r\n",
                "\nc\r",
            ],
        ];
    }

    public function testDiffToArrayInvalidFromType(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageRegExp('#^"from" must be an array or string\.$#');

        $this->differ->diffToArray(null, '');
    }

    public function testDiffInvalidToType(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageRegExp('#^"to" must be an array or string\.$#');

        $this->differ->diffToArray('', new \stdClass);
    }

    /**
     * @param array  $expected
     * @param string $input
     *
     * @dataProvider provideSplitStringByLinesCases
     */
    public function testSplitStringByLines(array $expected, string $input): void
    {
        $reflection = new \ReflectionObject($this->differ);
        $method     = $reflection->getMethod('splitStringByLines');
        $method->setAccessible(true);

        $this->assertSame($expected, $method->invoke($this->differ, $input));
    }

    public function provideSplitStringByLinesCases(): array
    {
        return [
            [
                [],
                '',
            ],
            [
                ['a'],
                'a',
            ],
            [
                ["a\n"],
                "a\n",
            ],
            [
                ["a\r"],
                "a\r",
            ],
            [
                ["a\r\n"],
                "a\r\n",
            ],
            [
                ["\n"],
                "\n",
            ],
            [
                ["\r"],
                "\r",
            ],
            [
                ["\r\n"],
                "\r\n",
            ],
            [
                [
                    "A\n",
                    "B\n",
                    "\n",
                    "C\n",
                ],
                "A\nB\n\nC\n",
            ],
            [
                [
                    "A\r\n",
                    "B\n",
                    "\n",
                    "C\r",
                ],
                "A\r\nB\n\nC\r",
            ],
            [
                [
                    "\n",
                    "A\r\n",
                    "B\n",
                    "\n",
                    'C',
                ],
                "\nA\r\nB\n\nC",
            ],
        ];
    }

    public function testConstructorInvalidArgInt(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageRegExp('/^Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got integer "1"\.$/');

        new Differ(1);
    }

    public function testConstructorInvalidArgObject(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageRegExp('/^Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got instance of "SplFileInfo"\.$/');

        new Differ(new \SplFileInfo(__FILE__));
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use PHPUnit\Framework\TestCase;

/**
 * @coversNothing
 */
abstract class LongestCommonSubsequenceTest extends TestCase
{
    /**
     * @var LongestCommonSubsequenceCalculator
     */
    private $implementation;

    /**
     * @var string
     */
    private $memoryLimit;

    /**
     * @var int[]
     */
    private $stress_sizes = [1, 2, 3, 100, 500, 1000, 2000];

    protected function setUp(): void
    {
        $this->memoryLimit = \ini_get('memory_limit');
        \ini_set('memory_limit', '256M');

        $this->implementation = $this->createImplementation();
    }

    protected function tearDown(): void
    {
        \ini_set('memory_limit', $this->memoryLimit);
    }

    public function testBothEmpty(): void
    {
        $from   = [];
        $to     = [];
        $common = $this->implementation->calculate($from, $to);

        $this->assertSame([], $common);
    }

    public function testIsStrictComparison(): void
    {
        $from = [
            false, 0, 0.0, '', null, [],
            true, 1, 1.0, 'foo', ['foo', 'bar'], ['foo' => 'bar'],
        ];
        $to     = $from;
        $common = $this->implementation->calculate($from, $to);

        $this->assertSame($from, $common);

        $to = [
            false, false, false, false, false, false,
            true, true, true, true, true, true,
        ];

        $expected = [
            false,
            true,
        ];

        $common = $this->implementation->calculate($from, $to);

        $this->assertSame($expected, $common);
    }

    public function testEqualSequences(): void
    {
        foreach ($this->stress_sizes as $size) {
            $range  = \range(1, $size);
            $from   = $range;
            $to     = $range;
            $common = $this->implementation->calculate($from, $to);

            $this->assertSame($range, $common);
        }
    }

    public function testDistinctSequences(): void
    {
        $from   = ['A'];
        $to     = ['B'];
        $common = $this->implementation->calculate($from, $to);
        $this->assertSame([], $common);

        $from   = ['A', 'B', 'C'];
        $to     = ['D', 'E', 'F'];
        $common = $this->implementation->calculate($from, $to);
        $this->assertSame([], $common);

        foreach ($this->stress_sizes as $size) {
            $from   = \range(1, $size);
            $to     = \range($size + 1, $size * 2);
            $common = $this->implementation->calculate($from, $to);
            $this->assertSame([], $common);
        }
    }

    public function testCommonSubsequence(): void
    {
        $from     = ['A',      'C',      'E', 'F', 'G'];
        $to       = ['A', 'B',      'D', 'E',           'H'];
        $expected = ['A',                'E'];
        $common   = $this->implementation->calculate($from, $to);
        $this->assertSame($expected, $common);

        $from     = ['A',      'C',      'E', 'F', 'G'];
        $to       = ['B', 'C', 'D', 'E', 'F',      'H'];
        $expected = ['C',                'E', 'F'];
        $common   = $this->implementation->calculate($from, $to);
        $this->assertSame($expected, $common);

        foreach ($this->stress_sizes as $size) {
            $from     = $size < 2 ? [1] : \range(1, $size + 1, 2);
            $to       = $size < 3 ? [1] : \range(1, $size + 1, 3);
            $expected = $size < 6 ? [1] : \range(1, $size + 1, 6);
            $common   = $this->implementation->calculate($from, $to);

            $this->assertSame($expected, $common);
        }
    }

    public function testSingleElementSubsequenceAtStart(): void
    {
        foreach ($this->stress_sizes as $size) {
            $from   = \range(1, $size);
            $to     = \array_slice($from, 0, 1);
            $common = $this->implementation->calculate($from, $to);

            $this->assertSame($to, $common);
        }
    }

    public function testSingleElementSubsequenceAtMiddle(): void
    {
        foreach ($this->stress_sizes as $size) {
            $from   = \range(1, $size);
            $to     = \array_slice($from, (int) ($size / 2), 1);
            $common = $this->implementation->calculate($from, $to);

            $this->assertSame($to, $common);
        }
    }

    public function testSingleElementSubsequenceAtEnd(): void
    {
        foreach ($this->stress_sizes as $size) {
            $from   = \range(1, $size);
            $to     = \array_slice($from, $size - 1, 1);
            $common = $this->implementation->calculate($from, $to);

            $this->assertSame($to, $common);
        }
    }

    public function testReversedSequences(): void
    {
        $from     = ['A', 'B'];
        $to       = ['B', 'A'];
        $expected = ['A'];
        $common   = $this->implementation->calculate($from, $to);
        $this->assertSame($expected, $common);

        foreach ($this->stress_sizes as $size) {
            $from   = \range(1, $size);
            $to     = \array_reverse($from);
            $common = $this->implementation->calculate($from, $to);

            $this->assertSame([1], $common);
        }
    }

    public function testStrictTypeCalculate(): void
    {
        $diff = $this->implementation->calculate(['5'], ['05']);

        $this->assertIsArray($diff);
        $this->assertCount(0, $diff);
    }

    /**
     * @return LongestCommonSubsequenceCalculator
     */
    abstract protected function createImplementation(): LongestCommonSubsequenceCalculator;
}
# sebastian/diff

Diff implementation for PHP, factored out of PHPUnit into a stand-alone component.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/diff

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/diff

### Usage

#### Generating diff

The `Differ` class can be used to generate a textual representation of the difference between two strings:

```php
<?php
use SebastianBergmann\Diff\Differ;

$differ = new Differ;
print $differ->diff('foo', 'bar');
```

The code above yields the output below:
```diff
--- Original
+++ New
@@ @@
-foo
+bar
```

There are three output builders available in this package:

#### UnifiedDiffOutputBuilder 

This is default builder, which generates the output close to udiff and is used by PHPUnit.

```php
<?php

use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;

$builder = new UnifiedDiffOutputBuilder(
    "--- Original\n+++ New\n", // custom header
    false                      // do not add line numbers to the diff 
);

$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```

#### StrictUnifiedDiffOutputBuilder

Generates (strict) Unified diff's (unidiffs) with hunks,
similar to `diff -u` and compatible with `patch` and `git apply`.

```php
<?php

use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder;

$builder = new StrictUnifiedDiffOutputBuilder([
    'collapseRanges'      => true, // ranges of length one are rendered with the trailing `,1`
    'commonLineThreshold' => 6,    // number of same lines before ending a new hunk and creating a new one (if needed)
    'contextLines'        => 3,    // like `diff:  -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3
    'fromFile'            => null,
    'fromFileDate'        => null,
    'toFile'              => null,
    'toFileDate'          => null,
]);

$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```

#### DiffOnlyOutputBuilder

Output only the lines that differ.

```php
<?php

use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder;

$builder = new DiffOnlyOutputBuilder(
    "--- Original\n+++ New\n"
);

$differ = new Differ($builder);
print $differ->diff('foo', 'bar');
```

#### DiffOutputBuilderInterface

You can pass any output builder to the `Differ` class as longs as it implements the `DiffOutputBuilderInterface`. 

#### Parsing diff

The `Parser` class can be used to parse a unified diff into an object graph:

```php
use SebastianBergmann\Diff\Parser;
use SebastianBergmann\Git;

$git = new Git('/usr/local/src/money');

$diff = $git->getDiff(
  '948a1a07768d8edd10dcefa8315c1cbeffb31833',
  'c07a373d2399f3e686234c4f7f088d635eb9641b'
);

$parser = new Parser;

print_r($parser->parse($diff));
```

The code above yields the output below:

    Array
    (
        [0] => SebastianBergmann\Diff\Diff Object
            (
                [from:SebastianBergmann\Diff\Diff:private] => a/tests/MoneyTest.php
                [to:SebastianBergmann\Diff\Diff:private] => b/tests/MoneyTest.php
                [chunks:SebastianBergmann\Diff\Diff:private] => Array
                    (
                        [0] => SebastianBergmann\Diff\Chunk Object
                            (
                                [start:SebastianBergmann\Diff\Chunk:private] => 87
                                [startRange:SebastianBergmann\Diff\Chunk:private] => 7
                                [end:SebastianBergmann\Diff\Chunk:private] => 87
                                [endRange:SebastianBergmann\Diff\Chunk:private] => 7
                                [lines:SebastianBergmann\Diff\Chunk:private] => Array
                                    (
                                        [0] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>      * @covers SebastianBergmann\Money\Money::add
                                            )

                                        [1] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>      * @covers SebastianBergmann\Money\Money::newMoney
                                            )

                                        [2] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>      */
                                            )

                                        [3] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 2
                                                [content:SebastianBergmann\Diff\Line:private] =>     public function testAnotherMoneyWithSameCurrencyObjectCanBeAdded()
                                            )

                                        [4] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 1
                                                [content:SebastianBergmann\Diff\Line:private] =>     public function testAnotherMoneyObjectWithSameCurrencyCanBeAdded()
                                            )

                                        [5] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>     {
                                            )

                                        [6] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>         $a = new Money(1, new Currency('EUR'));
                                            )

                                        [7] => SebastianBergmann\Diff\Line Object
                                            (
                                                [type:SebastianBergmann\Diff\Line:private] => 3
                                                [content:SebastianBergmann\Diff\Line:private] =>         $b = new Money(2, new Currency('EUR'));
                                            )
                                    )
                            )
                    )
            )
    )
/.idea
/composer.lock
/vendor
/.php_cs.cache
/.phpunit.result.cache
/from.txt.orig# Configuration for probot-stale - https://github.com/probot/stale

# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale Issue or Pull Request is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 7

# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
  - enhancement

# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false

# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false

# Label to use when marking as stale
staleLabel: wontfix

# Comment to post when marking as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.

# Comment to post when removing the stale label.
# unmarkComment: >
#   Your comment here.

# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
  This issue has been automatically closed because it has not had activity since it was marked as stale. Thank you for your contributions.

# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

# Limit to only `issues` or `pulls`
only: issues

language: php

php:
  - 7.1
  - 7.2
  - 7.3
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false

{
    "name": "sebastian/diff",
    "description": "Diff implementation",
    "keywords": ["diff", "udiff", "unidiff", "unified diff"],
    "homepage": "https://github.com/sebastianbergmann/diff",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        },
        {
            "name": "Kore Nordmann",
            "email": "mail@kore-nordmann.de"
        }
    ],
    "require": {
        "php": ">=7.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^7.5 || ^8.0",
        "symfony/process": "^2 || ^3.3 || ^4"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.0-dev"
        }
    }
}
<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of sebastian/diff.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['method']],
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'no_alias_functions' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_null_property_initialization' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_types' => true,
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => true,
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class Diff
{
    /**
     * @var string
     */
    private $from;

    /**
     * @var string
     */
    private $to;

    /**
     * @var Chunk[]
     */
    private $chunks;

    /**
     * @param string  $from
     * @param string  $to
     * @param Chunk[] $chunks
     */
    public function __construct(string $from, string $to, array $chunks = [])
    {
        $this->from   = $from;
        $this->to     = $to;
        $this->chunks = $chunks;
    }

    public function getFrom(): string
    {
        return $this->from;
    }

    public function getTo(): string
    {
        return $this->to;
    }

    /**
     * @return Chunk[]
     */
    public function getChunks(): array
    {
        return $this->chunks;
    }

    /**
     * @param Chunk[] $chunks
     */
    public function setChunks(array $chunks): void
    {
        $this->chunks = $chunks;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

/**
 * Unified diff parser.
 */
final class Parser
{
    /**
     * @param string $string
     *
     * @return Diff[]
     */
    public function parse(string $string): array
    {
        $lines = \preg_split('(\r\n|\r|\n)', $string);

        if (!empty($lines) && $lines[\count($lines) - 1] === '') {
            \array_pop($lines);
        }

        $lineCount = \count($lines);
        $diffs     = [];
        $diff      = null;
        $collected = [];

        for ($i = 0; $i < $lineCount; ++$i) {
            if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
                \preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
                if ($diff !== null) {
                    $this->parseFileDiff($diff, $collected);

                    $diffs[]   = $diff;
                    $collected = [];
                }

                $diff = new Diff($fromMatch['file'], $toMatch['file']);

                ++$i;
            } else {
                if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
                    continue;
                }

                $collected[] = $lines[$i];
            }
        }

        if ($diff !== null && \count($collected)) {
            $this->parseFileDiff($diff, $collected);

            $diffs[] = $diff;
        }

        return $diffs;
    }

    private function parseFileDiff(Diff $diff, array $lines): void
    {
        $chunks = [];
        $chunk  = null;

        foreach ($lines as $line) {
            if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
                $chunk = new Chunk(
                    (int) $match['start'],
                    isset($match['startrange']) ? \max(1, (int) $match['startrange']) : 1,
                    (int) $match['end'],
                    isset($match['endrange']) ? \max(1, (int) $match['endrange']) : 1
                );

                $chunks[]  = $chunk;
                $diffLines = [];

                continue;
            }

            if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
                $type = Line::UNCHANGED;

                if ($match['type'] === '+') {
                    $type = Line::ADDED;
                } elseif ($match['type'] === '-') {
                    $type = Line::REMOVED;
                }

                $diffLines[] = new Line($type, $match['line']);

                if (null !== $chunk) {
                    $chunk->setLines($diffLines);
                }
            }
        }

        $diff->setChunks($chunks);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
    /**
     * {@inheritdoc}
     */
    public function calculate(array $from, array $to): array
    {
        $common     = [];
        $fromLength = \count($from);
        $toLength   = \count($to);
        $width      = $fromLength + 1;
        $matrix     = new \SplFixedArray($width * ($toLength + 1));

        for ($i = 0; $i <= $fromLength; ++$i) {
            $matrix[$i] = 0;
        }

        for ($j = 0; $j <= $toLength; ++$j) {
            $matrix[$j * $width] = 0;
        }

        for ($i = 1; $i <= $fromLength; ++$i) {
            for ($j = 1; $j <= $toLength; ++$j) {
                $o          = ($j * $width) + $i;
                $matrix[$o] = \max(
                    $matrix[$o - 1],
                    $matrix[$o - $width],
                    $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
                );
            }
        }

        $i = $fromLength;
        $j = $toLength;

        while ($i > 0 && $j > 0) {
            if ($from[$i - 1] === $to[$j - 1]) {
                $common[] = $from[$i - 1];
                --$i;
                --$j;
            } else {
                $o = ($j * $width) + $i;

                if ($matrix[$o - $width] > $matrix[$o - 1]) {
                    --$j;
                } else {
                    --$i;
                }
            }
        }

        return \array_reverse($common);
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use SebastianBergmann\Diff\Differ;

/**
 * Builds a diff string representation in a loose unified diff format
 * listing only changes lines. Does not include line numbers.
 */
final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface
{
    /**
     * @var string
     */
    private $header;

    public function __construct(string $header = "--- Original\n+++ New\n")
    {
        $this->header = $header;
    }

    public function getDiff(array $diff): string
    {
        $buffer = \fopen('php://memory', 'r+b');

        if ('' !== $this->header) {
            \fwrite($buffer, $this->header);

            if ("\n" !== \substr($this->header, -1, 1)) {
                \fwrite($buffer, "\n");
            }
        }

        foreach ($diff as $diffEntry) {
            if ($diffEntry[1] === Differ::ADDED) {
                \fwrite($buffer, '+' . $diffEntry[0]);
            } elseif ($diffEntry[1] === Differ::REMOVED) {
                \fwrite($buffer, '-' . $diffEntry[0]);
            } elseif ($diffEntry[1] === Differ::DIFF_LINE_END_WARNING) {
                \fwrite($buffer, ' ' . $diffEntry[0]);

                continue; // Warnings should not be tested for line break, it will always be there
            } else { /* Not changed (old) 0 */
                continue; // we didn't write the non changs line, so do not add a line break either
            }

            $lc = \substr($diffEntry[0], -1);

            if ($lc !== "\n" && $lc !== "\r") {
                \fwrite($buffer, "\n"); // \No newline at end of file
            }
        }

        $diff = \stream_get_contents($buffer, -1, 0);
        \fclose($buffer);

        return $diff;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

/**
 * Defines how an output builder should take a generated
 * diff array and return a string representation of that diff.
 */
interface DiffOutputBuilderInterface
{
    public function getDiff(array $diff): string;
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use SebastianBergmann\Diff\Differ;

/**
 * Builds a diff string representation in unified diff format in chunks.
 */
final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
    /**
     * @var bool
     */
    private $collapseRanges = true;

    /**
     * @var int >= 0
     */
    private $commonLineThreshold = 6;

    /**
     * @var int >= 0
     */
    private $contextLines = 3;

    /**
     * @var string
     */
    private $header;

    /**
     * @var bool
     */
    private $addLineNumbers;

    public function __construct(string $header = "--- Original\n+++ New\n", bool $addLineNumbers = false)
    {
        $this->header         = $header;
        $this->addLineNumbers = $addLineNumbers;
    }

    public function getDiff(array $diff): string
    {
        $buffer = \fopen('php://memory', 'r+b');

        if ('' !== $this->header) {
            \fwrite($buffer, $this->header);

            if ("\n" !== \substr($this->header, -1, 1)) {
                \fwrite($buffer, "\n");
            }
        }

        if (0 !== \count($diff)) {
            $this->writeDiffHunks($buffer, $diff);
        }

        $diff = \stream_get_contents($buffer, -1, 0);

        \fclose($buffer);

        // If the last char is not a linebreak: add it.
        // This might happen when both the `from` and `to` do not have a trailing linebreak
        $last = \substr($diff, -1);

        return "\n" !== $last && "\r" !== $last
            ? $diff . "\n"
            : $diff
        ;
    }

    private function writeDiffHunks($output, array $diff): void
    {
        // detect "No newline at end of file" and insert into `$diff` if needed

        $upperLimit = \count($diff);

        if (0 === $diff[$upperLimit - 1][1]) {
            $lc = \substr($diff[$upperLimit - 1][0], -1);

            if ("\n" !== $lc) {
                \array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
            }
        } else {
            // search back for the last `+` and `-` line,
            // check if has trailing linebreak, else add under it warning under it
            $toFind = [1 => true, 2 => true];

            for ($i = $upperLimit - 1; $i >= 0; --$i) {
                if (isset($toFind[$diff[$i][1]])) {
                    unset($toFind[$diff[$i][1]]);
                    $lc = \substr($diff[$i][0], -1);

                    if ("\n" !== $lc) {
                        \array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
                    }

                    if (!\count($toFind)) {
                        break;
                    }
                }
            }
        }

        // write hunks to output buffer

        $cutOff      = \max($this->commonLineThreshold, $this->contextLines);
        $hunkCapture = false;
        $sameCount   = $toRange   = $fromRange = 0;
        $toStart     = $fromStart = 1;

        foreach ($diff as $i => $entry) {
            if (0 === $entry[1]) { // same
                if (false === $hunkCapture) {
                    ++$fromStart;
                    ++$toStart;

                    continue;
                }

                ++$sameCount;
                ++$toRange;
                ++$fromRange;

                if ($sameCount === $cutOff) {
                    $contextStartOffset = ($hunkCapture - $this->contextLines) < 0
                        ? $hunkCapture
                        : $this->contextLines
                    ;

                    // note: $contextEndOffset = $this->contextLines;
                    //
                    // because we never go beyond the end of the diff.
                    // with the cutoff/contextlines here the follow is never true;
                    //
                    // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) {
                    //    $contextEndOffset = count($diff) - 1;
                    // }
                    //
                    // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop

                    $this->writeHunk(
                        $diff,
                        $hunkCapture - $contextStartOffset,
                        $i - $cutOff + $this->contextLines + 1,
                        $fromStart - $contextStartOffset,
                        $fromRange - $cutOff + $contextStartOffset + $this->contextLines,
                        $toStart - $contextStartOffset,
                        $toRange - $cutOff + $contextStartOffset + $this->contextLines,
                        $output
                    );

                    $fromStart += $fromRange;
                    $toStart += $toRange;

                    $hunkCapture = false;
                    $sameCount   = $toRange = $fromRange = 0;
                }

                continue;
            }

            $sameCount = 0;

            if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) {
                continue;
            }

            if (false === $hunkCapture) {
                $hunkCapture = $i;
            }

            if (Differ::ADDED === $entry[1]) {
                ++$toRange;
            }

            if (Differ::REMOVED === $entry[1]) {
                ++$fromRange;
            }
        }

        if (false === $hunkCapture) {
            return;
        }

        // we end here when cutoff (commonLineThreshold) was not reached, but we where capturing a hunk,
        // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold

        $contextStartOffset = $hunkCapture - $this->contextLines < 0
            ? $hunkCapture
            : $this->contextLines
        ;

        // prevent trying to write out more common lines than there are in the diff _and_
        // do not write more than configured through the context lines
        $contextEndOffset = \min($sameCount, $this->contextLines);

        $fromRange -= $sameCount;
        $toRange -= $sameCount;

        $this->writeHunk(
            $diff,
            $hunkCapture - $contextStartOffset,
            $i - $sameCount + $contextEndOffset + 1,
            $fromStart - $contextStartOffset,
            $fromRange + $contextStartOffset + $contextEndOffset,
            $toStart - $contextStartOffset,
            $toRange + $contextStartOffset + $contextEndOffset,
            $output
        );
    }

    private function writeHunk(
        array $diff,
        int $diffStartIndex,
        int $diffEndIndex,
        int $fromStart,
        int $fromRange,
        int $toStart,
        int $toRange,
        $output
    ): void {
        if ($this->addLineNumbers) {
            \fwrite($output, '@@ -' . $fromStart);

            if (!$this->collapseRanges || 1 !== $fromRange) {
                \fwrite($output, ',' . $fromRange);
            }

            \fwrite($output, ' +' . $toStart);

            if (!$this->collapseRanges || 1 !== $toRange) {
                \fwrite($output, ',' . $toRange);
            }

            \fwrite($output, " @@\n");
        } else {
            \fwrite($output, "@@ @@\n");
        }

        for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
            if ($diff[$i][1] === Differ::ADDED) {
                \fwrite($output, '+' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::REMOVED) {
                \fwrite($output, '-' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::OLD) {
                \fwrite($output, ' ' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) {
                \fwrite($output, "\n"); // $diff[$i][0]
            } else { /* Not changed (old) Differ::OLD or Warning Differ::DIFF_LINE_END_WARNING */
                \fwrite($output, ' ' . $diff[$i][0]);
            }
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

use SebastianBergmann\Diff\ConfigurationException;
use SebastianBergmann\Diff\Differ;

/**
 * Strict Unified diff output builder.
 *
 * Generates (strict) Unified diff's (unidiffs) with hunks.
 */
final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface
{
    private static $default = [
        'collapseRanges'      => true, // ranges of length one are rendered with the trailing `,1`
        'commonLineThreshold' => 6,    // number of same lines before ending a new hunk and creating a new one (if needed)
        'contextLines'        => 3,    // like `diff:  -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3
        'fromFile'            => null,
        'fromFileDate'        => null,
        'toFile'              => null,
        'toFileDate'          => null,
    ];
    /**
     * @var bool
     */
    private $changed;

    /**
     * @var bool
     */
    private $collapseRanges;

    /**
     * @var int >= 0
     */
    private $commonLineThreshold;

    /**
     * @var string
     */
    private $header;

    /**
     * @var int >= 0
     */
    private $contextLines;

    public function __construct(array $options = [])
    {
        $options = \array_merge(self::$default, $options);

        if (!\is_bool($options['collapseRanges'])) {
            throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']);
        }

        if (!\is_int($options['contextLines']) || $options['contextLines'] < 0) {
            throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']);
        }

        if (!\is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] <= 0) {
            throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']);
        }

        foreach (['fromFile', 'toFile'] as $option) {
            if (!\is_string($options[$option])) {
                throw new ConfigurationException($option, 'a string', $options[$option]);
            }
        }

        foreach (['fromFileDate', 'toFileDate'] as $option) {
            if (null !== $options[$option] && !\is_string($options[$option])) {
                throw new ConfigurationException($option, 'a string or <null>', $options[$option]);
            }
        }

        $this->header = \sprintf(
            "--- %s%s\n+++ %s%s\n",
            $options['fromFile'],
            null === $options['fromFileDate'] ? '' : "\t" . $options['fromFileDate'],
            $options['toFile'],
            null === $options['toFileDate'] ? '' : "\t" . $options['toFileDate']
        );

        $this->collapseRanges      = $options['collapseRanges'];
        $this->commonLineThreshold = $options['commonLineThreshold'];
        $this->contextLines        = $options['contextLines'];
    }

    public function getDiff(array $diff): string
    {
        if (0 === \count($diff)) {
            return '';
        }

        $this->changed = false;

        $buffer = \fopen('php://memory', 'r+b');
        \fwrite($buffer, $this->header);

        $this->writeDiffHunks($buffer, $diff);

        if (!$this->changed) {
            \fclose($buffer);

            return '';
        }

        $diff = \stream_get_contents($buffer, -1, 0);

        \fclose($buffer);

        // If the last char is not a linebreak: add it.
        // This might happen when both the `from` and `to` do not have a trailing linebreak
        $last = \substr($diff, -1);

        return "\n" !== $last && "\r" !== $last
            ? $diff . "\n"
            : $diff
        ;
    }

    private function writeDiffHunks($output, array $diff): void
    {
        // detect "No newline at end of file" and insert into `$diff` if needed

        $upperLimit = \count($diff);

        if (0 === $diff[$upperLimit - 1][1]) {
            $lc = \substr($diff[$upperLimit - 1][0], -1);

            if ("\n" !== $lc) {
                \array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
            }
        } else {
            // search back for the last `+` and `-` line,
            // check if has trailing linebreak, else add under it warning under it
            $toFind = [1 => true, 2 => true];

            for ($i = $upperLimit - 1; $i >= 0; --$i) {
                if (isset($toFind[$diff[$i][1]])) {
                    unset($toFind[$diff[$i][1]]);
                    $lc = \substr($diff[$i][0], -1);

                    if ("\n" !== $lc) {
                        \array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]);
                    }

                    if (!\count($toFind)) {
                        break;
                    }
                }
            }
        }

        // write hunks to output buffer

        $cutOff      = \max($this->commonLineThreshold, $this->contextLines);
        $hunkCapture = false;
        $sameCount   = $toRange = $fromRange = 0;
        $toStart     = $fromStart = 1;

        foreach ($diff as $i => $entry) {
            if (0 === $entry[1]) { // same
                if (false === $hunkCapture) {
                    ++$fromStart;
                    ++$toStart;

                    continue;
                }

                ++$sameCount;
                ++$toRange;
                ++$fromRange;

                if ($sameCount === $cutOff) {
                    $contextStartOffset = ($hunkCapture - $this->contextLines) < 0
                        ? $hunkCapture
                        : $this->contextLines
                    ;

                    // note: $contextEndOffset = $this->contextLines;
                    //
                    // because we never go beyond the end of the diff.
                    // with the cutoff/contextlines here the follow is never true;
                    //
                    // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) {
                    //    $contextEndOffset = count($diff) - 1;
                    // }
                    //
                    // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop

                    $this->writeHunk(
                        $diff,
                        $hunkCapture - $contextStartOffset,
                        $i - $cutOff + $this->contextLines + 1,
                        $fromStart - $contextStartOffset,
                        $fromRange - $cutOff + $contextStartOffset + $this->contextLines,
                        $toStart - $contextStartOffset,
                        $toRange - $cutOff + $contextStartOffset + $this->contextLines,
                        $output
                    );

                    $fromStart += $fromRange;
                    $toStart += $toRange;

                    $hunkCapture = false;
                    $sameCount   = $toRange = $fromRange = 0;
                }

                continue;
            }

            $sameCount = 0;

            if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) {
                continue;
            }

            $this->changed = true;

            if (false === $hunkCapture) {
                $hunkCapture = $i;
            }

            if (Differ::ADDED === $entry[1]) { // added
                ++$toRange;
            }

            if (Differ::REMOVED === $entry[1]) { // removed
                ++$fromRange;
            }
        }

        if (false === $hunkCapture) {
            return;
        }

        // we end here when cutoff (commonLineThreshold) was not reached, but we where capturing a hunk,
        // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold

        $contextStartOffset = $hunkCapture - $this->contextLines < 0
            ? $hunkCapture
            : $this->contextLines
        ;

        // prevent trying to write out more common lines than there are in the diff _and_
        // do not write more than configured through the context lines
        $contextEndOffset = \min($sameCount, $this->contextLines);

        $fromRange -= $sameCount;
        $toRange -= $sameCount;

        $this->writeHunk(
            $diff,
            $hunkCapture - $contextStartOffset,
            $i - $sameCount + $contextEndOffset + 1,
            $fromStart - $contextStartOffset,
            $fromRange + $contextStartOffset + $contextEndOffset,
            $toStart - $contextStartOffset,
            $toRange + $contextStartOffset + $contextEndOffset,
            $output
        );
    }

    private function writeHunk(
        array $diff,
        int $diffStartIndex,
        int $diffEndIndex,
        int $fromStart,
        int $fromRange,
        int $toStart,
        int $toRange,
        $output
    ): void {
        \fwrite($output, '@@ -' . $fromStart);

        if (!$this->collapseRanges || 1 !== $fromRange) {
            \fwrite($output, ',' . $fromRange);
        }

        \fwrite($output, ' +' . $toStart);

        if (!$this->collapseRanges || 1 !== $toRange) {
            \fwrite($output, ',' . $toRange);
        }

        \fwrite($output, " @@\n");

        for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
            if ($diff[$i][1] === Differ::ADDED) {
                $this->changed = true;
                \fwrite($output, '+' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::REMOVED) {
                $this->changed = true;
                \fwrite($output, '-' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::OLD) {
                \fwrite($output, ' ' . $diff[$i][0]);
            } elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) {
                $this->changed = true;
                \fwrite($output, $diff[$i][0]);
            }
            //} elseif ($diff[$i][1] === Differ::DIFF_LINE_END_WARNING) { // custom comment inserted by PHPUnit/diff package
                //  skip
            //} else {
                //  unknown/invalid
            //}
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff\Output;

abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface
{
    /**
     * Takes input of the diff array and returns the common parts.
     * Iterates through diff line by line.
     *
     * @param array $diff
     * @param int   $lineThreshold
     *
     * @return array
     */
    protected function getCommonChunks(array $diff, int $lineThreshold = 5): array
    {
        $diffSize     = \count($diff);
        $capturing    = false;
        $chunkStart   = 0;
        $chunkSize    = 0;
        $commonChunks = [];

        for ($i = 0; $i < $diffSize; ++$i) {
            if ($diff[$i][1] === 0 /* OLD */) {
                if ($capturing === false) {
                    $capturing  = true;
                    $chunkStart = $i;
                    $chunkSize  = 0;
                } else {
                    ++$chunkSize;
                }
            } elseif ($capturing !== false) {
                if ($chunkSize >= $lineThreshold) {
                    $commonChunks[$chunkStart] = $chunkStart + $chunkSize;
                }

                $capturing = false;
            }
        }

        if ($capturing !== false && $chunkSize >= $lineThreshold) {
            $commonChunks[$chunkStart] = $chunkStart + $chunkSize;
        }

        return $commonChunks;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

interface LongestCommonSubsequenceCalculator
{
    /**
     * Calculates the longest common subsequence of two arrays.
     *
     * @param array $from
     * @param array $to
     *
     * @return array
     */
    public function calculate(array $from, array $to): array;
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class Chunk
{
    /**
     * @var int
     */
    private $start;

    /**
     * @var int
     */
    private $startRange;

    /**
     * @var int
     */
    private $end;

    /**
     * @var int
     */
    private $endRange;

    /**
     * @var Line[]
     */
    private $lines;

    public function __construct(int $start = 0, int $startRange = 1, int $end = 0, int $endRange = 1, array $lines = [])
    {
        $this->start      = $start;
        $this->startRange = $startRange;
        $this->end        = $end;
        $this->endRange   = $endRange;
        $this->lines      = $lines;
    }

    public function getStart(): int
    {
        return $this->start;
    }

    public function getStartRange(): int
    {
        return $this->startRange;
    }

    public function getEnd(): int
    {
        return $this->end;
    }

    public function getEndRange(): int
    {
        return $this->endRange;
    }

    /**
     * @return Line[]
     */
    public function getLines(): array
    {
        return $this->lines;
    }

    /**
     * @param Line[] $lines
     */
    public function setLines(array $lines): void
    {
        foreach ($lines as $line) {
            if (!$line instanceof Line) {
                throw new InvalidArgumentException;
            }
        }

        $this->lines = $lines;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;

/**
 * Diff implementation.
 */
final class Differ
{
    public const OLD                     = 0;
    public const ADDED                   = 1;
    public const REMOVED                 = 2;
    public const DIFF_LINE_END_WARNING   = 3;
    public const NO_LINE_END_EOF_WARNING = 4;

    /**
     * @var DiffOutputBuilderInterface
     */
    private $outputBuilder;

    /**
     * @param DiffOutputBuilderInterface $outputBuilder
     *
     * @throws InvalidArgumentException
     */
    public function __construct($outputBuilder = null)
    {
        if ($outputBuilder instanceof DiffOutputBuilderInterface) {
            $this->outputBuilder = $outputBuilder;
        } elseif (null === $outputBuilder) {
            $this->outputBuilder = new UnifiedDiffOutputBuilder;
        } elseif (\is_string($outputBuilder)) {
            // PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3 support
            // @see https://github.com/sebastianbergmann/phpunit/issues/2734#issuecomment-314514056
            // @deprecated
            $this->outputBuilder = new UnifiedDiffOutputBuilder($outputBuilder);
        } else {
            throw new InvalidArgumentException(
                \sprintf(
                    'Expected builder to be an instance of DiffOutputBuilderInterface, <null> or a string, got %s.',
                    \is_object($outputBuilder) ? 'instance of "' . \get_class($outputBuilder) . '"' : \gettype($outputBuilder) . ' "' . $outputBuilder . '"'
                )
            );
        }
    }

    /**
     * Returns the diff between two arrays or strings as string.
     *
     * @param array|string                            $from
     * @param array|string                            $to
     * @param null|LongestCommonSubsequenceCalculator $lcs
     *
     * @return string
     */
    public function diff($from, $to, LongestCommonSubsequenceCalculator $lcs = null): string
    {
        $diff = $this->diffToArray(
            $this->normalizeDiffInput($from),
            $this->normalizeDiffInput($to),
            $lcs
        );

        return $this->outputBuilder->getDiff($diff);
    }

    /**
     * Returns the diff between two arrays or strings as array.
     *
     * Each array element contains two elements:
     *   - [0] => mixed $token
     *   - [1] => 2|1|0
     *
     * - 2: REMOVED: $token was removed from $from
     * - 1: ADDED: $token was added to $from
     * - 0: OLD: $token is not changed in $to
     *
     * @param array|string                       $from
     * @param array|string                       $to
     * @param LongestCommonSubsequenceCalculator $lcs
     *
     * @return array
     */
    public function diffToArray($from, $to, LongestCommonSubsequenceCalculator $lcs = null): array
    {
        if (\is_string($from)) {
            $from = $this->splitStringByLines($from);
        } elseif (!\is_array($from)) {
            throw new InvalidArgumentException('"from" must be an array or string.');
        }

        if (\is_string($to)) {
            $to = $this->splitStringByLines($to);
        } elseif (!\is_array($to)) {
            throw new InvalidArgumentException('"to" must be an array or string.');
        }

        [$from, $to, $start, $end] = self::getArrayDiffParted($from, $to);

        if ($lcs === null) {
            $lcs = $this->selectLcsImplementation($from, $to);
        }

        $common = $lcs->calculate(\array_values($from), \array_values($to));
        $diff   = [];

        foreach ($start as $token) {
            $diff[] = [$token, self::OLD];
        }

        \reset($from);
        \reset($to);

        foreach ($common as $token) {
            while (($fromToken = \reset($from)) !== $token) {
                $diff[] = [\array_shift($from), self::REMOVED];
            }

            while (($toToken = \reset($to)) !== $token) {
                $diff[] = [\array_shift($to), self::ADDED];
            }

            $diff[] = [$token, self::OLD];

            \array_shift($from);
            \array_shift($to);
        }

        while (($token = \array_shift($from)) !== null) {
            $diff[] = [$token, self::REMOVED];
        }

        while (($token = \array_shift($to)) !== null) {
            $diff[] = [$token, self::ADDED];
        }

        foreach ($end as $token) {
            $diff[] = [$token, self::OLD];
        }

        if ($this->detectUnmatchedLineEndings($diff)) {
            \array_unshift($diff, ["#Warning: Strings contain different line endings!\n", self::DIFF_LINE_END_WARNING]);
        }

        return $diff;
    }

    /**
     * Casts variable to string if it is not a string or array.
     *
     * @param mixed $input
     *
     * @return array|string
     */
    private function normalizeDiffInput($input)
    {
        if (!\is_array($input) && !\is_string($input)) {
            return (string) $input;
        }

        return $input;
    }

    /**
     * Checks if input is string, if so it will split it line-by-line.
     *
     * @param string $input
     *
     * @return array
     */
    private function splitStringByLines(string $input): array
    {
        return \preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    }

    /**
     * @param array $from
     * @param array $to
     *
     * @return LongestCommonSubsequenceCalculator
     */
    private function selectLcsImplementation(array $from, array $to): LongestCommonSubsequenceCalculator
    {
        // We do not want to use the time-efficient implementation if its memory
        // footprint will probably exceed this value. Note that the footprint
        // calculation is only an estimation for the matrix and the LCS method
        // will typically allocate a bit more memory than this.
        $memoryLimit = 100 * 1024 * 1024;

        if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
            return new MemoryEfficientLongestCommonSubsequenceCalculator;
        }

        return new TimeEfficientLongestCommonSubsequenceCalculator;
    }

    /**
     * Calculates the estimated memory footprint for the DP-based method.
     *
     * @param array $from
     * @param array $to
     *
     * @return float|int
     */
    private function calculateEstimatedFootprint(array $from, array $to)
    {
        $itemSize = PHP_INT_SIZE === 4 ? 76 : 144;

        return $itemSize * \min(\count($from), \count($to)) ** 2;
    }

    /**
     * Returns true if line ends don't match in a diff.
     *
     * @param array $diff
     *
     * @return bool
     */
    private function detectUnmatchedLineEndings(array $diff): bool
    {
        $newLineBreaks = ['' => true];
        $oldLineBreaks = ['' => true];

        foreach ($diff as $entry) {
            if (self::OLD === $entry[1]) {
                $ln                 = $this->getLinebreak($entry[0]);
                $oldLineBreaks[$ln] = true;
                $newLineBreaks[$ln] = true;
            } elseif (self::ADDED === $entry[1]) {
                $newLineBreaks[$this->getLinebreak($entry[0])] = true;
            } elseif (self::REMOVED === $entry[1]) {
                $oldLineBreaks[$this->getLinebreak($entry[0])] = true;
            }
        }

        // if either input or output is a single line without breaks than no warning should be raised
        if (['' => true] === $newLineBreaks || ['' => true] === $oldLineBreaks) {
            return false;
        }

        // two way compare
        foreach ($newLineBreaks as $break => $set) {
            if (!isset($oldLineBreaks[$break])) {
                return true;
            }
        }

        foreach ($oldLineBreaks as $break => $set) {
            if (!isset($newLineBreaks[$break])) {
                return true;
            }
        }

        return false;
    }

    private function getLinebreak($line): string
    {
        if (!\is_string($line)) {
            return '';
        }

        $lc = \substr($line, -1);

        if ("\r" === $lc) {
            return "\r";
        }

        if ("\n" !== $lc) {
            return '';
        }

        if ("\r\n" === \substr($line, -2)) {
            return "\r\n";
        }

        return "\n";
    }

    private static function getArrayDiffParted(array &$from, array &$to): array
    {
        $start = [];
        $end   = [];

        \reset($to);

        foreach ($from as $k => $v) {
            $toK = \key($to);

            if ($toK === $k && $v === $to[$k]) {
                $start[$k] = $v;

                unset($from[$k], $to[$k]);
            } else {
                break;
            }
        }

        \end($from);
        \end($to);

        do {
            $fromK = \key($from);
            $toK   = \key($to);

            if (null === $fromK || null === $toK || \current($from) !== \current($to)) {
                break;
            }

            \prev($from);
            \prev($to);

            $end = [$fromK => $from[$fromK]] + $end;
            unset($from[$fromK], $to[$toK]);
        } while (true);

        return [$from, $to, $start, $end];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class Line
{
    public const ADDED     = 1;
    public const REMOVED   = 2;
    public const UNCHANGED = 3;

    /**
     * @var int
     */
    private $type;

    /**
     * @var string
     */
    private $content;

    public function __construct(int $type = self::UNCHANGED, string $content = '')
    {
        $this->type    = $type;
        $this->content = $content;
    }

    public function getContent(): string
    {
        return $this->content;
    }

    public function getType(): int
    {
        return $this->type;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class ConfigurationException extends InvalidArgumentException
{
    /**
     * @param string          $option
     * @param string          $expected
     * @param mixed           $value
     * @param int             $code
     * @param null|\Exception $previous
     */
    public function __construct(
        string $option,
        string $expected,
        $value,
        int $code = 0,
        \Exception $previous = null
    ) {
        parent::__construct(
            \sprintf(
                'Option "%s" must be %s, got "%s".',
                $option,
                $expected,
                \is_object($value) ? \get_class($value) : (null === $value ? '<null>' : \gettype($value) . '#' . $value)
            ),
            $code,
            $previous
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

interface Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/diff.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\Diff;

final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
{
    /**
     * {@inheritdoc}
     */
    public function calculate(array $from, array $to): array
    {
        $cFrom = \count($from);
        $cTo   = \count($to);

        if ($cFrom === 0) {
            return [];
        }

        if ($cFrom === 1) {
            if (\in_array($from[0], $to, true)) {
                return [$from[0]];
            }

            return [];
        }

        $i         = (int) ($cFrom / 2);
        $fromStart = \array_slice($from, 0, $i);
        $fromEnd   = \array_slice($from, $i);
        $llB       = $this->length($fromStart, $to);
        $llE       = $this->length(\array_reverse($fromEnd), \array_reverse($to));
        $jMax      = 0;
        $max       = 0;

        for ($j = 0; $j <= $cTo; $j++) {
            $m = $llB[$j] + $llE[$cTo - $j];

            if ($m >= $max) {
                $max  = $m;
                $jMax = $j;
            }
        }

        $toStart = \array_slice($to, 0, $jMax);
        $toEnd   = \array_slice($to, $jMax);

        return \array_merge(
            $this->calculate($fromStart, $toStart),
            $this->calculate($fromEnd, $toEnd)
        );
    }

    private function length(array $from, array $to): array
    {
        $current = \array_fill(0, \count($to) + 1, 0);
        $cFrom   = \count($from);
        $cTo     = \count($to);

        for ($i = 0; $i < $cFrom; $i++) {
            $prev = $current;

            for ($j = 0; $j < $cTo; $j++) {
                if ($from[$i] === $to[$j]) {
                    $current[$j + 1] = $prev[$j] + 1;
                } else {
                    $current[$j + 1] = \max($current[$j], $prev[$j + 1]);
                }
            }
        }

        return $current;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuite>
        <directory suffix="Test.php">tests</directory>
    </testsuite>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
Recursion Context

Copyright (c) 2002-2017, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
<?xml version="1.0" encoding="UTF-8"?>
<project name="recursion-context" default="setup">
 <target name="setup" depends="clean,composer"/>

 <target name="clean" description="Cleanup build artifacts">
  <delete dir="${basedir}/vendor"/>
  <delete file="${basedir}/composer.lock"/>
 </target>

 <target name="composer" depends="clean" description="Install dependencies with Composer">
  <exec executable="composer" taskname="composer">
   <arg value="update"/>
   <arg value="--no-interaction"/>
   <arg value="--no-progress"/>
   <arg value="--no-ansi"/>
   <arg value="--no-suggest"/>
   <arg value="--optimize-autoloader"/>
   <arg value="--prefer-stable"/>
  </exec>
 </target>
</project>
<?php
/*
 * This file is part of the Recursion Context package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\RecursionContext;

use PHPUnit\Framework\TestCase;

/**
 * @covers SebastianBergmann\RecursionContext\Context
 */
class ContextTest extends TestCase
{
    /**
     * @var \SebastianBergmann\RecursionContext\Context
     */
    private $context;

    protected function setUp()
    {
        $this->context = new Context();
    }

    public function failsProvider()
    {
        return array(
            array(true),
            array(false),
            array(null),
            array('string'),
            array(1),
            array(1.5),
            array(fopen('php://memory', 'r'))
        );
    }

    public function valuesProvider()
    {
        $obj2      = new \stdClass();
        $obj2->foo = 'bar';

        $obj3 = (object) array(1,2,"Test\r\n",4,5,6,7,8);

        $obj = new \stdClass();
        //@codingStandardsIgnoreStart
        $obj->null = null;
        //@codingStandardsIgnoreEnd
        $obj->boolean     = true;
        $obj->integer     = 1;
        $obj->double      = 1.2;
        $obj->string      = '1';
        $obj->text        = "this\nis\na\nvery\nvery\nvery\nvery\nvery\nvery\rlong\n\rtext";
        $obj->object      = $obj2;
        $obj->objectagain = $obj2;
        $obj->array       = array('foo' => 'bar');
        $obj->array2      = array(1,2,3,4,5,6);
        $obj->array3      = array($obj, $obj2, $obj3);
        $obj->self        = $obj;

        $storage = new \SplObjectStorage();
        $storage->attach($obj2);
        $storage->foo = $obj2;

        return array(
            array($obj, spl_object_hash($obj)),
            array($obj2, spl_object_hash($obj2)),
            array($obj3, spl_object_hash($obj3)),
            array($storage, spl_object_hash($storage)),
            array($obj->array, 0),
            array($obj->array2, 0),
            array($obj->array3, 0)
        );
    }

    /**
     * @covers       SebastianBergmann\RecursionContext\Context::add
     * @uses         SebastianBergmann\RecursionContext\InvalidArgumentException
     * @dataProvider failsProvider
     */
    public function testAddFails($value)
    {
        $this->expectException(Exception::class);
        $this->expectExceptionMessage('Only arrays and objects are supported');

        $this->context->add($value);
    }

    /**
     * @covers       SebastianBergmann\RecursionContext\Context::contains
     * @uses         SebastianBergmann\RecursionContext\InvalidArgumentException
     * @dataProvider failsProvider
     */
    public function testContainsFails($value)
    {
        $this->expectException(Exception::class);
        $this->expectExceptionMessage('Only arrays and objects are supported');

        $this->context->contains($value);
    }

    /**
     * @covers       SebastianBergmann\RecursionContext\Context::add
     * @dataProvider valuesProvider
     */
    public function testAdd($value, $key)
    {
        $this->assertEquals($key, $this->context->add($value));

        // Test we get the same key on subsequent adds
        $this->assertEquals($key, $this->context->add($value));
    }

    /**
     * @covers       SebastianBergmann\RecursionContext\Context::contains
     * @uses         SebastianBergmann\RecursionContext\Context::add
     * @depends      testAdd
     * @dataProvider valuesProvider
     */
    public function testContainsFound($value, $key)
    {
        $this->context->add($value);
        $this->assertEquals($key, $this->context->contains($value));

        // Test we get the same key on subsequent calls
        $this->assertEquals($key, $this->context->contains($value));
    }

    /**
     * @covers       SebastianBergmann\RecursionContext\Context::contains
     * @dataProvider valuesProvider
     */
    public function testContainsNotFound($value)
    {
        $this->assertFalse($this->context->contains($value));
    }
}
# Recursion Context

...

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/recursion-context

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/recursion-context

/.idea
/composer.lock
/vendor
language: php

php:
  - 7.0
  - 7.0snapshot
  - 7.1
  - 7.1snapshot
  - master

sudo: false

before_install:
  - composer self-update
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest --optimize-autoloader --prefer-stable

script:
  - ./vendor/bin/phpunit

notifications:
  email: false
{
    "name": "sebastian/recursion-context",
    "description": "Provides functionality to recursively process PHP variables",
    "homepage": "http://www.github.com/sebastianbergmann/recursion-context",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        },
        {
            "name": "Jeff Welch",
            "email": "whatthejeff@gmail.com"
        },
        {
            "name": "Adam Harvey",
            "email": "aharvey@php.net"
        }
    ],
    "require": {
        "php": ">=7.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.0.x-dev"
        }
    }
}
<?php
/*
 * This file is part of the Recursion Context package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\RecursionContext;

/**
 */
final class InvalidArgumentException extends \InvalidArgumentException implements Exception
{
}
<?php
/*
 * This file is part of the Recursion Context package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\RecursionContext;

/**
 * A context containing previously processed arrays and objects
 * when recursively processing a value.
 */
final class Context
{
    /**
     * @var array[]
     */
    private $arrays;

    /**
     * @var \SplObjectStorage
     */
    private $objects;

    /**
     * Initialises the context
     */
    public function __construct()
    {
        $this->arrays  = array();
        $this->objects = new \SplObjectStorage;
    }

    /**
     * Adds a value to the context.
     *
     * @param array|object $value The value to add.
     *
     * @return int|string The ID of the stored value, either as a string or integer.
     *
     * @throws InvalidArgumentException Thrown if $value is not an array or object
     */
    public function add(&$value)
    {
        if (is_array($value)) {
            return $this->addArray($value);
        } elseif (is_object($value)) {
            return $this->addObject($value);
        }

        throw new InvalidArgumentException(
            'Only arrays and objects are supported'
        );
    }

    /**
     * Checks if the given value exists within the context.
     *
     * @param array|object $value The value to check.
     *
     * @return int|string|false The string or integer ID of the stored value if it has already been seen, or false if the value is not stored.
     *
     * @throws InvalidArgumentException Thrown if $value is not an array or object
     */
    public function contains(&$value)
    {
        if (is_array($value)) {
            return $this->containsArray($value);
        } elseif (is_object($value)) {
            return $this->containsObject($value);
        }

        throw new InvalidArgumentException(
            'Only arrays and objects are supported'
        );
    }

    /**
     * @param array $array
     *
     * @return bool|int
     */
    private function addArray(array &$array)
    {
        $key = $this->containsArray($array);

        if ($key !== false) {
            return $key;
        }

        $key            = count($this->arrays);
        $this->arrays[] = &$array;

        if (!isset($array[PHP_INT_MAX]) && !isset($array[PHP_INT_MAX - 1])) {
            $array[] = $key;
            $array[] = $this->objects;
        } else { /* cover the improbable case too */
            do {
                $key = random_int(PHP_INT_MIN, PHP_INT_MAX);
            } while (isset($array[$key]));

            $array[$key] = $key;

            do {
                $key = random_int(PHP_INT_MIN, PHP_INT_MAX);
            } while (isset($array[$key]));

            $array[$key] = $this->objects;
        }

        return $key;
    }

    /**
     * @param object $object
     *
     * @return string
     */
    private function addObject($object)
    {
        if (!$this->objects->contains($object)) {
            $this->objects->attach($object);
        }

        return spl_object_hash($object);
    }

    /**
     * @param array $array
     *
     * @return int|false
     */
    private function containsArray(array &$array)
    {
        $end = array_slice($array, -2);

        return isset($end[1]) && $end[1] === $this->objects ? $end[0] : false;
    }

    /**
     * @param object $value
     *
     * @return string|false
     */
    private function containsObject($value)
    {
        if ($this->objects->contains($value)) {
            return spl_object_hash($value);
        }

        return false;
    }

    public function __destruct()
    {
        foreach ($this->arrays as &$array) {
            if (is_array($array)) {
                array_pop($array);
                array_pop($array);
            }
        }
    }
}
<?php
/*
 * This file is part of the Recursion Context package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann\RecursionContext;

/**
 */
interface Exception
{
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.2/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         executionOrder="depends,defects"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         colors="true"
         verbose="true">
    <testsuites>
        <testsuite name="unit">
            <directory suffix="Test.php">tests/unit</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
sebastian/type

Copyright (c) 2019, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [1.1.4] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.2` to `>=7.2`

## [1.1.3] - 2019-07-02

### Fixed

* Fixed class name comparison in `ObjectType` to be case insensitive

## [1.1.2] - 2019-06-19

### Fixed

* Fixed handling of `object` type

## [1.1.1] - 2019-06-08

### Fixed

* Fixed autoloading of `callback_function.php` fixture file

## [1.1.0] - 2019-06-07

### Added

* Added support for `callable` type
* Added support for `iterable` type

## [1.0.0] - 2019-06-06

* Initial release based on [code contributed by Michel Hartmann to PHPUnit](https://github.com/sebastianbergmann/phpunit/pull/3673)

[1.1.4]: https://github.com/sebastianbergmann/type/compare/1.1.3...1.1.4
[1.1.3]: https://github.com/sebastianbergmann/type/compare/1.1.2...1.1.3
[1.1.2]: https://github.com/sebastianbergmann/type/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/sebastianbergmann/type/compare/1.1.0...1.1.1
[1.1.0]: https://github.com/sebastianbergmann/type/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/sebastianbergmann/type/compare/ff74aa41746bd8d10e931843ebf37d42da513ede...1.0.0
<?xml version="1.0" encoding="UTF-8"?>
<project name="type" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="${basedir}/tools/composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>

    <target name="update-tools">
        <exec executable="phive" taskname="phive">
            <arg value="--no-progress"/>
            <arg value="update"/>
        </exec>

        <exec executable="${basedir}/tools/composer" taskname="composer">
            <arg value="self-update"/>
        </exec>
    </target>
</project>

<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\NullType
 */
final class NullTypeTest extends TestCase
{
    /**
     * @var NullType
     */
    private $type;

    protected function setUp(): void
    {
        $this->type = new NullType;
    }

    /**
     * @dataProvider assignableTypes
     */
    public function testIsAssignable(Type $assignableType): void
    {
        $this->assertTrue($this->type->isAssignable($assignableType));
    }

    public function assignableTypes(): array
    {
        return [
            [new SimpleType('int', false)],
            [new SimpleType('int', true)],
            [new ObjectType(TypeName::fromQualifiedName(self::class), false)],
            [new ObjectType(TypeName::fromQualifiedName(self::class), true)],
            [new UnknownType],
        ];
    }

    /**
     * @dataProvider notAssignable
     */
    public function testIsNotAssignable(Type $assignedType): void
    {
        $this->assertFalse($this->type->isAssignable($assignedType));
    }

    public function notAssignable(): array
    {
        return [
            'void' => [new VoidType],
        ];
    }

    public function testAllowsNull(): void
    {
        $this->assertTrue($this->type->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $this->assertEquals('', $this->type->getReturnTypeDeclaration());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\VoidType
 */
final class VoidTypeTest extends TestCase
{
    /**
     * @dataProvider assignableTypes
     */
    public function testIsAssignable(Type $assignableType): void
    {
        $type = new VoidType;

        $this->assertTrue($type->isAssignable($assignableType));
    }

    public function assignableTypes(): array
    {
        return [
            [new VoidType],
        ];
    }

    /**
     * @dataProvider notAssignableTypes
     */
    public function testIsNotAssignable(Type $assignableType): void
    {
        $type = new VoidType;

        $this->assertFalse($type->isAssignable($assignableType));
    }

    public function notAssignableTypes(): array
    {
        return [
            [new SimpleType('int', false)],
            [new SimpleType('int', true)],
            [new ObjectType(TypeName::fromQualifiedName(self::class), false)],
            [new ObjectType(TypeName::fromQualifiedName(self::class), true)],
            [new UnknownType],
        ];
    }

    public function testNotAllowNull(): void
    {
        $type = new VoidType;

        $this->assertFalse($type->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $type = new VoidType;

        $this->assertEquals(': void', $type->getReturnTypeDeclaration());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\Iterator;

/**
 * @covers \SebastianBergmann\Type\IterableType
 *
 * @uses \SebastianBergmann\Type\Type
 * @uses \SebastianBergmann\Type\TypeName
 * @uses \SebastianBergmann\Type\ObjectType
 * @uses \SebastianBergmann\Type\SimpleType
 */
final class IterableTypeTest extends TestCase
{
    /**
     * @var IterableType
     */
    private $type;

    protected function setUp(): void
    {
        $this->type = new IterableType(false);
    }

    public function testMayDisallowNull(): void
    {
        $this->assertFalse($this->type->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $this->assertEquals(': iterable', $this->type->getReturnTypeDeclaration());
    }

    public function testMayAllowNull(): void
    {
        $type = new IterableType(true);

        $this->assertTrue($type->allowsNull());
    }

    public function testCanGenerateNullableReturnTypeDeclaration(): void
    {
        $type = new IterableType(true);

        $this->assertEquals(': ?iterable', $type->getReturnTypeDeclaration());
    }

    public function testNullCanBeAssignedToNullableIterable(): void
    {
        $type = new IterableType(true);

        $this->assertTrue($type->isAssignable(new NullType));
    }

    public function testIterableCanBeAssignedToIterable(): void
    {
        $this->assertTrue($this->type->isAssignable(new IterableType(false)));
    }

    public function testArrayCanBeAssignedToIterable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue([], false)
            )
        );
    }

    public function testIteratorCanBeAssignedToIterable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue(new Iterator, false)
            )
        );
    }

    public function testSomethingThatIsNotIterableCannotBeAssignedToIterable(): void
    {
        $this->assertFalse(
            $this->type->isAssignable(
                Type::fromValue(null, false)
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\ClassWithCallbackMethods;
use SebastianBergmann\Type\TestFixture\ClassWithInvokeMethod;

/**
 * @covers \SebastianBergmann\Type\CallableType
 *
 * @uses \SebastianBergmann\Type\Type
 * @uses \SebastianBergmann\Type\ObjectType
 * @uses \SebastianBergmann\Type\SimpleType
 * @uses \SebastianBergmann\Type\TypeName
 */
final class CallableTypeTest extends TestCase
{
    /**
     * @var CallableType
     */
    private $type;

    protected function setUp(): void
    {
        $this->type = new CallableType(false);
    }

    public function testMayDisallowNull(): void
    {
        $this->assertFalse($this->type->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $this->assertEquals(': callable', $this->type->getReturnTypeDeclaration());
    }

    public function testMayAllowNull(): void
    {
        $type = new CallableType(true);

        $this->assertTrue($type->allowsNull());
    }

    public function testCanGenerateNullableReturnTypeDeclaration(): void
    {
        $type = new CallableType(true);

        $this->assertEquals(': ?callable', $type->getReturnTypeDeclaration());
    }

    public function testNullCanBeAssignedToNullableCallable(): void
    {
        $type = new CallableType(true);

        $this->assertTrue($type->isAssignable(new NullType));
    }

    public function testCallableCanBeAssignedToCallable(): void
    {
        $this->assertTrue($this->type->isAssignable(new CallableType(false)));
    }

    public function testClosureCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                new ObjectType(
                    TypeName::fromQualifiedName(\Closure::class),
                    false
                )
            )
        );
    }

    public function testInvokableCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                new ObjectType(
                    TypeName::fromQualifiedName(ClassWithInvokeMethod::class),
                    false
                )
            )
        );
    }

    public function testStringWithFunctionNameCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue('SebastianBergmann\Type\TestFixture\callback_function', false)
            )
        );
    }

    public function testStringWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue(ClassWithCallbackMethods::class . '::staticCallback', false)
            )
        );
    }

    public function testArrayWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue([ClassWithCallbackMethods::class, 'staticCallback'], false)
            )
        );
    }

    public function testArrayWithClassNameAndInstanceMethodNameCanBeAssignedToCallable(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                Type::fromValue([new ClassWithCallbackMethods, 'nonStaticCallback'], false)
            )
        );
    }

    public function testSomethingThatIsNotCallableCannotBeAssignedToCallable(): void
    {
        $this->assertFalse(
            $this->type->isAssignable(
                Type::fromValue(null, false)
            )
        );
    }

    public function testObjectWithoutInvokeMethodCannotBeAssignedToCallable(): void
    {
        $this->assertFalse(
            $this->type->isAssignable(
                Type::fromValue(new class {
                }, false)
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;
use SebastianBergmann\Type\TestFixture\ChildClass;
use SebastianBergmann\Type\TestFixture\ParentClass;

/**
 * @covers \SebastianBergmann\Type\ObjectType
 *
 * @uses \SebastianBergmann\Type\TypeName
 * @uses \SebastianBergmann\Type\Type
 * @uses \SebastianBergmann\Type\SimpleType
 */
final class ObjectTypeTest extends TestCase
{
    /**
     * @var ObjectType
     */
    private $childClass;

    /**
     * @var ObjectType
     */
    private $parentClass;

    protected function setUp(): void
    {
        $this->childClass = new ObjectType(
            TypeName::fromQualifiedName(ChildClass::class),
            false
        );

        $this->parentClass = new ObjectType(
            TypeName::fromQualifiedName(ParentClass::class),
            false
        );
    }

    public function testParentIsNotAssignableToChild(): void
    {
        $this->assertFalse($this->childClass->isAssignable($this->parentClass));
    }

    public function testChildIsAssignableToParent(): void
    {
        $this->assertTrue($this->parentClass->isAssignable($this->childClass));
    }

    public function testClassIsAssignableToSelf(): void
    {
        $this->assertTrue($this->parentClass->isAssignable($this->parentClass));
    }

    public function testSimpleTypeIsNotAssignableToClass(): void
    {
        $this->assertFalse($this->parentClass->isAssignable(new SimpleType('int', false)));
    }

    public function testClassFromOneNamespaceIsNotAssignableToClassInOtherNamespace(): void
    {
        $classFromNamespaceA = new ObjectType(
            TypeName::fromQualifiedName(\someNamespaceA\NamespacedClass::class),
            false
        );

        $classFromNamespaceB = new ObjectType(
            TypeName::fromQualifiedName(\someNamespaceB\NamespacedClass::class),
            false
        );
        $this->assertFalse($classFromNamespaceA->isAssignable($classFromNamespaceB));
    }

    public function testClassIsAssignableToSelfCaseInsensitively(): void
    {
        $classLowercased = new ObjectType(
            TypeName::fromQualifiedName(\strtolower(ParentClass::class)),
            false
        );

        $this->assertTrue($this->parentClass->isAssignable($classLowercased));
    }

    public function testNullIsAssignableToNullableType(): void
    {
        $someClass = new ObjectType(
            TypeName::fromQualifiedName(ParentClass::class),
            true
        );
        $this->assertTrue($someClass->isAssignable(Type::fromValue(null, true)));
    }

    public function testNullIsNotAssignableToNotNullableType(): void
    {
        $someClass = new ObjectType(
            TypeName::fromQualifiedName(ParentClass::class),
            false
        );

        $this->assertFalse($someClass->isAssignable(Type::fromValue(null, true)));
    }

    public function testPreservesNullNotAllowed(): void
    {
        $someClass = new ObjectType(
            TypeName::fromQualifiedName(ParentClass::class),
            false
        );

        $this->assertFalse($someClass->allowsNull());
    }

    public function testPreservesNullAllowed(): void
    {
        $someClass = new ObjectType(
            TypeName::fromQualifiedName(ParentClass::class),
            true
        );

        $this->assertTrue($someClass->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $this->assertEquals(': SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->getReturnTypeDeclaration());
    }

    public function testHasClassName(): void
    {
        $this->assertEquals('SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->className()->getQualifiedName());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\TypeName
 */
final class TypeNameTest extends TestCase
{
    public function testFromReflection(): void
    {
        $class    = new \ReflectionClass(TypeName::class);
        $typeName = TypeName::fromReflection($class);

        $this->assertTrue($typeName->isNamespaced());
        $this->assertEquals('SebastianBergmann\\Type', $typeName->getNamespaceName());
        $this->assertEquals(TypeName::class, $typeName->getQualifiedName());
        $this->assertEquals('TypeName', $typeName->getSimpleName());
    }

    public function testFromQualifiedName(): void
    {
        $typeName = TypeName::fromQualifiedName('PHPUnit\\Framework\\MockObject\\TypeName');

        $this->assertTrue($typeName->isNamespaced());
        $this->assertEquals('PHPUnit\\Framework\\MockObject', $typeName->getNamespaceName());
        $this->assertEquals('PHPUnit\\Framework\\MockObject\\TypeName', $typeName->getQualifiedName());
        $this->assertEquals('TypeName', $typeName->getSimpleName());
    }

    public function testFromQualifiedNameWithLeadingSeparator(): void
    {
        $typeName = TypeName::fromQualifiedName('\\Foo\\Bar');

        $this->assertTrue($typeName->isNamespaced());
        $this->assertEquals('Foo', $typeName->getNamespaceName());
        $this->assertEquals('Foo\\Bar', $typeName->getQualifiedName());
        $this->assertEquals('Bar', $typeName->getSimpleName());
    }

    public function testFromQualifiedNameWithoutNamespace(): void
    {
        $typeName = TypeName::fromQualifiedName('Bar');

        $this->assertFalse($typeName->isNamespaced());
        $this->assertNull($typeName->getNamespaceName());
        $this->assertEquals('Bar', $typeName->getQualifiedName());
        $this->assertEquals('Bar', $typeName->getSimpleName());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\Type
 *
 * @uses \SebastianBergmann\Type\SimpleType
 * @uses \SebastianBergmann\Type\GenericObjectType
 * @uses \SebastianBergmann\Type\ObjectType
 * @uses \SebastianBergmann\Type\TypeName
 * @uses \SebastianBergmann\Type\CallableType
 * @uses \SebastianBergmann\Type\IterableType
 */
final class TypeTest extends TestCase
{
    /**
     * @dataProvider valuesToNullableType
     */
    public function testTypeMappingFromValue($value, bool $allowsNull, Type $expectedType): void
    {
        $this->assertEquals($expectedType, Type::fromValue($value, $allowsNull));
    }

    public function valuesToNullableType(): array
    {
        return [
            '?null'    => [null, true, new NullType],
            'null'     => [null, false, new NullType],
            '?integer' => [1, true, new SimpleType('int', true, 1)],
            'integer'  => [1, false, new SimpleType('int', false, 1)],
            '?boolean' => [true, true, new SimpleType('bool', true, true)],
            'boolean'  => [true, false, new SimpleType('bool', false, true)],
            '?object'  => [new \stdClass, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
            'object'   => [new \stdClass, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)],
        ];
    }

    /**
     * @dataProvider namesToTypes
     */
    public function testTypeMappingFromName(string $typeName, bool $allowsNull, $expectedType): void
    {
        $this->assertEquals($expectedType, Type::fromName($typeName, $allowsNull));
    }

    public function namesToTypes(): array
    {
        return [
            '?void'             => ['void', true, new VoidType],
            'void'              => ['void', false, new VoidType],
            '?null'             => ['null', true, new NullType],
            'null'              => ['null', true, new NullType],
            '?int'              => ['int', true, new SimpleType('int', true)],
            '?integer'          => ['integer', true, new SimpleType('int', true)],
            'int'               => ['int', false, new SimpleType('int', false)],
            'bool'              => ['bool', false, new SimpleType('bool', false)],
            'boolean'           => ['boolean', false, new SimpleType('bool', false)],
            'object'            => ['object', false, new GenericObjectType(false)],
            'real'              => ['real', false, new SimpleType('float', false)],
            'double'            => ['double', false, new SimpleType('float', false)],
            'float'             => ['float', false, new SimpleType('float', false)],
            'string'            => ['string', false, new SimpleType('string', false)],
            'array'             => ['array', false, new SimpleType('array', false)],
            'resource'          => ['resource', false, new SimpleType('resource', false)],
            'resource (closed)' => ['resource (closed)', false, new SimpleType('resource (closed)', false)],
            'unknown type'      => ['unknown type', false, new UnknownType],
            '?classname'        => [\stdClass::class, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
            'classname'         => [\stdClass::class, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)],
            'callable'          => ['callable', false, new CallableType(false)],
            '?callable'         => ['callable', true, new CallableType(true)],
            'iterable'          => ['iterable', false, new IterableType(false)],
            '?iterable'         => ['iterable', true, new IterableType(true)],
        ];
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\UnknownType
 */
final class UnknownTypeTest extends TestCase
{
    /**
     * @var UnknownType
     */
    private $type;

    protected function setUp(): void
    {
        $this->type = new UnknownType;
    }

    /**
     * @dataProvider assignableTypes
     */
    public function testIsAssignable(Type $assignableType): void
    {
        $this->assertTrue($this->type->isAssignable($assignableType));
    }

    public function assignableTypes(): array
    {
        return [
            [new SimpleType('int', false)],
            [new SimpleType('int', true)],
            [new VoidType],
            [new ObjectType(TypeName::fromQualifiedName(self::class), false)],
            [new ObjectType(TypeName::fromQualifiedName(self::class), true)],
            [new UnknownType],
        ];
    }

    public function testAllowsNull(): void
    {
        $this->assertTrue($this->type->allowsNull());
    }

    public function testReturnTypeDeclaration(): void
    {
        $this->assertEquals('', $this->type->getReturnTypeDeclaration());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\SimpleType
 *
 * @uses \SebastianBergmann\Type\Type
 */
final class SimpleTypeTest extends TestCase
{
    public function testCanBeBool(): void
    {
        $type = new SimpleType('bool', false);

        $this->assertSame(': bool', $type->getReturnTypeDeclaration());
    }

    public function testCanBeBoolean(): void
    {
        $type = new SimpleType('boolean', false);

        $this->assertSame(': bool', $type->getReturnTypeDeclaration());
    }

    public function testCanBeDouble(): void
    {
        $type = new SimpleType('double', false);

        $this->assertSame(': float', $type->getReturnTypeDeclaration());
    }

    public function testCanBeFloat(): void
    {
        $type = new SimpleType('float', false);

        $this->assertSame(': float', $type->getReturnTypeDeclaration());
    }

    public function testCanBeReal(): void
    {
        $type = new SimpleType('real', false);

        $this->assertSame(': float', $type->getReturnTypeDeclaration());
    }

    public function testCanBeInt(): void
    {
        $type = new SimpleType('int', false);

        $this->assertSame(': int', $type->getReturnTypeDeclaration());
    }

    public function testCanBeInteger(): void
    {
        $type = new SimpleType('integer', false);

        $this->assertSame(': int', $type->getReturnTypeDeclaration());
    }

    public function testCanBeArray(): void
    {
        $type = new SimpleType('array', false);

        $this->assertSame(': array', $type->getReturnTypeDeclaration());
    }

    public function testCanBeArray2(): void
    {
        $type = new SimpleType('[]', false);

        $this->assertSame(': array', $type->getReturnTypeDeclaration());
    }

    public function testMayAllowNull(): void
    {
        $type = new SimpleType('bool', true);

        $this->assertTrue($type->allowsNull());
        $this->assertSame(': ?bool', $type->getReturnTypeDeclaration());
    }

    public function testMayNotAllowNull(): void
    {
        $type = new SimpleType('bool', false);

        $this->assertFalse($type->allowsNull());
    }

    /**
     * @dataProvider assignablePairs
     */
    public function testIsAssignable(Type $assignTo, Type $assignedType): void
    {
        $this->assertTrue($assignTo->isAssignable($assignedType));
    }

    public function assignablePairs(): array
    {
        return [
            'nullable to not nullable'     => [new SimpleType('int', false), new SimpleType('int', true)],
            'not nullable to nullable'     => [new SimpleType('int', true), new SimpleType('int', false)],
            'nullable to nullable'         => [new SimpleType('int', true), new SimpleType('int', true)],
            'not nullable to not nullable' => [new SimpleType('int', false), new SimpleType('int', false)],
            'null to not nullable'         => [new SimpleType('int', true), new NullType],
        ];
    }

    /**
     * @dataProvider notAssignablePairs
     */
    public function testIsNotAssignable(Type $assignTo, Type $assignedType): void
    {
        $this->assertFalse($assignTo->isAssignable($assignedType));
    }

    public function notAssignablePairs(): array
    {
        return [
            'null to not nullable' => [new SimpleType('int', false), new NullType],
            'int to boolean'       => [new SimpleType('boolean', false), new SimpleType('int', false)],
            'object'               => [new SimpleType('boolean', false), new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)],
            'unknown type'         => [new SimpleType('boolean', false), new UnknownType],
            'void'                 => [new SimpleType('boolean', false), new VoidType],
        ];
    }

    /**
     * @dataProvider returnTypes
     */
    public function testReturnTypeDeclaration(Type $type, string $returnType): void
    {
        $this->assertEquals($type->getReturnTypeDeclaration(), $returnType);
    }

    public function returnTypes(): array
    {
        return [
            '[]'      => [new SimpleType('[]', false), ': array'],
            'array'   => [new SimpleType('array', false), ': array'],
            '?array'  => [new SimpleType('array', true), ': ?array'],
            'boolean' => [new SimpleType('boolean', false), ': bool'],
            'real'    => [new SimpleType('real', false), ': float'],
            'double'  => [new SimpleType('double', false), ': float'],
            'integer' => [new SimpleType('integer', false), ': int'],
        ];
    }

    public function testCanHaveValue(): void
    {
        $this->assertSame('string', Type::fromValue('string', false)->value());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Type\GenericObjectType
 *
 * @uses \SebastianBergmann\Type\Type
 * @uses \SebastianBergmann\Type\ObjectType
 * @uses \SebastianBergmann\Type\SimpleType
 * @uses \SebastianBergmann\Type\TypeName
 */
final class GenericObjectTypeTest extends TestCase
{
    /**
     * @var GenericObjectType
     */
    private $type;

    protected function setUp(): void
    {
        $this->type = new GenericObjectType(false);
    }

    public function testMayDisallowNull(): void
    {
        $this->assertFalse($this->type->allowsNull());
    }

    public function testCanGenerateReturnTypeDeclaration(): void
    {
        $this->assertEquals(': object', $this->type->getReturnTypeDeclaration());
    }

    public function testMayAllowNull(): void
    {
        $type = new GenericObjectType(true);

        $this->assertTrue($type->allowsNull());
    }

    public function testCanGenerateNullableReturnTypeDeclaration(): void
    {
        $type = new GenericObjectType(true);

        $this->assertEquals(': ?object', $type->getReturnTypeDeclaration());
    }

    public function testObjectCanBeAssignedToGenericObject(): void
    {
        $this->assertTrue(
            $this->type->isAssignable(
                new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)
            )
        );
    }

    public function testNullCanBeAssignedToNullableGenericObject(): void
    {
        $type = new GenericObjectType(true);

        $this->assertTrue(
            $type->isAssignable(
                new NullType
            )
        );
    }

    public function testNonObjectCannotBeAssignedToGenericObject(): void
    {
        $this->assertFalse(
            $this->type->isAssignable(
                new SimpleType('bool', false)
            )
        );
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

final class ClassWithCallbackMethods
{
    public static function staticCallback(): void
    {
    }

    public function nonStaticCallback(): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

function callback_function(): void
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

class ChildClass extends ParentClass
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

class ParentClass
{
    public function foo(): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

final class Iterator implements \Iterator
{
    public function current(): void
    {
    }

    public function next(): void
    {
    }

    public function key(): void
    {
    }

    public function valid(): void
    {
    }

    public function rewind(): void
    {
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type\TestFixture;

final class ClassWithInvokeMethod
{
    public function __invoke(): void
    {
    }
}
# sebastian/type

Collection of value objects that represent the types of the PHP type system.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

```
composer require sebastian/type
```

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

```
composer require --dev sebastian/type
```
/.php_cs
/.php_cs.cache
/.phpunit.result.cache
/composer.lock
/vendor

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
patreon: s_bergmann
/tools export-ignore

<?xml version="1.0" encoding="UTF-8"?>
<phive xmlns="https://phar.io/phive">
  <phar name="php-cs-fixer" version="^2.15" installed="2.15.1" location="./tools/php-cs-fixer" copy="true"/>
  <phar name="psalm" version="^3.2" installed="3.4.5" location="./tools/psalm" copy="true"/>
</phive>
language: php

php:
  - 7.2
  - 7.3
  - 7.4snapshot
  - nightly

matrix:
  allow_failures:
    - php: master
  fast_finish: true

env:
  matrix:
    - DEPENDENCIES="high"
    - DEPENDENCIES="low"
  global:
    - DEFAULT_COMPOSER_FLAGS="--no-interaction --no-ansi --no-progress --no-suggest"

before_install:
  - ./tools/composer clear-cache

install:
  - if [[ "$DEPENDENCIES" = 'high' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS; fi
  - if [[ "$DEPENDENCIES" = 'low' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS --prefer-lowest; fi

script:
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false

jobs:
  include:
    - stage: "Static Code Analysis"
      php: 7.3
      env: php-cs-fixer
      install:
        - phpenv config-rm xdebug.ini
      script:
        - ./tools/php-cs-fixer fix --dry-run -v --show-progress=dots --diff-format=udiff
    - stage: "Static Code Analysis"
      php: 7.3
      env: psalm
      install:
        - phpenv config-rm xdebug.ini
      script:
        - travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS
        - ./tools/psalm --shepherd --stats
{
    "name": "sebastian/type",
    "description": "Collection of value objects that represent the types of the PHP type system",
    "type": "library",
    "homepage": "https://github.com/sebastianbergmann/type",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/type/issues"
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.2"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.2"
    },
    "config": {
        "platform": {
            "php": "7.2.0"
        },
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/_fixture"
        ],
        "files": [
            "tests/_fixture/callback_function.php"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.1-dev"
        }
    }
}
<?php declare(strict_types=1);
$header = <<<'EOF'
This file is part of sebastian/type.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'ordered_interfaces' => [
                'direction' => 'ascend',
                'order' => 'alpha',
            ],
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => ['groups' => ['simple', 'meta']],
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?xml version="1.0"?>
<psalm
    totallyTyped="false"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://getpsalm.org/schema/config"
    xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
    <projectFiles>
        <directory name="src" />
        <ignoreFiles>
            <directory name="vendor" />
        </ignoreFiles>
    </projectFiles>

    <issueHandlers>
        <LessSpecificReturnType errorLevel="info" />

        <!-- level 3 issues - slightly lazy code writing, but provably low false-negatives -->

        <DeprecatedMethod errorLevel="info" />
        <DeprecatedProperty errorLevel="info" />
        <DeprecatedClass errorLevel="info" />
        <DeprecatedConstant errorLevel="info" />
        <DeprecatedInterface errorLevel="info" />
        <DeprecatedTrait errorLevel="info" />

        <InternalMethod errorLevel="info" />
        <InternalProperty errorLevel="info" />
        <InternalClass errorLevel="info" />

        <MissingClosureReturnType errorLevel="info" />
        <MissingReturnType errorLevel="info" />
        <MissingPropertyType errorLevel="info" />
        <InvalidDocblock errorLevel="info" />
        <MisplacedRequiredParam errorLevel="info" />

        <PropertyNotSetInConstructor errorLevel="info" />
        <MissingConstructor errorLevel="info" />
        <MissingClosureParamType errorLevel="info" />
        <MissingParamType errorLevel="info" />

        <RedundantCondition errorLevel="info" />

        <DocblockTypeContradiction errorLevel="info" />
        <RedundantConditionGivenDocblockType errorLevel="info" />

        <UnresolvableInclude errorLevel="info" />

        <RawObjectIteration errorLevel="info" />

        <InvalidStringClass errorLevel="info" />
    </issueHandlers>
</psalm>
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
  <component name="NewModuleRootManager">
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/instantiator" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/myclabs/deep-copy" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phar-io/manifest" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phar-io/version" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/reflection-common" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/reflection-docblock" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/type-resolver" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpspec/prophecy" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-code-coverage" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-file-iterator" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-text-template" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-timer" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-token-stream" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/phpunit" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/code-unit-reverse-lookup" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/comparator" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/diff" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/environment" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/exporter" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/global-state" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/object-enumerator" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/object-reflector" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/recursion-context" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/resource-operations" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/version" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-ctype" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/theseer/tokenizer" />
      <excludeFolder url="file://$MODULE_DIR$/vendor/webmozart/assert" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module><component name="InspectionProjectProfileManager">
  <profile version="1.0">
    <option name="myName" value="Project Default" />
    <inspection_tool class="AmdModulesDependencies" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="AngularAmbiguousComponentTag" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularCliAddDependency" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="AngularIncorrectTemplateDefinition" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularInsecureBindingToEvent" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidAnimationTriggerAssignment" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidEntryComponent" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidExpressionResultType" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidImportedOrDeclaredSymbol" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidSelector" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularInvalidTemplateReferenceVariable" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularMissingEventHandler" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularMissingOrInvalidDeclarationInModule" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularMultipleStructuralDirectives" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularNonEmptyNgContent" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularRecursiveModuleImportExport" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularUndefinedBinding" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularUndefinedModuleExport" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AngularUndefinedTag" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="AutoloadingIssuesInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="BadExceptionsProcessingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="BadExpressionStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="BladeControlDirectives" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CallerJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CheckDtdRefs" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CheckEmptyScriptTag" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CheckImageSize" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CheckNodeTest" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CheckTagEmptyBody" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CheckValidXmlInScriptTagBody" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CheckXmlFileWithXercesValidator" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="ClassOverridesFieldOfSuperClassInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="CoffeeScriptArgumentsOutsideFunction" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptFunctionSignatures" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptInfiniteLoop" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptLiteralNotFunction" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptModulesDependencies" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptSillyAssignment" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptSwitchStatementWithNoDefaultBranch" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CoffeeScriptUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CommaExpressionJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ComposeUnknownKeys" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="ComposeUnknownValues" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="ConstantConditionalExpressionJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ConstantIfStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ContinueOrBreakFromFinallyBlockJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssFloatPxLength" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="CssInvalidAtRule" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssInvalidCharsetRule" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssInvalidElement" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssInvalidFunction" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssInvalidHtmlTagReference" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssInvalidImport" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssInvalidMediaFeature" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssInvalidPropertyValue" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssInvalidPseudoSelector" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssMissingComma" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssNegativeValue" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssNoGenericFontName" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssOverwrittenProperties" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssRedundantUnit" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssReplaceWithShorthandSafely" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="CssReplaceWithShorthandUnsafely" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="CssUnitlessNumber" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CssUnknownProperty" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myCustomPropertiesEnabled" value="false" />
      <option name="myIgnoreVendorSpecificProperties" value="false" />
      <option name="myCustomPropertiesList">
        <value>
          <list size="0" />
        </value>
      </option>
    </inspection_tool>
    <inspection_tool class="CssUnknownTarget" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssUnresolvedClass" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssUnresolvedCustomProperty" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CssUnusedSymbol" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CucumberExamplesColon" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CucumberMissedExamples" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="CucumberTableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="CucumberUndefinedStep" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DisallowWritingIntoStaticPropertiesInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="DockerFileAddOrCopySemantic" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DockerFileArgumentCount" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="DockerFileAssignments" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="DuplicateCaseLabelJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DuplicateKeyInSection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="DuplicateSectionInFile" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6BindWithArrowFunction" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6CheckImport" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6ClassMemberInitializationOrder" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6ConvertModuleExportToExport" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="ES6ConvertRequireIntoImport" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="ES6ConvertToForOf" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="ES6ConvertVarToLetConst" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6MissingAwait" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="ES6ModulesDependencies" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6PossiblyAsyncFunction" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="ES6ShorthandObjectProperty" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="ES6UnusedImports" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="EmptyStatementBodyJS" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_reportEmptyBlocks" value="false" />
    </inspection_tool>
    <inspection_tool class="ExceptionCaughtLocallyJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FallThroughInSwitchStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FileHeaderInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="FlowJSConfig" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="FlowJSFlagCommentPlacement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ForgottenDebugOutputInspection" enabled="true" level="ERROR" enabled_by_default="true">
      <option name="configuration">
        <list>
          <option value="\Codeception\Util\Debug::debug" />
          <option value="\Codeception\Util\Debug::pause" />
          <option value="\Doctrine::dump" />
          <option value="\Doctrine\Common\Util\Debug::dump" />
          <option value="\Doctrine\Common\Util\Debug::export" />
          <option value="\Illuminate\Support\Debug\Dumper::dump" />
          <option value="\Symfony\Component\Debug\Debug::enable" />
          <option value="\Symfony\Component\Debug\DebugClassLoader::enable" />
          <option value="\Symfony\Component\Debug\ErrorHandler::register" />
          <option value="\Symfony\Component\Debug\ExceptionHandler::register" />
          <option value="\TYPO3\CMS\Core\Utility\DebugUtility::debug" />
          <option value="\Zend\Debug\Debug::dump" />
          <option value="\Zend\Di\Display\Console::export" />
          <option value="\Zend_Debug::dump" />
          <option value="dd" />
          <option value="debug_print_backtrace" />
          <option value="debug_zval_dump" />
          <option value="dpm" />
          <option value="dpq" />
          <option value="dsm" />
          <option value="dump" />
          <option value="dvm" />
          <option value="error_log" />
          <option value="kpr" />
          <option value="phpinfo" />
          <option value="print_r" />
          <option value="var_dump" />
          <option value="var_export" />
          <option value="xdebug_break" />
          <option value="xdebug_call_class" />
          <option value="xdebug_call_file" />
          <option value="xdebug_call_function" />
          <option value="xdebug_call_line" />
          <option value="xdebug_code_coverage_started" />
          <option value="xdebug_debug_zval" />
          <option value="xdebug_debug_zval_stdout" />
          <option value="xdebug_dump_superglobals" />
          <option value="xdebug_enable" />
          <option value="xdebug_get_code_coverage" />
          <option value="xdebug_get_collected_errors" />
          <option value="xdebug_get_declared_vars" />
          <option value="xdebug_get_function_stack" />
          <option value="xdebug_get_headers" />
          <option value="xdebug_get_monitored_functions" />
          <option value="xdebug_get_profiler_filename" />
          <option value="xdebug_get_stack_depth" />
          <option value="xdebug_get_tracefile_name" />
          <option value="xdebug_is_enabled" />
          <option value="xdebug_memory_usage" />
          <option value="xdebug_peak_memory_usage" />
          <option value="xdebug_print_function_stack" />
          <option value="xdebug_start_code_coverage" />
          <option value="xdebug_start_error_collection" />
          <option value="xdebug_start_function_monitor" />
          <option value="xdebug_start_trace" />
          <option value="xdebug_stop_code_coverage" />
          <option value="xdebug_stop_error_collection" />
          <option value="xdebug_stop_function_monitor" />
          <option value="xdebug_stop_trace" />
          <option value="xdebug_time_index" />
          <option value="xdebug_var_dump" />
        </list>
      </option>
      <option name="migratedIntoUserSpace" value="true" />
    </inspection_tool>
    <inspection_tool class="GherkinBrokenTableInspection" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="GherkinMisplacedBackground" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="GherkinScenarioToScenarioOutline" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="HamlNestedTagContent" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HardwiredNamespacePrefix" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlDeprecatedAttribute" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlDeprecatedTag" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlExtraClosingTag" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlFormInputWithoutLabel" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlMissingClosingTag" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="HtmlRequiredAltAttribute" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlRequiredLangAttribute" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlRequiredTitleElement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlUnknownAnchorTarget" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlUnknownAttribute" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myValues">
        <value>
          <list size="0" />
        </value>
      </option>
      <option name="myCustomValuesEnabled" value="true" />
    </inspection_tool>
    <inspection_tool class="HtmlUnknownBooleanAttribute" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="HtmlUnknownTag" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myValues">
        <value>
          <list size="6">
            <item index="0" class="java.lang.String" itemvalue="nobr" />
            <item index="1" class="java.lang.String" itemvalue="noembed" />
            <item index="2" class="java.lang.String" itemvalue="comment" />
            <item index="3" class="java.lang.String" itemvalue="noscript" />
            <item index="4" class="java.lang.String" itemvalue="embed" />
            <item index="5" class="java.lang.String" itemvalue="script" />
          </list>
        </value>
      </option>
      <option name="myCustomValuesEnabled" value="true" />
    </inspection_tool>
    <inspection_tool class="HtmlUnknownTarget" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ImplicitTypeConversion" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="BITS" value="1720" />
      <option name="FLAG_EXPLICIT_CONVERSION" value="true" />
      <option name="IGNORE_NODESET_TO_BOOLEAN_VIA_STRING" value="true" />
    </inspection_tool>
    <inspection_tool class="IncompatibleMaskJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="InconsistentLineSeparators" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="IndexZeroUsage" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="InfiniteLoopJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="InfiniteRecursionJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSAccessibilityCheck" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSAnnotator" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="JSArrowFunctionBracesCanBeRemoved" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSAssignmentUsedAsCondition" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSBitwiseOperatorUsage" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSCheckFunctionSignatures" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSClosureCompilerSyntax" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSCommentMatchesSignature" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSComparisonWithNaN" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSConsecutiveCommasInArrayLiteral" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSConstructorReturnsPrimitive" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSDeprecatedSymbols" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSDuplicatedDeclaration" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSEqualityComparisonWithCoercion" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSFileReferences" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSFunctionExpressionToArrowFunction" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSIgnoredPromiseFromCall" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSIncompatibleTypesComparison" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSJQueryEfficiency" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSJoinVariableDeclarationAndAssignment" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSLastCommaInArrayLiteral" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSLastCommaInObjectLiteral" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSMethodCanBeStatic" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSMismatchedCollectionQueryUpdate" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="queries" value="trace,write,forEach,length" />
      <option name="updates" value="pop,push,shift,splice,unshift,add,insert,remove" />
    </inspection_tool>
    <inspection_tool class="JSMissingSwitchBranches" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSMissingSwitchDefault" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSNonASCIINames" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSObjectNullOrUndefined" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSPotentiallyInvalidConstructorUsage" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myConsiderUppercaseFunctionsToBeConstructors" value="true" />
    </inspection_tool>
    <inspection_tool class="JSPotentiallyInvalidTargetOfIndexedPropertyAccess" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSPotentiallyInvalidUsageOfClassThis" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSPotentiallyInvalidUsageOfThis" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSPrimitiveTypeWrapperUsage" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSRedeclarationOfBlockScope" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="JSRedundantSwitchStatement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSReferencingArgumentsOutsideOfFunction" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="JSReferencingMutableVariableFromClosure" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSRemoveUnnecessaryParentheses" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSStringConcatenationToES6Template" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="JSSuspiciousNameCombination" enabled="false" level="WARNING" enabled_by_default="false">
      <group names="x,width,left,right" />
      <group names="y,height,top,bottom" />
      <exclude classes="Math" />
    </inspection_tool>
    <inspection_tool class="JSSwitchVariableDeclarationIssue" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSTestFailedLine" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSTypeOfValues" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUndeclaredVariable" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUndefinedPropertyAssignment" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnfilteredForInLoop" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnnecessarySemicolon" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnreachableSwitchBranches" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnresolvedExtXType" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnresolvedFunction" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnresolvedLibraryURL" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnresolvedVariable" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnusedAssignment" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnusedGlobalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSValidateJSDoc" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSValidateTypes" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JSXNamespaceValidation" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="Json5StandardCompliance" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="JsonDuplicatePropertyKeys" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JsonSchemaCompliance" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JsonSchemaDeprecation" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="JsonSchemaRefReference" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JsonStandardCompliance" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="LessResolvedByNameOnly" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="LessUnresolvedMixin" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="LessUnresolvedVariable" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="LoopStatementThatDoesntLoopJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="MarkdownUnresolvedFileReference" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="MissingSinceTagDocInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="MssqlBuiltinInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="MssqlTriggerInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="MysqlParsingInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="NodeJsCodingAssistanceForCoreModules" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="NodeModulesDependencies" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="NpmUsedModulesInstalled" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="OctalIntegerJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PackageJsonMismatchedDependency" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PgSelectFromProcedureInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PhingDomInspection" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="PhpAssignmentInConditionInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpDivisionByZeroInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpDocMissingReturnTagInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="PhpDocSignatureInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="PhpFullyQualifiedNameUsageInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PhpIncludeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PhpMethodOrClassCallIsNotCaseSensitiveInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpMissingStrictTypesDeclarationInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpMultipleClassesDeclarationsInOneFile" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpShortOpenTagInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpTraditionalSyntaxArrayLiteralInspection" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpUnnecessaryFullyQualifiedNameInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PhpUsageOfSilenceOperatorInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="PhpVariableVariableInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="PointlessArithmeticExpressionJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="PointlessBooleanExpressionJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ProblematicWhitespace" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="RedundantTypeConversion" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="CHECK_ANY" value="false" />
    </inspection_tool>
    <inspection_tool class="RegExpAnonymousGroup" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="RequiredAttributes" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="myAdditionalRequiredHtmlAttributes" value="" />
    </inspection_tool>
    <inspection_tool class="ReservedWordUsedAsNameJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ReturnFromFinallyBlockJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SassScssResolvedByNameOnly" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="SassScssUnresolvedMixin" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SassScssUnresolvedPlaceholderSelector" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SassScssUnresolvedVariable" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SecurityAdvisoriesInspection" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="REPORT_MISSING_ROAVE_ADVISORIES" value="false" />
      <option name="optionConfiguration">
        <list>
          <option value="barryvdh/laravel-debugbar" />
          <option value="behat/behat" />
          <option value="brianium/paratest" />
          <option value="codeception/codeception" />
          <option value="codeception/mockery-module" />
          <option value="codeception/specify" />
          <option value="codeception/verify" />
          <option value="codedungeon/phpunit-result-printer" />
          <option value="composer/composer" />
          <option value="doctrine/coding-standard" />
          <option value="filp/whoops" />
          <option value="friendsofphp/php-cs-fixer" />
          <option value="humbug/humbug" />
          <option value="infection/infection" />
          <option value="jakub-onderka/php-parallel-lint" />
          <option value="johnkary/phpunit-speedtrap" />
          <option value="mikey179/vfsStream" />
          <option value="mockery/mockery" />
          <option value="mybuilder/phpunit-accelerator" />
          <option value="orchestra/testbench" />
          <option value="pdepend/pdepend" />
          <option value="phan/phan" />
          <option value="phing/phing" />
          <option value="phpcompatibility/php-compatibility" />
          <option value="phpmd/phpmd" />
          <option value="phpro/grumphp" />
          <option value="phpspec/phpspec" />
          <option value="phpspec/prophecy" />
          <option value="phpstan/phpstan" />
          <option value="phpunit/dbunit" />
          <option value="phpunit/phpcov" />
          <option value="phpunit/phpunit" />
          <option value="phpunit/phpunit-selenium" />
          <option value="povils/phpmnd" />
          <option value="roave/security-advisories" />
          <option value="satooshi/php-coveralls" />
          <option value="sebastian/phpcpd" />
          <option value="slevomat/coding-standard" />
          <option value="spatie/phpunit-watcher" />
          <option value="squizlabs/php_codesniffer" />
          <option value="sstalle/php7cc" />
          <option value="symfony/debug" />
          <option value="symfony/maker-bundle" />
          <option value="symfony/phpunit-bridge" />
          <option value="symfony/var-dumper" />
          <option value="vimeo/psalm" />
          <option value="wimg/php-compatibility" />
          <option value="yiisoft/yii2-debug" />
          <option value="yiisoft/yii2-gii" />
          <option value="zendframework/zend-debug" />
          <option value="zendframework/zend-test" />
        </list>
      </option>
    </inspection_tool>
    <inspection_tool class="ShiftOutOfRangeJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SillyAssignmentJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
      <option name="processCode" value="true" />
      <option name="processLiterals" value="true" />
      <option name="processComments" value="true" />
    </inspection_tool>
    <inspection_tool class="SqlAddNotNullColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlAmbiguousColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlAutoIncrementDuplicateInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlCheckUsingColumnsInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlConstantConditionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlDeprecateTypeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlDerivedTableAliasInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlDialectInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlDropIndexedColumnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlErrorHandlingInspection" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="SqlIdentifierInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlIllegalCursorStateInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlInsertValuesInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlJoinWithoutOnInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlNoDataSourceInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlNullComparisonInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlResolveInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlShouldBeInGroupByInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlSideEffectsInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlSignatureInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlStorageInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlTypeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlUnreachableCodeInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlUnusedSubqueryItemInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlUnusedVariableInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SqlWithoutWhereInspection" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SuspiciousTypeOfGuard" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ThisExpressionReferencesGlobalObjectJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ThrowFromFinallyBlockJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TrivialConditionalJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TrivialIfJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptAbstractClassConstructorCanBeMadeProtected" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptAccessibilityCheck" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptCheckImport" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="TypeScriptConfig" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptFieldCanBeMadeReadonly" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptLibrary" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="TypeScriptMissingAugmentationImport" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="TypeScriptPreferShortImport" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptSuspiciousConstructorParameterAssignment" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptUMDGlobal" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptUnresolvedFunction" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptUnresolvedVariable" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptValidateJSTypes" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="TypeScriptValidateTypes" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="TypescriptExplicitMemberType" enabled="false" level="INFORMATION" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryBooleanCheckInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="UnnecessaryContinueJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLabelJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLabelOnBreakStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLabelOnContinueStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnnecessaryLocalVariableJS" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="m_ignoreImmediatelyReturnedVariables" value="false" />
      <option name="m_ignoreAnnotatedVariables" value="false" />
    </inspection_tool>
    <inspection_tool class="UnnecessaryReturnJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnqualifiedReferenceInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
    <inspection_tool class="UnreachableCodeJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="UnresolvedReference" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="UnterminatedStatementJS" enabled="false" level="WARNING" enabled_by_default="false">
      <option name="ignoreSemicolonAtEndOfBlock" value="true" />
    </inspection_tool>
    <inspection_tool class="VueDataFunction" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="VueDuplicateTag" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="WebpackConfigHighlighting" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="WithStatementJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XmlDefaultAttributeValue" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XmlDeprecatedElement" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XmlDuplicatedId" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XmlHighlighting" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XmlInvalidId" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XmlPathReference" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XmlUnboundNsPrefix" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XmlUnusedNamespaceDeclaration" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XmlWrongRootElement" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XsltDeclarations" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XsltTemplateInvocation" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="XsltUnusedDeclaration" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="XsltVariableShadowing" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="YAMLDuplicatedKeys" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="YAMLRecursiveAlias" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="YAMLSchemaDeprecation" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
    <inspection_tool class="YAMLSchemaValidation" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="YAMLUnresolvedAlias" enabled="false" level="ERROR" enabled_by_default="false" />
    <inspection_tool class="YAMLUnusedAnchor" enabled="false" level="WARNING" enabled_by_default="false" />
  </profile>
</component><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
  </component>
</project><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="EAUltimateProjectSettings">
    <categories>
      <STRICTNESS_CATEGORY_SECURITY enabled="yes" />
      <STRICTNESS_CATEGORY_PROBABLE_BUGS enabled="yes" />
      <STRICTNESS_CATEGORY_PERFORMANCE enabled="yes" />
      <STRICTNESS_CATEGORY_ARCHITECTURE enabled="yes" />
      <STRICTNESS_CATEGORY_CONTROL_FLOW enabled="yes" />
      <STRICTNESS_CATEGORY_LANGUAGE_LEVEL_MIGRATION enabled="yes" />
      <STRICTNESS_CATEGORY_CODE_STYLE enabled="yes" />
      <STRICTNESS_CATEGORY_UNUSED enabled="yes" />
      <STRICTNESS_CATEGORY_PHPUNIT enabled="yes" />
    </categories>
    <settings>
      <ANALYZE_ONLY_MODIFIED_FILES value="no" />
      <PREFER_YODA_COMPARISON_STYLE value="no" />
    </settings>
  </component>
</project><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/type.iml" filepath="$PROJECT_DIR$/.idea/type.iml" />
    </modules>
  </component>
</project><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpIncludePathManager">
    <include_path>
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-ctype" />
      <path value="$PROJECT_DIR$/vendor/phpspec/prophecy" />
      <path value="$PROJECT_DIR$/vendor/sebastian/version" />
      <path value="$PROJECT_DIR$/vendor/sebastian/diff" />
      <path value="$PROJECT_DIR$/vendor/phar-io/version" />
      <path value="$PROJECT_DIR$/vendor/sebastian/code-unit-reverse-lookup" />
      <path value="$PROJECT_DIR$/vendor/phar-io/manifest" />
      <path value="$PROJECT_DIR$/vendor/sebastian/resource-operations" />
      <path value="$PROJECT_DIR$/vendor/sebastian/object-enumerator" />
      <path value="$PROJECT_DIR$/vendor/sebastian/object-reflector" />
      <path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-code-coverage" />
      <path value="$PROJECT_DIR$/vendor/sebastian/environment" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-token-stream" />
      <path value="$PROJECT_DIR$/vendor/sebastian/exporter" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-text-template" />
      <path value="$PROJECT_DIR$/vendor/sebastian/comparator" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-file-iterator" />
      <path value="$PROJECT_DIR$/vendor/sebastian/global-state" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
      <path value="$PROJECT_DIR$/vendor/myclabs/deep-copy" />
      <path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
      <path value="$PROJECT_DIR$/vendor/doctrine/instantiator" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/type-resolver" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-docblock" />
      <path value="$PROJECT_DIR$/vendor/composer" />
      <path value="$PROJECT_DIR$/vendor/webmozart/assert" />
      <path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
    </include_path>
  </component>
  <component name="PhpProjectSharedConfiguration" php_language_level="7.2" />
  <component name="PhpUnit">
    <phpunit_settings>
      <PhpUnitSettings load_method="CUSTOM_LOADER" custom_loader_path="$PROJECT_DIR$/vendor/autoload.php" />
    </phpunit_settings>
  </component>
</project><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptSettings">
    <option name="languageLevel" value="ES6" />
  </component>
</project><?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class GenericObjectType extends Type
{
    /**
     * @var bool
     */
    private $allowsNull;

    public function __construct(bool $nullable)
    {
        $this->allowsNull = $nullable;
    }

    public function isAssignable(Type $other): bool
    {
        if ($this->allowsNull && $other instanceof NullType) {
            return true;
        }

        if (!$other instanceof ObjectType) {
            return false;
        }

        return true;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': ' . ($this->allowsNull ? '?' : '') . 'object';
    }

    public function allowsNull(): bool
    {
        return $this->allowsNull;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class SimpleType extends Type
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var bool
     */
    private $allowsNull;

    /**
     * @var mixed
     */
    private $value;

    public function __construct(string $name, bool $nullable, $value = null)
    {
        $this->name       = $this->normalize($name);
        $this->allowsNull = $nullable;
        $this->value      = $value;
    }

    public function isAssignable(Type $other): bool
    {
        if ($this->allowsNull && $other instanceof NullType) {
            return true;
        }

        if ($other instanceof self) {
            return $this->name === $other->name;
        }

        return false;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': ' . ($this->allowsNull ? '?' : '') . $this->name;
    }

    public function allowsNull(): bool
    {
        return $this->allowsNull;
    }

    public function value()
    {
        return $this->value;
    }

    private function normalize(string $name): string
    {
        $name = \strtolower($name);

        switch ($name) {
            case 'boolean':
                return 'bool';

            case 'real':
            case 'double':
                return 'float';

            case 'integer':
                return 'int';

            case '[]':
                return 'array';

            default:
                return $name;
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

abstract class Type
{
    public static function fromValue($value, bool $allowsNull): self
    {
        $typeName = \gettype($value);

        if ($typeName === 'object') {
            return new ObjectType(TypeName::fromQualifiedName(\get_class($value)), $allowsNull);
        }

        $type = self::fromName($typeName, $allowsNull);

        if ($type instanceof SimpleType) {
            $type = new SimpleType($typeName, $allowsNull, $value);
        }

        return $type;
    }

    public static function fromName(string $typeName, bool $allowsNull): self
    {
        switch (\strtolower($typeName)) {
            case 'callable':
                return new CallableType($allowsNull);

            case 'iterable':
                return new IterableType($allowsNull);

            case 'null':
                return new NullType;

            case 'object':
                return new GenericObjectType($allowsNull);

            case 'unknown type':
                return new UnknownType;

            case 'void':
                return new VoidType;

            case 'array':
            case 'bool':
            case 'boolean':
            case 'double':
            case 'float':
            case 'int':
            case 'integer':
            case 'real':
            case 'resource':
            case 'resource (closed)':
            case 'string':
                return new SimpleType($typeName, $allowsNull);

            default:
                return new ObjectType(TypeName::fromQualifiedName($typeName), $allowsNull);
        }
    }

    abstract public function isAssignable(Type $other): bool;

    abstract public function getReturnTypeDeclaration(): string;

    abstract public function allowsNull(): bool;
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class NullType extends Type
{
    public function isAssignable(Type $other): bool
    {
        return !($other instanceof VoidType);
    }

    public function getReturnTypeDeclaration(): string
    {
        return '';
    }

    public function allowsNull(): bool
    {
        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class ObjectType extends Type
{
    /**
     * @var TypeName
     */
    private $className;

    /**
     * @var bool
     */
    private $allowsNull;

    public function __construct(TypeName $className, bool $allowsNull)
    {
        $this->className  = $className;
        $this->allowsNull = $allowsNull;
    }

    public function isAssignable(Type $other): bool
    {
        if ($this->allowsNull && $other instanceof NullType) {
            return true;
        }

        if ($other instanceof self) {
            if (0 === \strcasecmp($this->className->getQualifiedName(), $other->className->getQualifiedName())) {
                return true;
            }

            if (\is_subclass_of($other->className->getQualifiedName(), $this->className->getQualifiedName(), true)) {
                return true;
            }
        }

        return false;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': ' . ($this->allowsNull ? '?' : '') . $this->className->getQualifiedName();
    }

    public function allowsNull(): bool
    {
        return $this->allowsNull;
    }

    public function className(): TypeName
    {
        return $this->className;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class CallableType extends Type
{
    /**
     * @var bool
     */
    private $allowsNull;

    public function __construct(bool $nullable)
    {
        $this->allowsNull = $nullable;
    }

    /**
     * @throws RuntimeException
     */
    public function isAssignable(Type $other): bool
    {
        if ($this->allowsNull && $other instanceof NullType) {
            return true;
        }

        if ($other instanceof self) {
            return true;
        }

        if ($other instanceof ObjectType) {
            if ($this->isClosure($other)) {
                return true;
            }

            if ($this->hasInvokeMethod($other)) {
                return true;
            }
        }

        if ($other instanceof SimpleType) {
            if ($this->isFunction($other)) {
                return true;
            }

            if ($this->isClassCallback($other)) {
                return true;
            }

            if ($this->isObjectCallback($other)) {
                return true;
            }
        }

        return false;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': ' . ($this->allowsNull ? '?' : '') . 'callable';
    }

    public function allowsNull(): bool
    {
        return $this->allowsNull;
    }

    private function isClosure(ObjectType $type): bool
    {
        return !$type->className()->isNamespaced() && $type->className()->getSimpleName() === \Closure::class;
    }

    /**
     * @throws RuntimeException
     */
    private function hasInvokeMethod(ObjectType $type): bool
    {
        try {
            $class = new \ReflectionClass($type->className()->getQualifiedName());
            // @codeCoverageIgnoreStart
        } catch (\ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                (int) $e->getCode(),
                $e
            );
            // @codeCoverageIgnoreEnd
        }

        if ($class->hasMethod('__invoke')) {
            return true;
        }

        return false;
    }

    private function isFunction(SimpleType $type): bool
    {
        if (!\is_string($type->value())) {
            return false;
        }

        return \function_exists($type->value());
    }

    private function isObjectCallback(SimpleType $type): bool
    {
        if (!\is_array($type->value())) {
            return false;
        }

        if (\count($type->value()) !== 2) {
            return false;
        }

        if (!\is_object($type->value()[0]) || !\is_string($type->value()[1])) {
            return false;
        }

        [$object, $methodName] = $type->value();

        $reflector = new \ReflectionObject($object);

        return $reflector->hasMethod($methodName);
    }

    private function isClassCallback(SimpleType $type): bool
    {
        if (!\is_string($type->value()) && !\is_array($type->value())) {
            return false;
        }

        if (\is_string($type->value())) {
            if (\strpos($type->value(), '::') === false) {
                return false;
            }

            [$className, $methodName] = \explode('::', $type->value());
        }

        if (\is_array($type->value())) {
            if (\count($type->value()) !== 2) {
                return false;
            }

            if (!\is_string($type->value()[0]) || !\is_string($type->value()[1])) {
                return false;
            }

            [$className, $methodName] = $type->value();
        }

        \assert(isset($className) && \is_string($className));
        \assert(isset($methodName) && \is_string($methodName));

        try {
            $class = new \ReflectionClass($className);

            if ($class->hasMethod($methodName)) {
                $method = $class->getMethod($methodName);

                return $method->isPublic() && $method->isStatic();
            }
            // @codeCoverageIgnoreStart
        } catch (\ReflectionException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                (int) $e->getCode(),
                $e
            );
            // @codeCoverageIgnoreEnd
        }

        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class UnknownType extends Type
{
    public function isAssignable(Type $other): bool
    {
        return true;
    }

    public function getReturnTypeDeclaration(): string
    {
        return '';
    }

    public function allowsNull(): bool
    {
        return true;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class TypeName
{
    /**
     * @var ?string
     */
    private $namespaceName;

    /**
     * @var string
     */
    private $simpleName;

    public static function fromQualifiedName(string $fullClassName): self
    {
        if ($fullClassName[0] === '\\') {
            $fullClassName = \substr($fullClassName, 1);
        }

        $classNameParts = \explode('\\', $fullClassName);

        $simpleName    = \array_pop($classNameParts);
        $namespaceName = \implode('\\', $classNameParts);

        return new self($namespaceName, $simpleName);
    }

    public static function fromReflection(\ReflectionClass $type): self
    {
        return new self(
            $type->getNamespaceName(),
            $type->getShortName()
        );
    }

    public function __construct(?string $namespaceName, string $simpleName)
    {
        if ($namespaceName === '') {
            $namespaceName = null;
        }

        $this->namespaceName = $namespaceName;
        $this->simpleName    = $simpleName;
    }

    public function getNamespaceName(): ?string
    {
        return $this->namespaceName;
    }

    public function getSimpleName(): string
    {
        return $this->simpleName;
    }

    public function getQualifiedName(): string
    {
        return $this->namespaceName === null
             ? $this->simpleName
             : $this->namespaceName . '\\' . $this->simpleName;
    }

    public function isNamespaced(): bool
    {
        return $this->namespaceName !== null;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class VoidType extends Type
{
    public function isAssignable(Type $other): bool
    {
        return $other instanceof self;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': void';
    }

    public function allowsNull(): bool
    {
        return false;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class RuntimeException extends \RuntimeException implements Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

interface Exception
{
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/type.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Type;

final class IterableType extends Type
{
    /**
     * @var bool
     */
    private $allowsNull;

    public function __construct(bool $nullable)
    {
        $this->allowsNull = $nullable;
    }

    /**
     * @throws RuntimeException
     */
    public function isAssignable(Type $other): bool
    {
        if ($this->allowsNull && $other instanceof NullType) {
            return true;
        }

        if ($other instanceof self) {
            return true;
        }

        if ($other instanceof SimpleType) {
            return \is_iterable($other->value());
        }

        if ($other instanceof ObjectType) {
            try {
                return (new \ReflectionClass($other->className()->getQualifiedName()))->isIterable();
                // @codeCoverageIgnoreStart
            } catch (\ReflectionException $e) {
                throw new RuntimeException(
                    $e->getMessage(),
                    (int) $e->getCode(),
                    $e
                );
                // @codeCoverageIgnoreEnd
            }
        }

        return false;
    }

    public function getReturnTypeDeclaration(): string
    {
        return ': ' . ($this->allowsNull ? '?' : '') . 'iterable';
    }

    public function allowsNull(): bool
    {
        return $this->allowsNull;
    }
}
<?php
$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->files()
    ->in('src')
    ->name('*.php');

return Symfony\CS\Config\Config::create()
    ->level(\Symfony\CS\FixerInterface::NONE_LEVEL)
    ->fixers(
        array(
            'align_double_arrow',
            'align_equals',
            'braces',
            'concat_with_spaces',
            'duplicate_semicolon',
            'elseif',
            'empty_return',
            'encoding',
            'eof_ending',
            'extra_empty_lines',
            'function_call_space',
            'function_declaration',
            'indentation',
            'join_function',
            'line_after_namespace',
            'linefeed',
            'list_commas',
            'lowercase_constants',
            'lowercase_keywords',
            'method_argument_space',
            'multiple_use',
            'namespace_no_leading_whitespace',
            'no_blank_lines_after_class_opening',
            'no_empty_lines_after_phpdocs',
            'parenthesis',
            'php_closing_tag',
            'phpdoc_indent',
            'phpdoc_no_access',
            'phpdoc_no_empty_return',
            'phpdoc_no_package',
            'phpdoc_params',
            'phpdoc_scalar',
            'phpdoc_separation',
            'phpdoc_to_comment',
            'phpdoc_trim',
            'phpdoc_types',
            'phpdoc_var_without_name',
            'remove_lines_between_uses',
            'return',
            'self_accessor',
            'short_array_syntax',
            'short_tag',
            'single_line_after_imports',
            'single_quote',
            'spaces_before_semicolon',
            'spaces_cast',
            'ternary_spaces',
            'trailing_spaces',
            'trim_array_spaces',
            'unused_use',
            'visibility',
            'whitespacy_lines'
        )
    )
    ->finder($finder);

Version

Copyright (c) 2013-2015, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Version

**Version** is a library that helps with managing the version number of Git-hosted PHP projects.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/version

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/version

## Usage

The constructor of the `SebastianBergmann\Version` class expects two parameters:

* `$release` is the version number of the latest release (`X.Y.Z`, for instance) or the name of the release series (`X.Y`) when no release has been made from that branch / for that release series yet.
* `$path` is the path to the directory (or a subdirectory thereof) where the sourcecode of the project can be found. Simply passing `__DIR__` here usually suffices.

Apart from the constructor, the `SebastianBergmann\Version` class has a single public method: `getVersion()`.

Here is a contrived example that shows the basic usage:

    <?php
    $version = new SebastianBergmann\Version(
      '3.7.10', '/usr/local/src/phpunit'
    );

    var_dump($version->getVersion());
    ?>

    string(18) "3.7.10-17-g00f3408"

When a new release is prepared, the string that is passed to the constructor as the first argument needs to be updated.

### How SebastianBergmann\Version::getVersion() works

* If `$path` is not (part of) a Git repository and `$release` is in `X.Y.Z` format then `$release` is returned as-is.
* If `$path` is not (part of) a Git repository and `$release` is in `X.Y` format then `$release` is returned suffixed with `-dev`.
* If `$path` is (part of) a Git repository and `$release` is in `X.Y.Z` format then the output of `git describe --tags` is returned as-is.
* If `$path` is (part of) a Git repository and `$release` is in `X.Y` format then a string is returned that begins with `X.Y` and ends with information from `git describe --tags`.
/.idea
*.php diff=php
{
    "name": "sebastian/version",
    "description": "Library that helps with managing the version number of Git-hosted PHP projects",
    "homepage": "https://github.com/sebastianbergmann/version",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de",
            "role": "lead"
        }
    ],
    "support": {
        "issues": "https://github.com/sebastianbergmann/version/issues"
    },
    "require": {
        "php": ">=5.6"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "2.0.x-dev"
        }
    }
}
<?php
/*
 * This file is part of the Version package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SebastianBergmann;

/**
 * @since Class available since Release 1.0.0
 */
class Version
{
    /**
     * @var string
     */
    private $path;

    /**
     * @var string
     */
    private $release;

    /**
     * @var string
     */
    private $version;

    /**
     * @param string $release
     * @param string $path
     */
    public function __construct($release, $path)
    {
        $this->release = $release;
        $this->path    = $path;
    }

    /**
     * @return string
     */
    public function getVersion()
    {
        if ($this->version === null) {
            if (count(explode('.', $this->release)) == 3) {
                $this->version = $this->release;
            } else {
                $this->version = $this->release . '-dev';
            }

            $git = $this->getGitInformation($this->path);

            if ($git) {
                if (count(explode('.', $this->release)) == 3) {
                    $this->version = $git;
                } else {
                    $git = explode('-', $git);

                    $this->version = $this->release . '-' . end($git);
                }
            }
        }

        return $this->version;
    }

    /**
     * @param string $path
     *
     * @return bool|string
     */
    private function getGitInformation($path)
    {
        if (!is_dir($path . DIRECTORY_SEPARATOR . '.git')) {
            return false;
        }

        $process = proc_open(
            'git describe --tags',
            [
                1 => ['pipe', 'w'],
                2 => ['pipe', 'w'],
            ],
            $pipes,
            $path
        );

        if (!is_resource($process)) {
            return false;
        }

        $result = trim(stream_get_contents($pipes[1]));

        fclose($pipes[1]);
        fclose($pipes[2]);

        $returnCode = proc_close($process);

        if ($returnCode !== 0) {
            return false;
        }

        return $result;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/7.5/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>
sebastian/environment

Copyright (c) 2014-2019, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# Changes in sebastianbergmann/environment

All notable changes in `sebastianbergmann/environment` are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## [4.2.4] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [4.2.3] - 2019-11-20

### Changed

* Implemented [#50](https://github.com/sebastianbergmann/environment/pull/50): Windows improvements to console capabilities

### Fixed

* Fixed [#49](https://github.com/sebastianbergmann/environment/issues/49): Detection how OpCache handles docblocks does not work correctly when PHPDBG is used

## [4.2.2] - 2019-05-05

### Fixed

* Fixed [#44](https://github.com/sebastianbergmann/environment/pull/44): `TypeError` in `Console::getNumberOfColumnsInteractive()`

## [4.2.1] - 2019-04-25

### Fixed

* Fixed an issue in `Runtime::getCurrentSettings()`

## [4.2.0] - 2019-04-25

### Added

* Implemented [#36](https://github.com/sebastianbergmann/environment/pull/36): `Runtime::getCurrentSettings()`

## [4.1.0] - 2019-02-01

### Added

* Implemented `Runtime::getNameWithVersionAndCodeCoverageDriver()` method
* Implemented [#34](https://github.com/sebastianbergmann/environment/pull/34): Support for PCOV extension

## [4.0.2] - 2019-01-28

### Fixed

* Fixed [#33](https://github.com/sebastianbergmann/environment/issues/33): `Runtime::discardsComments()` returns true too eagerly

### Removed

* Removed support for Zend Optimizer+ in `Runtime::discardsComments()`

## [4.0.1] - 2018-11-25

### Fixed

* Fixed [#31](https://github.com/sebastianbergmann/environment/issues/31): Regressions in `Console` class

## [4.0.0] - 2018-10-23 [YANKED]

### Fixed

* Fixed [#25](https://github.com/sebastianbergmann/environment/pull/25): `Console::hasColorSupport()` does not work on Windows

### Removed

* This component is no longer supported on PHP 7.0

## [3.1.0] - 2017-07-01

### Added

* Implemented [#21](https://github.com/sebastianbergmann/environment/issues/21): Equivalent of `PHP_OS_FAMILY` (for PHP < 7.2) 

## [3.0.4] - 2017-06-20

### Fixed

* Fixed [#20](https://github.com/sebastianbergmann/environment/pull/20): PHP 7 mode of HHVM not forced

## [3.0.3] - 2017-05-18

### Fixed

* Fixed [#18](https://github.com/sebastianbergmann/environment/issues/18): `Uncaught TypeError: preg_match() expects parameter 2 to be string, null given`

## [3.0.2] - 2017-04-21

### Fixed

* Fixed [#17](https://github.com/sebastianbergmann/environment/issues/17): `Uncaught TypeError: trim() expects parameter 1 to be string, boolean given`

## [3.0.1] - 2017-04-21

### Fixed

* Fixed inverted logic in `Runtime::discardsComments()`

## [3.0.0] - 2017-04-21

### Added

* Implemented `Runtime::discardsComments()` for querying whether the PHP runtime discards annotations

### Removed

* This component is no longer supported on PHP 5.6

[4.2.4]: https://github.com/sebastianbergmann/phpunit/compare/4.2.3...4.2.4
[4.2.3]: https://github.com/sebastianbergmann/phpunit/compare/4.2.2...4.2.3
[4.2.2]: https://github.com/sebastianbergmann/phpunit/compare/4.2.1...4.2.2
[4.2.1]: https://github.com/sebastianbergmann/phpunit/compare/4.2.0...4.2.1
[4.2.0]: https://github.com/sebastianbergmann/phpunit/compare/4.1.0...4.2.0
[4.1.0]: https://github.com/sebastianbergmann/phpunit/compare/4.0.2...4.1.0
[4.0.2]: https://github.com/sebastianbergmann/phpunit/compare/4.0.1...4.0.2
[4.0.1]: https://github.com/sebastianbergmann/phpunit/compare/66691f8e2dc4641909166b275a9a4f45c0e89092...4.0.1
[4.0.0]: https://github.com/sebastianbergmann/phpunit/compare/3.1.0...66691f8e2dc4641909166b275a9a4f45c0e89092
[3.1.0]: https://github.com/sebastianbergmann/phpunit/compare/3.0...3.1.0
[3.0.4]: https://github.com/sebastianbergmann/phpunit/compare/3.0.3...3.0.4
[3.0.3]: https://github.com/sebastianbergmann/phpunit/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/sebastianbergmann/phpunit/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/sebastianbergmann/phpunit/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/sebastianbergmann/phpunit/compare/2.0...3.0.0

<?xml version="1.0" encoding="UTF-8"?>
<project name="environment" default="setup">
    <target name="setup" depends="clean,composer"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>
</project>
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Environment\Console
 */
final class ConsoleTest extends TestCase
{
    /**
     * @var \SebastianBergmann\Environment\Console
     */
    private $console;

    protected function setUp(): void
    {
        $this->console = new Console;
    }

    /**
     * @todo Now that this component is PHP 7-only and uses return type declarations
     * this test makes even less sense than before
     */
    public function testCanDetectIfStdoutIsInteractiveByDefault(): void
    {
        $this->assertIsBool($this->console->isInteractive());
    }

    /**
     * @todo Now that this component is PHP 7-only and uses return type declarations
     * this test makes even less sense than before
     */
    public function testCanDetectIfFileDescriptorIsInteractive(): void
    {
        $this->assertIsBool($this->console->isInteractive(\STDOUT));
    }

    /**
     * @todo Now that this component is PHP 7-only and uses return type declarations
     * this test makes even less sense than before
     */
    public function testCanDetectColorSupport(): void
    {
        $this->assertIsBool($this->console->hasColorSupport());
    }

    /**
     * @todo Now that this component is PHP 7-only and uses return type declarations
     * this test makes even less sense than before
     */
    public function testCanDetectNumberOfColumns(): void
    {
        $this->assertIsInt($this->console->getNumberOfColumns());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Environment\OperatingSystem
 */
final class OperatingSystemTest extends TestCase
{
    /**
     * @var \SebastianBergmann\Environment\OperatingSystem
     */
    private $os;

    protected function setUp(): void
    {
        $this->os = new OperatingSystem;
    }

    /**
     * @requires OS Linux
     */
    public function testFamilyCanBeRetrieved(): void
    {
        $this->assertEquals('Linux', $this->os->getFamily());
    }

    /**
     * @requires OS Darwin
     */
    public function testFamilyReturnsDarwinWhenRunningOnDarwin(): void
    {
        $this->assertEquals('Darwin', $this->os->getFamily());
    }

    /**
     * @requires OS Windows
     */
    public function testGetFamilyReturnsWindowsWhenRunningOnWindows(): void
    {
        $this->assertSame('Windows', $this->os->getFamily());
    }

    /**
     * @requires PHP 7.2.0
     */
    public function testGetFamilyReturnsPhpOsFamilyWhenRunningOnPhp72AndGreater(): void
    {
        $this->assertSame(\PHP_OS_FAMILY, $this->os->getFamily());
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\Environment\Runtime
 */
final class RuntimeTest extends TestCase
{
    /**
     * @var \SebastianBergmann\Environment\Runtime
     */
    private $env;

    protected function setUp(): void
    {
        $this->env = new Runtime;
    }

    /**
     * @requires extension xdebug
     */
    public function testCanCollectCodeCoverageWhenXdebugExtensionIsEnabled(): void
    {
        $this->assertTrue($this->env->canCollectCodeCoverage());
    }

    /**
     * @requires extension pcov
     */
    public function testCanCollectCodeCoverageWhenPcovExtensionIsEnabled(): void
    {
        $this->assertTrue($this->env->canCollectCodeCoverage());
    }

    public function testCanCollectCodeCoverageWhenRunningOnPhpdbg(): void
    {
        $this->markTestSkippedWhenNotRunningOnPhpdbg();

        $this->assertTrue($this->env->canCollectCodeCoverage());
    }

    public function testBinaryCanBeRetrieved(): void
    {
        $this->assertNotEmpty($this->env->getBinary());
    }

    /**
     * @requires PHP
     */
    public function testIsHhvmReturnsFalseWhenRunningOnPhp(): void
    {
        $this->assertFalse($this->env->isHHVM());
    }

    /**
     * @requires PHP
     */
    public function testIsPhpReturnsTrueWhenRunningOnPhp(): void
    {
        $this->markTestSkippedWhenRunningOnPhpdbg();

        $this->assertTrue($this->env->isPHP());
    }

    /**
     * @requires extension pcov
     */
    public function testPCOVCanBeDetected(): void
    {
        $this->assertTrue($this->env->hasPCOV());
    }

    public function testPhpdbgCanBeDetected(): void
    {
        $this->markTestSkippedWhenNotRunningOnPhpdbg();

        $this->assertTrue($this->env->hasPHPDBGCodeCoverage());
    }

    /**
     * @requires extension xdebug
     */
    public function testXdebugCanBeDetected(): void
    {
        $this->markTestSkippedWhenRunningOnPhpdbg();

        $this->assertTrue($this->env->hasXdebug());
    }

    public function testNameAndVersionCanBeRetrieved(): void
    {
        $this->assertNotEmpty($this->env->getNameWithVersion());
    }

    public function testGetNameReturnsPhpdbgWhenRunningOnPhpdbg(): void
    {
        $this->markTestSkippedWhenNotRunningOnPhpdbg();

        $this->assertSame('PHPDBG', $this->env->getName());
    }

    /**
     * @requires PHP
     */
    public function testGetNameReturnsPhpdbgWhenRunningOnPhp(): void
    {
        $this->markTestSkippedWhenRunningOnPhpdbg();

        $this->assertSame('PHP', $this->env->getName());
    }

    public function testNameAndCodeCoverageDriverCanBeRetrieved(): void
    {
        $this->assertNotEmpty($this->env->getNameWithVersionAndCodeCoverageDriver());
    }

    /**
     * @requires PHP
     */
    public function testGetVersionReturnsPhpVersionWhenRunningPhp(): void
    {
        $this->assertSame(\PHP_VERSION, $this->env->getVersion());
    }

    /**
     * @requires PHP
     */
    public function testGetVendorUrlReturnsPhpDotNetWhenRunningPhp(): void
    {
        $this->assertSame('https://secure.php.net/', $this->env->getVendorUrl());
    }

    private function markTestSkippedWhenNotRunningOnPhpdbg(): void
    {
        if ($this->isRunningOnPhpdbg()) {
            return;
        }

        $this->markTestSkipped('PHPDBG is required.');
    }

    private function markTestSkippedWhenRunningOnPhpdbg(): void
    {
        if (!$this->isRunningOnPhpdbg()) {
            return;
        }

        $this->markTestSkipped('Cannot run on PHPDBG');
    }

    private function isRunningOnPhpdbg(): bool
    {
        return \PHP_SAPI === 'phpdbg';
    }
}
# sebastian/environment

This component provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths.

[![Latest Stable Version](https://img.shields.io/packagist/v/sebastian/environment.svg?style=flat-square)](https://packagist.org/packages/sebastian/environment)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.1-8892BF.svg?style=flat-square)](https://php.net/)
[![Build Status](https://travis-ci.org/sebastianbergmann/environment.svg?branch=master)](https://travis-ci.org/sebastianbergmann/environment)

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/environment

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/environment
/.idea
/vendor
/composer.lock
/composer.phar
/.php_cs.cache
/.phpunit.result.cache
github: sebastianbergmann
language: php

php:
  - 7.1
  - 7.2
  - 7.3
  - 7.4snapshot

env:
  matrix:
    - DRIVER="phpdbg"
    - DRIVER="xdebug"

before_install:
  - composer clear-cache

install:
  - travis_retry composer update --no-interaction --no-ansi --no-progress --no-suggest

script:
  - if [[ "$DRIVER" = 'phpdbg' ]]; then phpdbg -qrr vendor/bin/phpunit --coverage-clover=coverage.xml; fi
  - if [[ "$DRIVER" != 'phpdbg' ]]; then vendor/bin/phpunit --coverage-clover=coverage.xml; fi

after_success:
  - bash <(curl -s https://codecov.io/bash)

notifications:
  email: false
{
    "name": "sebastian/environment",
    "description": "Provides functionality to handle HHVM/PHP environments",
    "keywords": ["environment","hhvm","xdebug"],
    "homepage": "http://www.github.com/sebastianbergmann/environment",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^7.5"
    },
    "suggest": {
        "ext-posix": "*"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "4.2-dev"
        }
    }
}
<?php
$header = <<<'EOF'
This file is part of sebastian/environment.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'combine_nested_dirname' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => true,
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'random_api_migration' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => [
                'elements' => [
                    'const',
                    'method',
                    'property',
                ],
            ],
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

/**
 * Utility class for HHVM/PHP environment handling.
 */
final class Runtime
{
    /**
     * @var string
     */
    private static $binary;

    /**
     * Returns true when Xdebug or PCOV is available or
     * the runtime used is PHPDBG.
     */
    public function canCollectCodeCoverage(): bool
    {
        return $this->hasXdebug() || $this->hasPCOV() || $this->hasPHPDBGCodeCoverage();
    }

    /**
     * Returns true when Zend OPcache is loaded, enabled, and is configured to discard comments.
     */
    public function discardsComments(): bool
    {
        if (!\extension_loaded('Zend OPcache')) {
            return false;
        }

        if (\ini_get('opcache.save_comments') !== '0') {
            return false;
        }

        if ((\PHP_SAPI === 'cli' || \PHP_SAPI === 'phpdbg') && \ini_get('opcache.enable_cli') === '1') {
            return true;
        }

        if (\PHP_SAPI !== 'cli' && \PHP_SAPI !== 'phpdbg' && \ini_get('opcache.enable') === '1') {
            return true;
        }

        return false;
    }

    /**
     * Returns the path to the binary of the current runtime.
     * Appends ' --php' to the path when the runtime is HHVM.
     */
    public function getBinary(): string
    {
        // HHVM
        if (self::$binary === null && $this->isHHVM()) {
            // @codeCoverageIgnoreStart
            if ((self::$binary = \getenv('PHP_BINARY')) === false) {
                self::$binary = \PHP_BINARY;
            }

            self::$binary = \escapeshellarg(self::$binary) . ' --php' .
                ' -d hhvm.php7.all=1';
            // @codeCoverageIgnoreEnd
        }

        if (self::$binary === null && \PHP_BINARY !== '') {
            self::$binary = \escapeshellarg(\PHP_BINARY);
        }

        if (self::$binary === null) {
            // @codeCoverageIgnoreStart
            $possibleBinaryLocations = [
                \PHP_BINDIR . '/php',
                \PHP_BINDIR . '/php-cli.exe',
                \PHP_BINDIR . '/php.exe',
            ];

            foreach ($possibleBinaryLocations as $binary) {
                if (\is_readable($binary)) {
                    self::$binary = \escapeshellarg($binary);

                    break;
                }
            }
            // @codeCoverageIgnoreEnd
        }

        if (self::$binary === null) {
            // @codeCoverageIgnoreStart
            self::$binary = 'php';
            // @codeCoverageIgnoreEnd
        }

        return self::$binary;
    }

    public function getNameWithVersion(): string
    {
        return $this->getName() . ' ' . $this->getVersion();
    }

    public function getNameWithVersionAndCodeCoverageDriver(): string
    {
        if (!$this->canCollectCodeCoverage() || $this->hasPHPDBGCodeCoverage()) {
            return $this->getNameWithVersion();
        }

        if ($this->hasXdebug()) {
            return \sprintf(
                '%s with Xdebug %s',
                $this->getNameWithVersion(),
                \phpversion('xdebug')
            );
        }

        if ($this->hasPCOV()) {
            return \sprintf(
                '%s with PCOV %s',
                $this->getNameWithVersion(),
                \phpversion('pcov')
            );
        }
    }

    public function getName(): string
    {
        if ($this->isHHVM()) {
            // @codeCoverageIgnoreStart
            return 'HHVM';
            // @codeCoverageIgnoreEnd
        }

        if ($this->isPHPDBG()) {
            // @codeCoverageIgnoreStart
            return 'PHPDBG';
            // @codeCoverageIgnoreEnd
        }

        return 'PHP';
    }

    public function getVendorUrl(): string
    {
        if ($this->isHHVM()) {
            // @codeCoverageIgnoreStart
            return 'http://hhvm.com/';
            // @codeCoverageIgnoreEnd
        }

        return 'https://secure.php.net/';
    }

    public function getVersion(): string
    {
        if ($this->isHHVM()) {
            // @codeCoverageIgnoreStart
            return HHVM_VERSION;
            // @codeCoverageIgnoreEnd
        }

        return \PHP_VERSION;
    }

    /**
     * Returns true when the runtime used is PHP and Xdebug is loaded.
     */
    public function hasXdebug(): bool
    {
        return ($this->isPHP() || $this->isHHVM()) && \extension_loaded('xdebug');
    }

    /**
     * Returns true when the runtime used is HHVM.
     */
    public function isHHVM(): bool
    {
        return \defined('HHVM_VERSION');
    }

    /**
     * Returns true when the runtime used is PHP without the PHPDBG SAPI.
     */
    public function isPHP(): bool
    {
        return !$this->isHHVM() && !$this->isPHPDBG();
    }

    /**
     * Returns true when the runtime used is PHP with the PHPDBG SAPI.
     */
    public function isPHPDBG(): bool
    {
        return \PHP_SAPI === 'phpdbg' && !$this->isHHVM();
    }

    /**
     * Returns true when the runtime used is PHP with the PHPDBG SAPI
     * and the phpdbg_*_oplog() functions are available (PHP >= 7.0).
     */
    public function hasPHPDBGCodeCoverage(): bool
    {
        return $this->isPHPDBG();
    }

    /**
     * Returns true when the runtime used is PHP with PCOV loaded and enabled
     */
    public function hasPCOV(): bool
    {
        return $this->isPHP() && \extension_loaded('pcov') && \ini_get('pcov.enabled');
    }

    /**
     * Parses the loaded php.ini file (if any) as well as all
     * additional php.ini files from the additional ini dir for
     * a list of all configuration settings loaded from files
     * at startup. Then checks for each php.ini setting passed
     * via the `$values` parameter whether this setting has
     * been changed at runtime. Returns an array of strings
     * where each string has the format `key=value` denoting
     * the name of a changed php.ini setting with its new value.
     *
     * @return string[]
     */
    public function getCurrentSettings(array $values): array
    {
        $diff  = [];
        $files = [];

        if ($file = \php_ini_loaded_file()) {
            $files[] = $file;
        }

        if ($scanned = \php_ini_scanned_files()) {
            $files = \array_merge(
                $files,
                \array_map(
                    'trim',
                    \explode(",\n", $scanned)
                )
            );
        }

        foreach ($files as $ini) {
            $config = \parse_ini_file($ini, true);

            foreach ($values as $value) {
                $set = \ini_get($value);

                if (isset($config[$value]) && $set != $config[$value]) {
                    $diff[] = \sprintf('%s=%s', $value, $set);
                }
            }
        }

        return $diff;
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

final class OperatingSystem
{
    /**
     * Returns PHP_OS_FAMILY (if defined (which it is on PHP >= 7.2)).
     * Returns a string (compatible with PHP_OS_FAMILY) derived from PHP_OS otherwise.
     */
    public function getFamily(): string
    {
        if (\defined('PHP_OS_FAMILY')) {
            return \PHP_OS_FAMILY;
        }

        if (\DIRECTORY_SEPARATOR === '\\') {
            return 'Windows';
        }

        switch (\PHP_OS) {
            case 'Darwin':
                return 'Darwin';

            case 'DragonFly':
            case 'FreeBSD':
            case 'NetBSD':
            case 'OpenBSD':
                return 'BSD';

            case 'Linux':
                return 'Linux';

            case 'SunOS':
                return 'Solaris';

            default:
                return 'Unknown';
        }
    }
}
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/environment.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Environment;

final class Console
{
    /**
     * @var int
     */
    public const STDIN  = 0;

    /**
     * @var int
     */
    public const STDOUT = 1;

    /**
     * @var int
     */
    public const STDERR = 2;

    /**
     * Returns true if STDOUT supports colorization.
     *
     * This code has been copied and adapted from
     * Symfony\Component\Console\Output\StreamOutput.
     */
    public function hasColorSupport(): bool
    {
        if ('Hyper' === \getenv('TERM_PROGRAM')) {
            return true;
        }

        if ($this->isWindows()) {
            // @codeCoverageIgnoreStart
            return (\defined('STDOUT') && \function_exists('sapi_windows_vt100_support') && @\sapi_windows_vt100_support(\STDOUT))
                || false !== \getenv('ANSICON')
                || 'ON' === \getenv('ConEmuANSI')
                || 'xterm' === \getenv('TERM');
            // @codeCoverageIgnoreEnd
        }

        if (!\defined('STDOUT')) {
            // @codeCoverageIgnoreStart
            return false;
            // @codeCoverageIgnoreEnd
        }

        return $this->isInteractive(\STDOUT);
    }

    /**
     * Returns the number of columns of the terminal.
     *
     * @codeCoverageIgnore
     */
    public function getNumberOfColumns(): int
    {
        if (!$this->isInteractive(\defined('STDIN') ? \STDIN : self::STDIN)) {
            return 80;
        }

        if ($this->isWindows()) {
            return $this->getNumberOfColumnsWindows();
        }

        return $this->getNumberOfColumnsInteractive();
    }

    /**
     * Returns if the file descriptor is an interactive terminal or not.
     *
     * Normally, we want to use a resource as a parameter, yet sadly it's not always awailable,
     * eg when running code in interactive console (`php -a`), STDIN/STDOUT/STDERR constants are not defined.
     *
     * @param int|resource $fileDescriptor
     */
    public function isInteractive($fileDescriptor = self::STDOUT): bool
    {
        if (\is_resource($fileDescriptor)) {
            // These functions require a descriptor that is a real resource, not a numeric ID of it
            if (\function_exists('stream_isatty') && @\stream_isatty($fileDescriptor)) {
                return true;
            }

            $stat = @\fstat(\STDOUT);
            // Check if formatted mode is S_IFCHR
            return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
        }

        return \function_exists('posix_isatty') && @\posix_isatty($fileDescriptor);
    }

    private function isWindows(): bool
    {
        return \DIRECTORY_SEPARATOR === '\\';
    }

    /**
     * @codeCoverageIgnore
     */
    private function getNumberOfColumnsInteractive(): int
    {
        if (\function_exists('shell_exec') && \preg_match('#\d+ (\d+)#', \shell_exec('stty size') ?: '', $match) === 1) {
            if ((int) $match[1] > 0) {
                return (int) $match[1];
            }
        }

        if (\function_exists('shell_exec') && \preg_match('#columns = (\d+);#', \shell_exec('stty') ?: '', $match) === 1) {
            if ((int) $match[1] > 0) {
                return (int) $match[1];
            }
        }

        return 80;
    }

    /**
     * @codeCoverageIgnore
     */
    private function getNumberOfColumnsWindows(): int
    {
        $ansicon = \getenv('ANSICON');
        $columns = 80;

        if (\is_string($ansicon) && \preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', \trim($ansicon), $matches)) {
            $columns = $matches[1];
        } elseif (\function_exists('proc_open')) {
            $process = \proc_open(
                'mode CON',
                [
                    1 => ['pipe', 'w'],
                    2 => ['pipe', 'w'],
                ],
                $pipes,
                null,
                null,
                ['suppress_errors' => true]
            );

            if (\is_resource($process)) {
                $info = \stream_get_contents($pipes[1]);

                \fclose($pipes[1]);
                \fclose($pipes[2]);
                \proc_close($process);

                if (\preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
                    $columns = $matches[2];
                }
            }
        }

        return $columns - 1;
    }
}
Exporter

Copyright (c) 2002-2021, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.

## [3.1.5] - 2022-09-14

### Fixed

* [#47](https://github.com/sebastianbergmann/exporter/pull/47): Fix `float` export precision

## [3.1.4] - 2021-11-11

### Changed

* [#38](https://github.com/sebastianbergmann/exporter/pull/38): Improve export of closed resources

## [3.1.3] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.0` to `>=7.0`

## [3.1.2] - 2019-09-14

### Fixed

* [#29](https://github.com/sebastianbergmann/exporter/pull/29): Second parameter for `str_repeat()` must be an integer

### Removed

* Remove HHVM-specific code that is no longer needed

[3.1.5]: https://github.com/sebastianbergmann/exporter/compare/3.1.4...3.1.5
[3.1.4]: https://github.com/sebastianbergmann/exporter/compare/3.1.3...3.1.4
[3.1.3]: https://github.com/sebastianbergmann/exporter/compare/3.1.2...3.1.3
[3.1.2]: https://github.com/sebastianbergmann/exporter/compare/3.1.1...3.1.2
Exporter
========

This component provides the functionality to export PHP variables for visualization.

## Usage

Exporting:

```php
<?php
use SebastianBergmann\Exporter\Exporter;

$exporter = new Exporter;

/*
Exception Object &0000000078de0f0d000000002003a261 (
    'message' => ''
    'string' => ''
    'code' => 0
    'file' => '/home/sebastianbergmann/test.php'
    'line' => 34
    'previous' => null
)
*/

print $exporter->export(new Exception);
```

## Data Types

Exporting simple types:

```php
<?php
use SebastianBergmann\Exporter\Exporter;

$exporter = new Exporter;

// 46
print $exporter->export(46);

// 4.0
print $exporter->export(4.0);

// 'hello, world!'
print $exporter->export('hello, world!');

// false
print $exporter->export(false);

// NAN
print $exporter->export(acos(8));

// -INF
print $exporter->export(log(0));

// null
print $exporter->export(null);

// resource(13) of type (stream)
print $exporter->export(fopen('php://stderr', 'w'));

// Binary String: 0x000102030405
print $exporter->export(chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5));
```

Exporting complex types:

```php
<?php
use SebastianBergmann\Exporter\Exporter;

$exporter = new Exporter;

/*
Array &0 (
    0 => Array &1 (
        0 => 1
        1 => 2
        2 => 3
    )
    1 => Array &2 (
        0 => ''
        1 => 0
        2 => false
    )
)
*/

print $exporter->export(array(array(1,2,3), array("",0,FALSE)));

/*
Array &0 (
    'self' => Array &1 (
        'self' => Array &1
    )
)
*/

$array = array();
$array['self'] = &$array;
print $exporter->export($array);

/*
stdClass Object &0000000003a66dcc0000000025e723e2 (
    'self' => stdClass Object &0000000003a66dcc0000000025e723e2
)
*/

$obj = new stdClass();
$obj->self = $obj;
print $exporter->export($obj);
```

Compact exports:

```php
<?php
use SebastianBergmann\Exporter\Exporter;

$exporter = new Exporter;

// Array ()
print $exporter->shortenedExport(array());

// Array (...)
print $exporter->shortenedExport(array(1,2,3,4,5));

// stdClass Object ()
print $exporter->shortenedExport(new stdClass);

// Exception Object (...)
print $exporter->shortenedExport(new Exception);

// this\nis\na\nsuper\nlong\nstring\nt...\nspace
print $exporter->shortenedExport(
<<<LONG_STRING
this
is
a
super
long
string
that
wraps
a
lot
and
eats
up
a
lot
of
space
LONG_STRING
);
```

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/exporter

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/exporter

{
    "name": "sebastian/exporter",
    "description": "Provides the functionality to export PHP variables for visualization",
    "keywords": ["exporter","export"],
    "homepage": "http://www.github.com/sebastianbergmann/exporter",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        },
        {
            "name": "Jeff Welch",
            "email": "whatthejeff@gmail.com"
        },
        {
            "name": "Volker Dusch",
            "email": "github@wallbash.com"
        },
        {
            "name": "Adam Harvey",
            "email": "aharvey@php.net"
        },
        {
            "name": "Bernhard Schussek",
            "email": "bschussek@gmail.com"
        }
    ],
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "prefer-stable": true,
    "require": {
        "php": ">=7.0",
        "sebastian/recursion-context": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^8.5",
        "ext-mbstring": "*"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.1.x-dev"
        }
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of exporter package.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Exporter;

use SebastianBergmann\RecursionContext\Context;

/**
 * A nifty utility for visualizing PHP variables.
 *
 * <code>
 * <?php
 * use SebastianBergmann\Exporter\Exporter;
 *
 * $exporter = new Exporter;
 * print $exporter->export(new Exception);
 * </code>
 */
class Exporter
{
    /**
     * Exports a value as a string
     *
     * The output of this method is similar to the output of print_r(), but
     * improved in various aspects:
     *
     *  - NULL is rendered as "null" (instead of "")
     *  - TRUE is rendered as "true" (instead of "1")
     *  - FALSE is rendered as "false" (instead of "")
     *  - Strings are always quoted with single quotes
     *  - Carriage returns and newlines are normalized to \n
     *  - Recursion and repeated rendering is treated properly
     *
     * @param int $indentation The indentation level of the 2nd+ line
     *
     * @return string
     */
    public function export($value, $indentation = 0)
    {
        return $this->recursiveExport($value, $indentation);
    }

    /**
     * @param array<mixed> $data
     * @param Context      $context
     *
     * @return string
     */
    public function shortenedRecursiveExport(&$data, Context $context = null)
    {
        $result   = [];
        $exporter = new self();

        if (!$context) {
            $context = new Context;
        }

        $array = $data;
        $context->add($data);

        foreach ($array as $key => $value) {
            if (\is_array($value)) {
                if ($context->contains($data[$key]) !== false) {
                    $result[] = '*RECURSION*';
                } else {
                    $result[] = \sprintf(
                        'array(%s)',
                        $this->shortenedRecursiveExport($data[$key], $context)
                    );
                }
            } else {
                $result[] = $exporter->shortenedExport($value);
            }
        }

        return \implode(', ', $result);
    }

    /**
     * Exports a value into a single-line string
     *
     * The output of this method is similar to the output of
     * SebastianBergmann\Exporter\Exporter::export().
     *
     * Newlines are replaced by the visible string '\n'.
     * Contents of arrays and objects (if any) are replaced by '...'.
     *
     * @return string
     *
     * @see    SebastianBergmann\Exporter\Exporter::export
     */
    public function shortenedExport($value)
    {
        if (\is_string($value)) {
            $string = \str_replace("\n", '', $this->export($value));

            if (\function_exists('mb_strlen')) {
                if (\mb_strlen($string) > 40) {
                    $string = \mb_substr($string, 0, 30) . '...' . \mb_substr($string, -7);
                }
            } else {
                if (\strlen($string) > 40) {
                    $string = \substr($string, 0, 30) . '...' . \substr($string, -7);
                }
            }

            return $string;
        }

        if (\is_object($value)) {
            return \sprintf(
                '%s Object (%s)',
                \get_class($value),
                \count($this->toArray($value)) > 0 ? '...' : ''
            );
        }

        if (\is_array($value)) {
            return \sprintf(
                'Array (%s)',
                \count($value) > 0 ? '...' : ''
            );
        }

        return $this->export($value);
    }

    /**
     * Converts an object to an array containing all of its private, protected
     * and public properties.
     *
     * @return array
     */
    public function toArray($value)
    {
        if (!\is_object($value)) {
            return (array) $value;
        }

        $array = [];

        foreach ((array) $value as $key => $val) {
            // Exception traces commonly reference hundreds to thousands of
            // objects currently loaded in memory. Including them in the result
            // has a severe negative performance impact.
            if ("\0Error\0trace" === $key || "\0Exception\0trace" === $key) {
                continue;
            }

            // properties are transformed to keys in the following way:
            // private   $property => "\0Classname\0property"
            // protected $property => "\0*\0property"
            // public    $property => "property"
            if (\preg_match('/^\0.+\0(.+)$/', (string) $key, $matches)) {
                $key = $matches[1];
            }

            // See https://github.com/php/php-src/commit/5721132
            if ($key === "\0gcdata") {
                continue;
            }

            $array[$key] = $val;
        }

        // Some internal classes like SplObjectStorage don't work with the
        // above (fast) mechanism nor with reflection in Zend.
        // Format the output similarly to print_r() in this case
        if ($value instanceof \SplObjectStorage) {
            foreach ($value as $key => $val) {
                $array[\spl_object_hash($val)] = [
                    'obj' => $val,
                    'inf' => $value->getInfo(),
                ];
            }
        }

        return $array;
    }

    /**
     * Recursive implementation of export
     *
     * @param mixed                                       $value       The value to export
     * @param int                                         $indentation The indentation level of the 2nd+ line
     * @param \SebastianBergmann\RecursionContext\Context $processed   Previously processed objects
     *
     * @return string
     *
     * @see    SebastianBergmann\Exporter\Exporter::export
     */
    protected function recursiveExport(&$value, $indentation, $processed = null)
    {
        if ($value === null) {
            return 'null';
        }

        if ($value === true) {
            return 'true';
        }

        if ($value === false) {
            return 'false';
        }

        if (\is_float($value)) {
            $precisionBackup = \ini_get('precision');

            \ini_set('precision', '-1');

            try {
                $valueStr = (string) $value;

                if ((string) (int) $value === $valueStr) {
                    return $valueStr . '.0';
                }

                return $valueStr;
            } finally {
                \ini_set('precision', $precisionBackup);
            }
        }

        if ($this->isClosedResource($value)) {
            return 'resource (closed)';
        }

        if (\is_resource($value)) {
            return \sprintf(
                'resource(%d) of type (%s)',
                $value,
                \get_resource_type($value)
            );
        }

        if (\is_string($value)) {
            // Match for most non printable chars somewhat taking multibyte chars into account
            if (\preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value)) {
                return 'Binary String: 0x' . \bin2hex($value);
            }

            return "'" .
            \str_replace(
                '<lf>',
                "\n",
                \str_replace(
                    ["\r\n", "\n\r", "\r", "\n"],
                    ['\r\n<lf>', '\n\r<lf>', '\r<lf>', '\n<lf>'],
                    $value
                )
            ) .
            "'";
        }

        $whitespace = \str_repeat(' ', (int)(4 * $indentation));

        if (!$processed) {
            $processed = new Context;
        }

        if (\is_array($value)) {
            if (($key = $processed->contains($value)) !== false) {
                return 'Array &' . $key;
            }

            $array  = $value;
            $key    = $processed->add($value);
            $values = '';

            if (\count($array) > 0) {
                foreach ($array as $k => $v) {
                    $values .= \sprintf(
                        '%s    %s => %s' . "\n",
                        $whitespace,
                        $this->recursiveExport($k, $indentation),
                        $this->recursiveExport($value[$k], $indentation + 1, $processed)
                    );
                }

                $values = "\n" . $values . $whitespace;
            }

            return \sprintf('Array &%s (%s)', $key, $values);
        }

        if (\is_object($value)) {
            $class = \get_class($value);

            if ($hash = $processed->contains($value)) {
                return \sprintf('%s Object &%s', $class, $hash);
            }

            $hash   = $processed->add($value);
            $values = '';
            $array  = $this->toArray($value);

            if (\count($array) > 0) {
                foreach ($array as $k => $v) {
                    $values .= \sprintf(
                        '%s    %s => %s' . "\n",
                        $whitespace,
                        $this->recursiveExport($k, $indentation),
                        $this->recursiveExport($v, $indentation + 1, $processed)
                    );
                }

                $values = "\n" . $values . $whitespace;
            }

            return \sprintf('%s Object &%s (%s)', $class, $hash, $values);
        }

        return \var_export($value, true);
    }

    /**
     * Determines whether a variable represents a resource, either open or closed.
     *
     * @param mixed $actual The variable to test.
     *
     * @return bool
     */
    private function isResource($value)
    {
        return $value !== null
            && \is_scalar($value) === false
            && \is_array($value) === false
            && \is_object($value) === false;
    }

    /**
     * Determines whether a variable represents a closed resource.
     *
     * @param mixed $actual The variable to test.
     *
     * @return bool
     */
    private function isClosedResource($value)
    {
        /*
         * PHP 7.2 introduced "resource (closed)".
         */
        if (\gettype($value) === 'resource (closed)') {
            return true;
        }

        /*
         * If gettype did not work, attempt to determine whether this is
         * a closed resource in another way.
         */
        $isResource       = \is_resource($value);
        $isNotNonResource = $this->isResource($value);

        if ($isResource === false && $isNotNonResource === true) {
            return true;
        }

        if ($isNotNonResource === true) {
            try {
                $resourceType = @\get_resource_type($value);

                if ($resourceType === 'Unknown') {
                    return true;
                }
            } catch (TypeError $e) {
                // Ignore. Not a resource.
            } catch (Exception $e) {
                // Ignore. Not a resource.
            }
        }

        return false;
    }
}
Resource Operations

Copyright (c) 2015-2018, Sebastian Bergmann <sebastian@phpunit.de>.
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 Sebastian Bergmann nor the names of his
   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 OWNER OR 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.
# ChangeLog

All notable changes are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.

## [2.0.2] - 2020-11-30

### Changed

* Changed PHP version constraint in `composer.json` from `^7.1` to `>=7.1`

## [2.0.1] - 2018-10-04

### Fixed

* Functions and methods with nullable parameters of type `resource` are now also considered

## [2.0.0] - 2018-09-27

### Changed

* [FunctionSignatureMap.php](https://raw.githubusercontent.com/phan/phan/master/src/Phan/Language/Internal/FunctionSignatureMap.php) from `phan/phan` is now used instead of [arginfo.php](https://raw.githubusercontent.com/rlerdorf/phan/master/includes/arginfo.php) from `rlerdorf/phan`

### Removed

* This component is no longer supported on PHP 5.6 and PHP 7.0

## 1.0.0 - 2015-07-28

* Initial release

[2.0.2]: https://github.com/sebastianbergmann/comparator/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/sebastianbergmann/comparator/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/sebastianbergmann/comparator/compare/1.0.0...2.0.0
<?xml version="1.0" encoding="UTF-8"?>
<project name="resource-operations" default="setup">
    <target name="setup" depends="clean,composer,generate"/>

    <target name="clean" description="Cleanup build artifacts">
        <delete dir="${basedir}/vendor"/>
        <delete file="${basedir}/composer.lock"/>
    </target>

    <target name="composer" depends="clean" description="Install dependencies with Composer">
        <exec executable="composer" taskname="composer">
            <arg value="update"/>
            <arg value="--no-interaction"/>
            <arg value="--no-progress"/>
            <arg value="--no-ansi"/>
            <arg value="--no-suggest"/>
        </exec>
    </target>

    <target name="generate" depends="-download-arginfo">
        <exec executable="${basedir}/build/generate.php" taskname="generate" />
    </target>

    <target name="-download-arginfo">
        <tstamp>
            <format property="thirty.days.ago" pattern="MM/dd/yyyy hh:mm aa" offset="-30" unit="day"/>
        </tstamp>

        <delete>
            <fileset dir="${basedir}/build">
                <include name="arginfo.php" />
                <date datetime="${thirty.days.ago}" when="before"/>
            </fileset>
        </delete>

        <get src="https://raw.githubusercontent.com/phan/phan/master/src/Phan/Language/Internal/FunctionSignatureMap.php" dest="${basedir}/build/FunctionSignatureMap.php" skipexisting="true"/>
    </target>
</project>
<?php declare(strict_types=1);
/*
 * This file is part of resource-operations.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\ResourceOperations;

use PHPUnit\Framework\TestCase;

/**
 * @covers \SebastianBergmann\ResourceOperations\ResourceOperations
 */
final class ResourceOperationsTest extends TestCase
{
    public function testGetFunctions(): void
    {
        $functions = ResourceOperations::getFunctions();

        $this->assertInternalType('array', $functions);
        $this->assertContains('fopen', $functions);
    }
}
# Resource Operations

Provides a list of PHP built-in functions that operate on resources.

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

    composer require sebastian/resource-operations

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

    composer require --dev sebastian/resource-operations

/.idea
/.php_cs.cache
/build/FunctionSignatureMap.php
/composer.lock
/vendor
# Configuration for probot-stale - https://github.com/probot/stale

# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 60

# Number of days of inactivity before a stale Issue or Pull Request is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 7

# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
  - enhancement

# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false

# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false

# Label to use when marking as stale
staleLabel: stale

# Comment to post when marking as stale. Set to `false` to disable
markComment: >
  This issue has been automatically marked as stale because it has not had activity within the last 60 days. It will be closed after 7 days if no further activity occurs. Thank you for your contributions.

# Comment to post when removing the stale label.
# unmarkComment: >
#   Your comment here.

# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
  This issue has been automatically closed because it has not had activity since it was marked as stale. Thank you for your contributions.

# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

# Limit to only `issues` or `pulls`
only: issues

#!/usr/bin/env php
<?php declare(strict_types=1);
/*
 * This file is part of resource-operations.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$functions         = require __DIR__ . '/FunctionSignatureMap.php';
$resourceFunctions = [];

foreach ($functions as $function => $arguments) {
    foreach ($arguments as $argument) {
        if (strpos($argument, '?') === 0) {
            $argument = substr($argument, 1);
        }

        if ($argument === 'resource') {
            $resourceFunctions[] = explode('\'', $function)[0];
        }
    }
}

$resourceFunctions = array_unique($resourceFunctions);
sort($resourceFunctions);

$buffer = <<<EOT
<?php declare(strict_types=1);
/*
 * This file is part of resource-operations.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\ResourceOperations;

final class ResourceOperations
{
    /**
     * @return string[]
     */
    public static function getFunctions(): array
    {
        return [

EOT;

foreach ($resourceFunctions as $function) {
    $buffer .= sprintf("            '%s',\n", $function);
}

$buffer .= <<< EOT
        ];
    }
}

EOT;

file_put_contents(__DIR__ . '/../src/ResourceOperations.php', $buffer);

{
    "name": "sebastian/resource-operations",
    "description": "Provides a list of PHP built-in functions that operate on resources",
    "homepage": "https://www.github.com/sebastianbergmann/resource-operations",
    "license": "BSD-3-Clause",
    "authors": [
        {
            "name": "Sebastian Bergmann",
            "email": "sebastian@phpunit.de"
        }
    ],
    "require": {
        "php": ">=7.1"
    },
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "config": {
        "platform": {
            "php": "7.1.0"
        },
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "extra": {
        "branch-alias": {
            "dev-master": "2.0-dev"
        }
    }
}

<?php
$header = <<<'EOF'
This file is part of resource-operations.

(c) Sebastian Bergmann <sebastian@phpunit.de>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

return PhpCsFixer\Config::create()
    ->setRiskyAllowed(true)
    ->setRules(
        [
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'array_syntax' => ['syntax' => 'short'],
            'binary_operator_spaces' => [
                'operators' => [
                    '=' => 'align',
                    '=>' => 'align',
                ],
            ],
            'blank_line_after_namespace' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'continue',
                    'declare',
                    'do',
                    'for',
                    'foreach',
                    'if',
                    'include',
                    'include_once',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'while',
                    'yield',
                ],
            ],
            'braces' => true,
            'cast_spaces' => true,
            'class_attributes_separation' => ['elements' => ['const', 'method', 'property']],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'compact_nullable_typehint' => true,
            'concat_space' => ['spacing' => 'one'],
            'declare_equal_normalize' => ['space' => 'none'],
            'declare_strict_types' => true,
            'dir_constant' => true,
            'elseif' => true,
            'encoding' => true,
            'full_opening_tag' => true,
            'function_declaration' => true,
            'header_comment' => ['header' => $header, 'separate' => 'none'],
            'indentation_type' => true,
            'is_null' => true,
            'line_ending' => true,
            'list_syntax' => ['syntax' => 'short'],
            'logical_operators' => true,
            'lowercase_cast' => true,
            'lowercase_constants' => true,
            'lowercase_keywords' => true,
            'lowercase_static_reference' => true,
            'magic_constant_casing' => true,
            'method_argument_space' => ['ensure_fully_multiline' => true],
            'modernize_types_casting' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => true,
            'native_constant_invocation' => true,
            'native_function_casing' => true,
            'native_function_invocation' => true,
            'new_with_braces' => false,
            'no_alias_functions' => true,
            'no_alternative_syntax' => true,
            'no_blank_lines_after_class_opening' => true,
            'no_blank_lines_after_phpdoc' => true,
            'no_blank_lines_before_namespace' => true,
            'no_closing_tag' => true,
            'no_empty_comment' => true,
            'no_empty_phpdoc' => true,
            'no_empty_statement' => true,
            'no_extra_blank_lines' => true,
            'no_homoglyph_names' => true,
            'no_leading_import_slash' => true,
            'no_leading_namespace_whitespace' => true,
            'no_mixed_echo_print' => ['use' => 'print'],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_null_property_initialization' => true,
            'no_php4_constructor' => true,
            'no_short_bool_cast' => true,
            'no_short_echo_tag' => true,
            'no_singleline_whitespace_before_semicolons' => true,
            'no_spaces_after_function_name' => true,
            'no_spaces_inside_parenthesis' => true,
            'no_superfluous_elseif' => true,
            'no_superfluous_phpdoc_tags' => true,
            'no_trailing_comma_in_list_call' => true,
            'no_trailing_comma_in_singleline_array' => true,
            'no_trailing_whitespace' => true,
            'no_trailing_whitespace_in_comment' => true,
            'no_unneeded_control_parentheses' => true,
            'no_unneeded_curly_braces' => true,
            'no_unneeded_final_method' => true,
            'no_unreachable_default_argument_value' => true,
            'no_unset_on_property' => true,
            'no_unused_imports' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'no_whitespace_before_comma_in_array' => true,
            'no_whitespace_in_blank_line' => true,
            'non_printable_character' => true,
            'normalize_index_brace' => true,
            'object_operator_without_whitespace' => true,
            'ordered_class_elements' => [
                'order' => [
                    'use_trait',
                    'constant_public',
                    'constant_protected',
                    'constant_private',
                    'property_public_static',
                    'property_protected_static',
                    'property_private_static',
                    'property_public',
                    'property_protected',
                    'property_private',
                    'method_public_static',
                    'construct',
                    'destruct',
                    'magic',
                    'phpunit',
                    'method_public',
                    'method_protected',
                    'method_private',
                    'method_protected_static',
                    'method_private_static',
                ],
            ],
            'ordered_imports' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_align' => true,
            'phpdoc_annotation_without_dot' => true,
            'phpdoc_indent' => true,
            'phpdoc_no_access' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_no_package' => true,
            'phpdoc_order' => true,
            'phpdoc_return_self_reference' => true,
            'phpdoc_scalar' => true,
            'phpdoc_separation' => true,
            'phpdoc_single_line_var_spacing' => true,
            'phpdoc_to_comment' => true,
            'phpdoc_trim' => true,
            'phpdoc_trim_consecutive_blank_line_separation' => true,
            'phpdoc_types' => true,
            'phpdoc_types_order' => true,
            'phpdoc_var_without_name' => true,
            'pow_to_exponentiation' => true,
            'protected_to_private' => true,
            'return_assignment' => true,
            'return_type_declaration' => ['space_before' => 'none'],
            'self_accessor' => true,
            'semicolon_after_instruction' => true,
            'set_type_to_cast' => true,
            'short_scalar_cast' => true,
            'simplified_null_return' => true,
            'single_blank_line_at_eof' => true,
            'single_import_per_statement' => true,
            'single_line_after_imports' => true,
            'single_quote' => true,
            'standardize_not_equals' => true,
            'ternary_to_null_coalescing' => true,
            'trailing_comma_in_multiline_array' => true,
            'trim_array_spaces' => true,
            'unary_operator_spaces' => true,
            'visibility_required' => true,
            'void_return' => true,
            'whitespace_after_comma_in_array' => true,
        ]
    )
    ->setFinder(
        PhpCsFixer\Finder::create()
        ->files()
        ->in(__DIR__ . '/src')
        ->in(__DIR__ . '/tests')
    );
<?php declare(strict_types=1);
/*
 * This file is part of resource-operations.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\ResourceOperations;

final class ResourceOperations
{
    /**
     * @return string[]
     */
    public static function getFunctions(): array
    {
        return [
            'Directory::close',
            'Directory::read',
            'Directory::rewind',
            'DirectoryIterator::openFile',
            'FilesystemIterator::openFile',
            'Gmagick::readimagefile',
            'HttpResponse::getRequestBodyStream',
            'HttpResponse::getStream',
            'HttpResponse::setStream',
            'Imagick::pingImageFile',
            'Imagick::readImageFile',
            'Imagick::writeImageFile',
            'Imagick::writeImagesFile',
            'MongoGridFSCursor::__construct',
            'MongoGridFSFile::getResource',
            'MysqlndUhConnection::stmtInit',
            'MysqlndUhConnection::storeResult',
            'MysqlndUhConnection::useResult',
            'PDF_activate_item',
            'PDF_add_launchlink',
            'PDF_add_locallink',
            'PDF_add_nameddest',
            'PDF_add_note',
            'PDF_add_pdflink',
            'PDF_add_table_cell',
            'PDF_add_textflow',
            'PDF_add_thumbnail',
            'PDF_add_weblink',
            'PDF_arc',
            'PDF_arcn',
            'PDF_attach_file',
            'PDF_begin_document',
            'PDF_begin_font',
            'PDF_begin_glyph',
            'PDF_begin_item',
            'PDF_begin_layer',
            'PDF_begin_page',
            'PDF_begin_page_ext',
            'PDF_begin_pattern',
            'PDF_begin_template',
            'PDF_begin_template_ext',
            'PDF_circle',
            'PDF_clip',
            'PDF_close',
            'PDF_close_image',
            'PDF_close_pdi',
            'PDF_close_pdi_page',
            'PDF_closepath',
            'PDF_closepath_fill_stroke',
            'PDF_closepath_stroke',
            'PDF_concat',
            'PDF_continue_text',
            'PDF_create_3dview',
            'PDF_create_action',
            'PDF_create_annotation',
            'PDF_create_bookmark',
            'PDF_create_field',
            'PDF_create_fieldgroup',
            'PDF_create_gstate',
            'PDF_create_pvf',
            'PDF_create_textflow',
            'PDF_curveto',
            'PDF_define_layer',
            'PDF_delete',
            'PDF_delete_pvf',
            'PDF_delete_table',
            'PDF_delete_textflow',
            'PDF_encoding_set_char',
            'PDF_end_document',
            'PDF_end_font',
            'PDF_end_glyph',
            'PDF_end_item',
            'PDF_end_layer',
            'PDF_end_page',
            'PDF_end_page_ext',
            'PDF_end_pattern',
            'PDF_end_template',
            'PDF_endpath',
            'PDF_fill',
            'PDF_fill_imageblock',
            'PDF_fill_pdfblock',
            'PDF_fill_stroke',
            'PDF_fill_textblock',
            'PDF_findfont',
            'PDF_fit_image',
            'PDF_fit_pdi_page',
            'PDF_fit_table',
            'PDF_fit_textflow',
            'PDF_fit_textline',
            'PDF_get_apiname',
            'PDF_get_buffer',
            'PDF_get_errmsg',
            'PDF_get_errnum',
            'PDF_get_parameter',
            'PDF_get_pdi_parameter',
            'PDF_get_pdi_value',
            'PDF_get_value',
            'PDF_info_font',
            'PDF_info_matchbox',
            'PDF_info_table',
            'PDF_info_textflow',
            'PDF_info_textline',
            'PDF_initgraphics',
            'PDF_lineto',
            'PDF_load_3ddata',
            'PDF_load_font',
            'PDF_load_iccprofile',
            'PDF_load_image',
            'PDF_makespotcolor',
            'PDF_moveto',
            'PDF_new',
            'PDF_open_ccitt',
            'PDF_open_file',
            'PDF_open_image',
            'PDF_open_image_file',
            'PDF_open_memory_image',
            'PDF_open_pdi',
            'PDF_open_pdi_document',
            'PDF_open_pdi_page',
            'PDF_pcos_get_number',
            'PDF_pcos_get_stream',
            'PDF_pcos_get_string',
            'PDF_place_image',
            'PDF_place_pdi_page',
            'PDF_process_pdi',
            'PDF_rect',
            'PDF_restore',
            'PDF_resume_page',
            'PDF_rotate',
            'PDF_save',
            'PDF_scale',
            'PDF_set_border_color',
            'PDF_set_border_dash',
            'PDF_set_border_style',
            'PDF_set_gstate',
            'PDF_set_info',
            'PDF_set_layer_dependency',
            'PDF_set_parameter',
            'PDF_set_text_pos',
            'PDF_set_value',
            'PDF_setcolor',
            'PDF_setdash',
            'PDF_setdashpattern',
            'PDF_setflat',
            'PDF_setfont',
            'PDF_setgray',
            'PDF_setgray_fill',
            'PDF_setgray_stroke',
            'PDF_setlinecap',
            'PDF_setlinejoin',
            'PDF_setlinewidth',
            'PDF_setmatrix',
            'PDF_setmiterlimit',
            'PDF_setrgbcolor',
            'PDF_setrgbcolor_fill',
            'PDF_setrgbcolor_stroke',
            'PDF_shading',
            'PDF_shading_pattern',
            'PDF_shfill',
            'PDF_show',
            'PDF_show_boxed',
            'PDF_show_xy',
            'PDF_skew',
            'PDF_stringwidth',
            'PDF_stroke',
            'PDF_suspend_page',
            'PDF_translate',
            'PDF_utf16_to_utf8',
            'PDF_utf32_to_utf16',
            'PDF_utf8_to_utf16',
            'PDO::pgsqlLOBOpen',
            'RarEntry::getStream',
            'SQLite3::openBlob',
            'SWFMovie::saveToFile',
            'SplFileInfo::openFile',
            'SplFileObject::openFile',
            'SplTempFileObject::openFile',
            'V8Js::compileString',
            'V8Js::executeScript',
            'Vtiful\Kernel\Excel::setColumn',
            'Vtiful\Kernel\Excel::setRow',
            'Vtiful\Kernel\Format::align',
            'Vtiful\Kernel\Format::bold',
            'Vtiful\Kernel\Format::italic',
            'Vtiful\Kernel\Format::underline',
            'XMLWriter::openMemory',
            'XMLWriter::openURI',
            'ZipArchive::getStream',
            'Zookeeper::setLogStream',
            'apc_bin_dumpfile',
            'apc_bin_loadfile',
            'bbcode_add_element',
            'bbcode_add_smiley',
            'bbcode_create',
            'bbcode_destroy',
            'bbcode_parse',
            'bbcode_set_arg_parser',
            'bbcode_set_flags',
            'bcompiler_read',
            'bcompiler_write_class',
            'bcompiler_write_constant',
            'bcompiler_write_exe_footer',
            'bcompiler_write_file',
            'bcompiler_write_footer',
            'bcompiler_write_function',
            'bcompiler_write_functions_from_file',
            'bcompiler_write_header',
            'bcompiler_write_included_filename',
            'bzclose',
            'bzerrno',
            'bzerror',
            'bzerrstr',
            'bzflush',
            'bzopen',
            'bzread',
            'bzwrite',
            'cairo_surface_write_to_png',
            'closedir',
            'copy',
            'crack_closedict',
            'crack_opendict',
            'cubrid_bind',
            'cubrid_close_prepare',
            'cubrid_close_request',
            'cubrid_col_get',
            'cubrid_col_size',
            'cubrid_column_names',
            'cubrid_column_types',
            'cubrid_commit',
            'cubrid_connect',
            'cubrid_connect_with_url',
            'cubrid_current_oid',
            'cubrid_db_parameter',
            'cubrid_disconnect',
            'cubrid_drop',
            'cubrid_fetch',
            'cubrid_free_result',
            'cubrid_get',
            'cubrid_get_autocommit',
            'cubrid_get_charset',
            'cubrid_get_class_name',
            'cubrid_get_db_parameter',
            'cubrid_get_query_timeout',
            'cubrid_get_server_info',
            'cubrid_insert_id',
            'cubrid_is_instance',
            'cubrid_lob2_bind',
            'cubrid_lob2_close',
            'cubrid_lob2_export',
            'cubrid_lob2_import',
            'cubrid_lob2_new',
            'cubrid_lob2_read',
            'cubrid_lob2_seek',
            'cubrid_lob2_seek64',
            'cubrid_lob2_size',
            'cubrid_lob2_size64',
            'cubrid_lob2_tell',
            'cubrid_lob2_tell64',
            'cubrid_lob2_write',
            'cubrid_lob_export',
            'cubrid_lob_get',
            'cubrid_lob_send',
            'cubrid_lob_size',
            'cubrid_lock_read',
            'cubrid_lock_write',
            'cubrid_move_cursor',
            'cubrid_next_result',
            'cubrid_num_cols',
            'cubrid_num_rows',
            'cubrid_pconnect',
            'cubrid_pconnect_with_url',
            'cubrid_prepare',
            'cubrid_put',
            'cubrid_query',
            'cubrid_rollback',
            'cubrid_schema',
            'cubrid_seq_add',
            'cubrid_seq_drop',
            'cubrid_seq_insert',
            'cubrid_seq_put',
            'cubrid_set_add',
            'cubrid_set_autocommit',
            'cubrid_set_db_parameter',
            'cubrid_set_drop',
            'cubrid_set_query_timeout',
            'cubrid_unbuffered_query',
            'curl_close',
            'curl_copy_handle',
            'curl_errno',
            'curl_error',
            'curl_escape',
            'curl_exec',
            'curl_getinfo',
            'curl_multi_add_handle',
            'curl_multi_close',
            'curl_multi_errno',
            'curl_multi_exec',
            'curl_multi_getcontent',
            'curl_multi_info_read',
            'curl_multi_remove_handle',
            'curl_multi_select',
            'curl_multi_setopt',
            'curl_pause',
            'curl_reset',
            'curl_setopt',
            'curl_setopt_array',
            'curl_share_close',
            'curl_share_errno',
            'curl_share_init',
            'curl_share_setopt',
            'curl_unescape',
            'cyrus_authenticate',
            'cyrus_bind',
            'cyrus_close',
            'cyrus_connect',
            'cyrus_query',
            'cyrus_unbind',
            'db2_autocommit',
            'db2_bind_param',
            'db2_client_info',
            'db2_close',
            'db2_column_privileges',
            'db2_columns',
            'db2_commit',
            'db2_conn_error',
            'db2_conn_errormsg',
            'db2_connect',
            'db2_cursor_type',
            'db2_exec',
            'db2_execute',
            'db2_fetch_array',
            'db2_fetch_assoc',
            'db2_fetch_both',
            'db2_fetch_object',
            'db2_fetch_row',
            'db2_field_display_size',
            'db2_field_name',
            'db2_field_num',
            'db2_field_precision',
            'db2_field_scale',
            'db2_field_type',
            'db2_field_width',
            'db2_foreign_keys',
            'db2_free_result',
            'db2_free_stmt',
            'db2_get_option',
            'db2_last_insert_id',
            'db2_lob_read',
            'db2_next_result',
            'db2_num_fields',
            'db2_num_rows',
            'db2_pclose',
            'db2_pconnect',
            'db2_prepare',
            'db2_primary_keys',
            'db2_procedure_columns',
            'db2_procedures',
            'db2_result',
            'db2_rollback',
            'db2_server_info',
            'db2_set_option',
            'db2_special_columns',
            'db2_statistics',
            'db2_stmt_error',
            'db2_stmt_errormsg',
            'db2_table_privileges',
            'db2_tables',
            'dba_close',
            'dba_delete',
            'dba_exists',
            'dba_fetch',
            'dba_firstkey',
            'dba_insert',
            'dba_nextkey',
            'dba_open',
            'dba_optimize',
            'dba_popen',
            'dba_replace',
            'dba_sync',
            'dbplus_add',
            'dbplus_aql',
            'dbplus_close',
            'dbplus_curr',
            'dbplus_find',
            'dbplus_first',
            'dbplus_flush',
            'dbplus_freelock',
            'dbplus_freerlocks',
            'dbplus_getlock',
            'dbplus_getunique',
            'dbplus_info',
            'dbplus_last',
            'dbplus_lockrel',
            'dbplus_next',
            'dbplus_open',
            'dbplus_prev',
            'dbplus_rchperm',
            'dbplus_rcreate',
            'dbplus_rcrtexact',
            'dbplus_rcrtlike',
            'dbplus_restorepos',
            'dbplus_rkeys',
            'dbplus_ropen',
            'dbplus_rquery',
            'dbplus_rrename',
            'dbplus_rsecindex',
            'dbplus_runlink',
            'dbplus_rzap',
            'dbplus_savepos',
            'dbplus_setindex',
            'dbplus_setindexbynumber',
            'dbplus_sql',
            'dbplus_tremove',
            'dbplus_undo',
            'dbplus_undoprepare',
            'dbplus_unlockrel',
            'dbplus_unselect',
            'dbplus_update',
            'dbplus_xlockrel',
            'dbplus_xunlockrel',
            'deflate_add',
            'dio_close',
            'dio_fcntl',
            'dio_open',
            'dio_read',
            'dio_seek',
            'dio_stat',
            'dio_tcsetattr',
            'dio_truncate',
            'dio_write',
            'dir',
            'eio_busy',
            'eio_cancel',
            'eio_chmod',
            'eio_chown',
            'eio_close',
            'eio_custom',
            'eio_dup2',
            'eio_fallocate',
            'eio_fchmod',
            'eio_fchown',
            'eio_fdatasync',
            'eio_fstat',
            'eio_fstatvfs',
            'eio_fsync',
            'eio_ftruncate',
            'eio_futime',
            'eio_get_last_error',
            'eio_grp',
            'eio_grp_add',
            'eio_grp_cancel',
            'eio_grp_limit',
            'eio_link',
            'eio_lstat',
            'eio_mkdir',
            'eio_mknod',
            'eio_nop',
            'eio_open',
            'eio_read',
            'eio_readahead',
            'eio_readdir',
            'eio_readlink',
            'eio_realpath',
            'eio_rename',
            'eio_rmdir',
            'eio_seek',
            'eio_sendfile',
            'eio_stat',
            'eio_statvfs',
            'eio_symlink',
            'eio_sync',
            'eio_sync_file_range',
            'eio_syncfs',
            'eio_truncate',
            'eio_unlink',
            'eio_utime',
            'eio_write',
            'enchant_broker_describe',
            'enchant_broker_dict_exists',
            'enchant_broker_free',
            'enchant_broker_free_dict',
            'enchant_broker_get_dict_path',
            'enchant_broker_get_error',
            'enchant_broker_init',
            'enchant_broker_list_dicts',
            'enchant_broker_request_dict',
            'enchant_broker_request_pwl_dict',
            'enchant_broker_set_dict_path',
            'enchant_broker_set_ordering',
            'enchant_dict_add_to_personal',
            'enchant_dict_add_to_session',
            'enchant_dict_check',
            'enchant_dict_describe',
            'enchant_dict_get_error',
            'enchant_dict_is_in_session',
            'enchant_dict_quick_check',
            'enchant_dict_store_replacement',
            'enchant_dict_suggest',
            'event_add',
            'event_base_free',
            'event_base_loop',
            'event_base_loopbreak',
            'event_base_loopexit',
            'event_base_new',
            'event_base_priority_init',
            'event_base_reinit',
            'event_base_set',
            'event_buffer_base_set',
            'event_buffer_disable',
            'event_buffer_enable',
            'event_buffer_fd_set',
            'event_buffer_free',
            'event_buffer_new',
            'event_buffer_priority_set',
            'event_buffer_read',
            'event_buffer_set_callback',
            'event_buffer_timeout_set',
            'event_buffer_watermark_set',
            'event_buffer_write',
            'event_del',
            'event_free',
            'event_new',
            'event_priority_set',
            'event_set',
            'event_timer_add',
            'event_timer_del',
            'event_timer_pending',
            'event_timer_set',
            'expect_expectl',
            'expect_popen',
            'fam_cancel_monitor',
            'fam_close',
            'fam_monitor_collection',
            'fam_monitor_directory',
            'fam_monitor_file',
            'fam_next_event',
            'fam_open',
            'fam_pending',
            'fam_resume_monitor',
            'fam_suspend_monitor',
            'fann_cascadetrain_on_data',
            'fann_cascadetrain_on_file',
            'fann_clear_scaling_params',
            'fann_copy',
            'fann_create_from_file',
            'fann_create_shortcut_array',
            'fann_create_standard',
            'fann_create_standard_array',
            'fann_create_train',
            'fann_create_train_from_callback',
            'fann_descale_input',
            'fann_descale_output',
            'fann_descale_train',
            'fann_destroy',
            'fann_destroy_train',
            'fann_duplicate_train_data',
            'fann_get_MSE',
            'fann_get_activation_function',
            'fann_get_activation_steepness',
            'fann_get_bias_array',
            'fann_get_bit_fail',
            'fann_get_bit_fail_limit',
            'fann_get_cascade_activation_functions',
            'fann_get_cascade_activation_functions_count',
            'fann_get_cascade_activation_steepnesses',
            'fann_get_cascade_activation_steepnesses_count',
            'fann_get_cascade_candidate_change_fraction',
            'fann_get_cascade_candidate_limit',
            'fann_get_cascade_candidate_stagnation_epochs',
            'fann_get_cascade_max_cand_epochs',
            'fann_get_cascade_max_out_epochs',
            'fann_get_cascade_min_cand_epochs',
            'fann_get_cascade_min_out_epochs',
            'fann_get_cascade_num_candidate_groups',
            'fann_get_cascade_num_candidates',
            'fann_get_cascade_output_change_fraction',
            'fann_get_cascade_output_stagnation_epochs',
            'fann_get_cascade_weight_multiplier',
            'fann_get_connection_array',
            'fann_get_connection_rate',
            'fann_get_errno',
            'fann_get_errstr',
            'fann_get_layer_array',
            'fann_get_learning_momentum',
            'fann_get_learning_rate',
            'fann_get_network_type',
            'fann_get_num_input',
            'fann_get_num_layers',
            'fann_get_num_output',
            'fann_get_quickprop_decay',
            'fann_get_quickprop_mu',
            'fann_get_rprop_decrease_factor',
            'fann_get_rprop_delta_max',
            'fann_get_rprop_delta_min',
            'fann_get_rprop_delta_zero',
            'fann_get_rprop_increase_factor',
            'fann_get_sarprop_step_error_shift',
            'fann_get_sarprop_step_error_threshold_factor',
            'fann_get_sarprop_temperature',
            'fann_get_sarprop_weight_decay_shift',
            'fann_get_total_connections',
            'fann_get_total_neurons',
            'fann_get_train_error_function',
            'fann_get_train_stop_function',
            'fann_get_training_algorithm',
            'fann_init_weights',
            'fann_length_train_data',
            'fann_merge_train_data',
            'fann_num_input_train_data',
            'fann_num_output_train_data',
            'fann_randomize_weights',
            'fann_read_train_from_file',
            'fann_reset_errno',
            'fann_reset_errstr',
            'fann_run',
            'fann_save',
            'fann_save_train',
            'fann_scale_input',
            'fann_scale_input_train_data',
            'fann_scale_output',
            'fann_scale_output_train_data',
            'fann_scale_train',
            'fann_scale_train_data',
            'fann_set_activation_function',
            'fann_set_activation_function_hidden',
            'fann_set_activation_function_layer',
            'fann_set_activation_function_output',
            'fann_set_activation_steepness',
            'fann_set_activation_steepness_hidden',
            'fann_set_activation_steepness_layer',
            'fann_set_activation_steepness_output',
            'fann_set_bit_fail_limit',
            'fann_set_callback',
            'fann_set_cascade_activation_functions',
            'fann_set_cascade_activation_steepnesses',
            'fann_set_cascade_candidate_change_fraction',
            'fann_set_cascade_candidate_limit',
            'fann_set_cascade_candidate_stagnation_epochs',
            'fann_set_cascade_max_cand_epochs',
            'fann_set_cascade_max_out_epochs',
            'fann_set_cascade_min_cand_epochs',
            'fann_set_cascade_min_out_epochs',
            'fann_set_cascade_num_candidate_groups',
            'fann_set_cascade_output_change_fraction',
            'fann_set_cascade_output_stagnation_epochs',
            'fann_set_cascade_weight_multiplier',
            'fann_set_error_log',
            'fann_set_input_scaling_params',
            'fann_set_learning_momentum',
            'fann_set_learning_rate',
            'fann_set_output_scaling_params',
            'fann_set_quickprop_decay',
            'fann_set_quickprop_mu',
            'fann_set_rprop_decrease_factor',
            'fann_set_rprop_delta_max',
            'fann_set_rprop_delta_min',
            'fann_set_rprop_delta_zero',
            'fann_set_rprop_increase_factor',
            'fann_set_sarprop_step_error_shift',
            'fann_set_sarprop_step_error_threshold_factor',
            'fann_set_sarprop_temperature',
            'fann_set_sarprop_weight_decay_shift',
            'fann_set_scaling_params',
            'fann_set_train_error_function',
            'fann_set_train_stop_function',
            'fann_set_training_algorithm',
            'fann_set_weight',
            'fann_set_weight_array',
            'fann_shuffle_train_data',
            'fann_subset_train_data',
            'fann_test',
            'fann_test_data',
            'fann_train',
            'fann_train_epoch',
            'fann_train_on_data',
            'fann_train_on_file',
            'fbsql_affected_rows',
            'fbsql_autocommit',
            'fbsql_blob_size',
            'fbsql_change_user',
            'fbsql_clob_size',
            'fbsql_close',
            'fbsql_commit',
            'fbsql_connect',
            'fbsql_create_blob',
            'fbsql_create_clob',
            'fbsql_create_db',
            'fbsql_data_seek',
            'fbsql_database',
            'fbsql_database_password',
            'fbsql_db_query',
            'fbsql_db_status',
            'fbsql_drop_db',
            'fbsql_errno',
            'fbsql_error',
            'fbsql_fetch_array',
            'fbsql_fetch_assoc',
            'fbsql_fetch_field',
            'fbsql_fetch_lengths',
            'fbsql_fetch_object',
            'fbsql_fetch_row',
            'fbsql_field_flags',
            'fbsql_field_len',
            'fbsql_field_name',
            'fbsql_field_seek',
            'fbsql_field_table',
            'fbsql_field_type',
            'fbsql_free_result',
            'fbsql_get_autostart_info',
            'fbsql_hostname',
            'fbsql_insert_id',
            'fbsql_list_dbs',
            'fbsql_list_fields',
            'fbsql_list_tables',
            'fbsql_next_result',
            'fbsql_num_fields',
            'fbsql_num_rows',
            'fbsql_password',
            'fbsql_pconnect',
            'fbsql_query',
            'fbsql_read_blob',
            'fbsql_read_clob',
            'fbsql_result',
            'fbsql_rollback',
            'fbsql_rows_fetched',
            'fbsql_select_db',
            'fbsql_set_characterset',
            'fbsql_set_lob_mode',
            'fbsql_set_password',
            'fbsql_set_transaction',
            'fbsql_start_db',
            'fbsql_stop_db',
            'fbsql_table_name',
            'fbsql_username',
            'fclose',
            'fdf_add_doc_javascript',
            'fdf_add_template',
            'fdf_close',
            'fdf_create',
            'fdf_enum_values',
            'fdf_get_ap',
            'fdf_get_attachment',
            'fdf_get_encoding',
            'fdf_get_file',
            'fdf_get_flags',
            'fdf_get_opt',
            'fdf_get_status',
            'fdf_get_value',
            'fdf_get_version',
            'fdf_next_field_name',
            'fdf_open',
            'fdf_open_string',
            'fdf_remove_item',
            'fdf_save',
            'fdf_save_string',
            'fdf_set_ap',
            'fdf_set_encoding',
            'fdf_set_file',
            'fdf_set_flags',
            'fdf_set_javascript_action',
            'fdf_set_on_import_javascript',
            'fdf_set_opt',
            'fdf_set_status',
            'fdf_set_submit_form_action',
            'fdf_set_target_frame',
            'fdf_set_value',
            'fdf_set_version',
            'feof',
            'fflush',
            'ffmpeg_frame::__construct',
            'ffmpeg_frame::toGDImage',
            'fgetc',
            'fgetcsv',
            'fgets',
            'fgetss',
            'file',
            'file_get_contents',
            'file_put_contents',
            'finfo::buffer',
            'finfo::file',
            'finfo_buffer',
            'finfo_close',
            'finfo_file',
            'finfo_open',
            'finfo_set_flags',
            'flock',
            'fopen',
            'fpassthru',
            'fprintf',
            'fputcsv',
            'fputs',
            'fread',
            'fscanf',
            'fseek',
            'fstat',
            'ftell',
            'ftp_alloc',
            'ftp_append',
            'ftp_cdup',
            'ftp_chdir',
            'ftp_chmod',
            'ftp_close',
            'ftp_delete',
            'ftp_exec',
            'ftp_fget',
            'ftp_fput',
            'ftp_get',
            'ftp_get_option',
            'ftp_login',
            'ftp_mdtm',
            'ftp_mkdir',
            'ftp_mlsd',
            'ftp_nb_continue',
            'ftp_nb_fget',
            'ftp_nb_fput',
            'ftp_nb_get',
            'ftp_nb_put',
            'ftp_nlist',
            'ftp_pasv',
            'ftp_put',
            'ftp_pwd',
            'ftp_quit',
            'ftp_raw',
            'ftp_rawlist',
            'ftp_rename',
            'ftp_rmdir',
            'ftp_set_option',
            'ftp_site',
            'ftp_size',
            'ftp_systype',
            'ftruncate',
            'fwrite',
            'get_resource_type',
            'gmp_div',
            'gnupg::init',
            'gnupg_adddecryptkey',
            'gnupg_addencryptkey',
            'gnupg_addsignkey',
            'gnupg_cleardecryptkeys',
            'gnupg_clearencryptkeys',
            'gnupg_clearsignkeys',
            'gnupg_decrypt',
            'gnupg_decryptverify',
            'gnupg_encrypt',
            'gnupg_encryptsign',
            'gnupg_export',
            'gnupg_geterror',
            'gnupg_getprotocol',
            'gnupg_import',
            'gnupg_init',
            'gnupg_keyinfo',
            'gnupg_setarmor',
            'gnupg_seterrormode',
            'gnupg_setsignmode',
            'gnupg_sign',
            'gnupg_verify',
            'gupnp_context_get_host_ip',
            'gupnp_context_get_port',
            'gupnp_context_get_subscription_timeout',
            'gupnp_context_host_path',
            'gupnp_context_new',
            'gupnp_context_set_subscription_timeout',
            'gupnp_context_timeout_add',
            'gupnp_context_unhost_path',
            'gupnp_control_point_browse_start',
            'gupnp_control_point_browse_stop',
            'gupnp_control_point_callback_set',
            'gupnp_control_point_new',
            'gupnp_device_action_callback_set',
            'gupnp_device_info_get',
            'gupnp_device_info_get_service',
            'gupnp_root_device_get_available',
            'gupnp_root_device_get_relative_location',
            'gupnp_root_device_new',
            'gupnp_root_device_set_available',
            'gupnp_root_device_start',
            'gupnp_root_device_stop',
            'gupnp_service_action_get',
            'gupnp_service_action_return',
            'gupnp_service_action_return_error',
            'gupnp_service_action_set',
            'gupnp_service_freeze_notify',
            'gupnp_service_info_get',
            'gupnp_service_info_get_introspection',
            'gupnp_service_introspection_get_state_variable',
            'gupnp_service_notify',
            'gupnp_service_proxy_action_get',
            'gupnp_service_proxy_action_set',
            'gupnp_service_proxy_add_notify',
            'gupnp_service_proxy_callback_set',
            'gupnp_service_proxy_get_subscribed',
            'gupnp_service_proxy_remove_notify',
            'gupnp_service_proxy_send_action',
            'gupnp_service_proxy_set_subscribed',
            'gupnp_service_thaw_notify',
            'gzclose',
            'gzeof',
            'gzgetc',
            'gzgets',
            'gzgetss',
            'gzpassthru',
            'gzputs',
            'gzread',
            'gzrewind',
            'gzseek',
            'gztell',
            'gzwrite',
            'hash_update_stream',
            'http\Env\Response::send',
            'http_get_request_body_stream',
            'ibase_add_user',
            'ibase_affected_rows',
            'ibase_backup',
            'ibase_blob_add',
            'ibase_blob_cancel',
            'ibase_blob_close',
            'ibase_blob_create',
            'ibase_blob_get',
            'ibase_blob_open',
            'ibase_close',
            'ibase_commit',
            'ibase_commit_ret',
            'ibase_connect',
            'ibase_db_info',
            'ibase_delete_user',
            'ibase_drop_db',
            'ibase_execute',
            'ibase_fetch_assoc',
            'ibase_fetch_object',
            'ibase_fetch_row',
            'ibase_field_info',
            'ibase_free_event_handler',
            'ibase_free_query',
            'ibase_free_result',
            'ibase_gen_id',
            'ibase_maintain_db',
            'ibase_modify_user',
            'ibase_name_result',
            'ibase_num_fields',
            'ibase_num_params',
            'ibase_param_info',
            'ibase_pconnect',
            'ibase_prepare',
            'ibase_query',
            'ibase_restore',
            'ibase_rollback',
            'ibase_rollback_ret',
            'ibase_server_info',
            'ibase_service_attach',
            'ibase_service_detach',
            'ibase_set_event_handler',
            'ibase_trans',
            'ifx_affected_rows',
            'ifx_close',
            'ifx_connect',
            'ifx_do',
            'ifx_error',
            'ifx_fetch_row',
            'ifx_fieldproperties',
            'ifx_fieldtypes',
            'ifx_free_result',
            'ifx_getsqlca',
            'ifx_htmltbl_result',
            'ifx_num_fields',
            'ifx_num_rows',
            'ifx_pconnect',
            'ifx_prepare',
            'ifx_query',
            'image2wbmp',
            'imageaffine',
            'imagealphablending',
            'imageantialias',
            'imagearc',
            'imagebmp',
            'imagechar',
            'imagecharup',
            'imagecolorallocate',
            'imagecolorallocatealpha',
            'imagecolorat',
            'imagecolorclosest',
            'imagecolorclosestalpha',
            'imagecolorclosesthwb',
            'imagecolordeallocate',
            'imagecolorexact',
            'imagecolorexactalpha',
            'imagecolormatch',
            'imagecolorresolve',
            'imagecolorresolvealpha',
            'imagecolorset',
            'imagecolorsforindex',
            'imagecolorstotal',
            'imagecolortransparent',
            'imageconvolution',
            'imagecopy',
            'imagecopymerge',
            'imagecopymergegray',
            'imagecopyresampled',
            'imagecopyresized',
            'imagecrop',
            'imagecropauto',
            'imagedashedline',
            'imagedestroy',
            'imageellipse',
            'imagefill',
            'imagefilledarc',
            'imagefilledellipse',
            'imagefilledpolygon',
            'imagefilledrectangle',
            'imagefilltoborder',
            'imagefilter',
            'imageflip',
            'imagefttext',
            'imagegammacorrect',
            'imagegd',
            'imagegd2',
            'imagegetclip',
            'imagegif',
            'imagegrabscreen',
            'imagegrabwindow',
            'imageinterlace',
            'imageistruecolor',
            'imagejpeg',
            'imagelayereffect',
            'imageline',
            'imageopenpolygon',
            'imagepalettecopy',
            'imagepalettetotruecolor',
            'imagepng',
            'imagepolygon',
            'imagepsencodefont',
            'imagepsextendfont',
            'imagepsfreefont',
            'imagepsloadfont',
            'imagepsslantfont',
            'imagepstext',
            'imagerectangle',
            'imageresolution',
            'imagerotate',
            'imagesavealpha',
            'imagescale',
            'imagesetbrush',
            'imagesetclip',
            'imagesetinterpolation',
            'imagesetpixel',
            'imagesetstyle',
            'imagesetthickness',
            'imagesettile',
            'imagestring',
            'imagestringup',
            'imagesx',
            'imagesy',
            'imagetruecolortopalette',
            'imagettftext',
            'imagewbmp',
            'imagewebp',
            'imagexbm',
            'imap_append',
            'imap_body',
            'imap_bodystruct',
            'imap_check',
            'imap_clearflag_full',
            'imap_close',
            'imap_create',
            'imap_createmailbox',
            'imap_delete',
            'imap_deletemailbox',
            'imap_expunge',
            'imap_fetch_overview',
            'imap_fetchbody',
            'imap_fetchheader',
            'imap_fetchmime',
            'imap_fetchstructure',
            'imap_fetchtext',
            'imap_gc',
            'imap_get_quota',
            'imap_get_quotaroot',
            'imap_getacl',
            'imap_getmailboxes',
            'imap_getsubscribed',
            'imap_header',
            'imap_headerinfo',
            'imap_headers',
            'imap_list',
            'imap_listmailbox',
            'imap_listscan',
            'imap_listsubscribed',
            'imap_lsub',
            'imap_mail_copy',
            'imap_mail_move',
            'imap_mailboxmsginfo',
            'imap_msgno',
            'imap_num_msg',
            'imap_num_recent',
            'imap_ping',
            'imap_rename',
            'imap_renamemailbox',
            'imap_reopen',
            'imap_savebody',
            'imap_scan',
            'imap_scanmailbox',
            'imap_search',
            'imap_set_quota',
            'imap_setacl',
            'imap_setflag_full',
            'imap_sort',
            'imap_status',
            'imap_subscribe',
            'imap_thread',
            'imap_uid',
            'imap_undelete',
            'imap_unsubscribe',
            'inflate_add',
            'inflate_get_read_len',
            'inflate_get_status',
            'ingres_autocommit',
            'ingres_autocommit_state',
            'ingres_charset',
            'ingres_close',
            'ingres_commit',
            'ingres_connect',
            'ingres_cursor',
            'ingres_errno',
            'ingres_error',
            'ingres_errsqlstate',
            'ingres_escape_string',
            'ingres_execute',
            'ingres_fetch_array',
            'ingres_fetch_assoc',
            'ingres_fetch_object',
            'ingres_fetch_proc_return',
            'ingres_fetch_row',
            'ingres_field_length',
            'ingres_field_name',
            'ingres_field_nullable',
            'ingres_field_precision',
            'ingres_field_scale',
            'ingres_field_type',
            'ingres_free_result',
            'ingres_next_error',
            'ingres_num_fields',
            'ingres_num_rows',
            'ingres_pconnect',
            'ingres_prepare',
            'ingres_query',
            'ingres_result_seek',
            'ingres_rollback',
            'ingres_set_environment',
            'ingres_unbuffered_query',
            'inotify_add_watch',
            'inotify_init',
            'inotify_queue_len',
            'inotify_read',
            'inotify_rm_watch',
            'kadm5_chpass_principal',
            'kadm5_create_principal',
            'kadm5_delete_principal',
            'kadm5_destroy',
            'kadm5_flush',
            'kadm5_get_policies',
            'kadm5_get_principal',
            'kadm5_get_principals',
            'kadm5_init_with_password',
            'kadm5_modify_principal',
            'ldap_add',
            'ldap_bind',
            'ldap_close',
            'ldap_compare',
            'ldap_control_paged_result',
            'ldap_control_paged_result_response',
            'ldap_count_entries',
            'ldap_delete',
            'ldap_errno',
            'ldap_error',
            'ldap_exop',
            'ldap_exop_passwd',
            'ldap_exop_refresh',
            'ldap_exop_whoami',
            'ldap_first_attribute',
            'ldap_first_entry',
            'ldap_first_reference',
            'ldap_free_result',
            'ldap_get_attributes',
            'ldap_get_dn',
            'ldap_get_entries',
            'ldap_get_option',
            'ldap_get_values',
            'ldap_get_values_len',
            'ldap_mod_add',
            'ldap_mod_del',
            'ldap_mod_replace',
            'ldap_modify',
            'ldap_modify_batch',
            'ldap_next_attribute',
            'ldap_next_entry',
            'ldap_next_reference',
            'ldap_parse_exop',
            'ldap_parse_reference',
            'ldap_parse_result',
            'ldap_rename',
            'ldap_sasl_bind',
            'ldap_set_option',
            'ldap_set_rebind_proc',
            'ldap_sort',
            'ldap_start_tls',
            'ldap_unbind',
            'libxml_set_streams_context',
            'm_checkstatus',
            'm_completeauthorizations',
            'm_connect',
            'm_connectionerror',
            'm_deletetrans',
            'm_destroyconn',
            'm_getcell',
            'm_getcellbynum',
            'm_getcommadelimited',
            'm_getheader',
            'm_initconn',
            'm_iscommadelimited',
            'm_maxconntimeout',
            'm_monitor',
            'm_numcolumns',
            'm_numrows',
            'm_parsecommadelimited',
            'm_responsekeys',
            'm_responseparam',
            'm_returnstatus',
            'm_setblocking',
            'm_setdropfile',
            'm_setip',
            'm_setssl',
            'm_setssl_cafile',
            'm_setssl_files',
            'm_settimeout',
            'm_transactionssent',
            'm_transinqueue',
            'm_transkeyval',
            'm_transnew',
            'm_transsend',
            'm_validateidentifier',
            'm_verifyconnection',
            'm_verifysslcert',
            'mailparse_determine_best_xfer_encoding',
            'mailparse_msg_create',
            'mailparse_msg_extract_part',
            'mailparse_msg_extract_part_file',
            'mailparse_msg_extract_whole_part_file',
            'mailparse_msg_free',
            'mailparse_msg_get_part',
            'mailparse_msg_get_part_data',
            'mailparse_msg_get_structure',
            'mailparse_msg_parse',
            'mailparse_msg_parse_file',
            'mailparse_stream_encode',
            'mailparse_uudecode_all',
            'maxdb::use_result',
            'maxdb_affected_rows',
            'maxdb_connect',
            'maxdb_disable_rpl_parse',
            'maxdb_dump_debug_info',
            'maxdb_embedded_connect',
            'maxdb_enable_reads_from_master',
            'maxdb_enable_rpl_parse',
            'maxdb_errno',
            'maxdb_error',
            'maxdb_fetch_lengths',
            'maxdb_field_tell',
            'maxdb_get_host_info',
            'maxdb_get_proto_info',
            'maxdb_get_server_info',
            'maxdb_get_server_version',
            'maxdb_info',
            'maxdb_init',
            'maxdb_insert_id',
            'maxdb_master_query',
            'maxdb_more_results',
            'maxdb_next_result',
            'maxdb_num_fields',
            'maxdb_num_rows',
            'maxdb_rpl_parse_enabled',
            'maxdb_rpl_probe',
            'maxdb_select_db',
            'maxdb_sqlstate',
            'maxdb_stmt::result_metadata',
            'maxdb_stmt_affected_rows',
            'maxdb_stmt_errno',
            'maxdb_stmt_error',
            'maxdb_stmt_num_rows',
            'maxdb_stmt_param_count',
            'maxdb_stmt_result_metadata',
            'maxdb_stmt_sqlstate',
            'maxdb_thread_id',
            'maxdb_use_result',
            'maxdb_warning_count',
            'mcrypt_enc_get_algorithms_name',
            'mcrypt_enc_get_block_size',
            'mcrypt_enc_get_iv_size',
            'mcrypt_enc_get_key_size',
            'mcrypt_enc_get_modes_name',
            'mcrypt_enc_get_supported_key_sizes',
            'mcrypt_enc_is_block_algorithm',
            'mcrypt_enc_is_block_algorithm_mode',
            'mcrypt_enc_is_block_mode',
            'mcrypt_enc_self_test',
            'mcrypt_generic',
            'mcrypt_generic_deinit',
            'mcrypt_generic_end',
            'mcrypt_generic_init',
            'mcrypt_module_close',
            'mcrypt_module_open',
            'mdecrypt_generic',
            'mkdir',
            'mqseries_back',
            'mqseries_begin',
            'mqseries_close',
            'mqseries_cmit',
            'mqseries_conn',
            'mqseries_connx',
            'mqseries_disc',
            'mqseries_get',
            'mqseries_inq',
            'mqseries_open',
            'mqseries_put',
            'mqseries_put1',
            'mqseries_set',
            'msg_get_queue',
            'msg_receive',
            'msg_remove_queue',
            'msg_send',
            'msg_set_queue',
            'msg_stat_queue',
            'msql_affected_rows',
            'msql_close',
            'msql_connect',
            'msql_create_db',
            'msql_data_seek',
            'msql_db_query',
            'msql_drop_db',
            'msql_fetch_array',
            'msql_fetch_field',
            'msql_fetch_object',
            'msql_fetch_row',
            'msql_field_flags',
            'msql_field_len',
            'msql_field_name',
            'msql_field_seek',
            'msql_field_table',
            'msql_field_type',
            'msql_free_result',
            'msql_list_dbs',
            'msql_list_fields',
            'msql_list_tables',
            'msql_num_fields',
            'msql_num_rows',
            'msql_pconnect',
            'msql_query',
            'msql_result',
            'msql_select_db',
            'mssql_bind',
            'mssql_close',
            'mssql_connect',
            'mssql_data_seek',
            'mssql_execute',
            'mssql_fetch_array',
            'mssql_fetch_assoc',
            'mssql_fetch_batch',
            'mssql_fetch_field',
            'mssql_fetch_object',
            'mssql_fetch_row',
            'mssql_field_length',
            'mssql_field_name',
            'mssql_field_seek',
            'mssql_field_type',
            'mssql_free_result',
            'mssql_free_statement',
            'mssql_init',
            'mssql_next_result',
            'mssql_num_fields',
            'mssql_num_rows',
            'mssql_pconnect',
            'mssql_query',
            'mssql_result',
            'mssql_rows_affected',
            'mssql_select_db',
            'mysql_affected_rows',
            'mysql_client_encoding',
            'mysql_close',
            'mysql_connect',
            'mysql_create_db',
            'mysql_data_seek',
            'mysql_db_name',
            'mysql_db_query',
            'mysql_drop_db',
            'mysql_errno',
            'mysql_error',
            'mysql_fetch_array',
            'mysql_fetch_assoc',
            'mysql_fetch_field',
            'mysql_fetch_lengths',
            'mysql_fetch_object',
            'mysql_fetch_row',
            'mysql_field_flags',
            'mysql_field_len',
            'mysql_field_name',
            'mysql_field_seek',
            'mysql_field_table',
            'mysql_field_type',
            'mysql_free_result',
            'mysql_get_host_info',
            'mysql_get_proto_info',
            'mysql_get_server_info',
            'mysql_info',
            'mysql_insert_id',
            'mysql_list_dbs',
            'mysql_list_fields',
            'mysql_list_processes',
            'mysql_list_tables',
            'mysql_num_fields',
            'mysql_num_rows',
            'mysql_pconnect',
            'mysql_ping',
            'mysql_query',
            'mysql_real_escape_string',
            'mysql_result',
            'mysql_select_db',
            'mysql_set_charset',
            'mysql_stat',
            'mysql_tablename',
            'mysql_thread_id',
            'mysql_unbuffered_query',
            'mysqlnd_uh_convert_to_mysqlnd',
            'ncurses_bottom_panel',
            'ncurses_del_panel',
            'ncurses_delwin',
            'ncurses_getmaxyx',
            'ncurses_getyx',
            'ncurses_hide_panel',
            'ncurses_keypad',
            'ncurses_meta',
            'ncurses_move_panel',
            'ncurses_mvwaddstr',
            'ncurses_new_panel',
            'ncurses_newpad',
            'ncurses_newwin',
            'ncurses_panel_above',
            'ncurses_panel_below',
            'ncurses_panel_window',
            'ncurses_pnoutrefresh',
            'ncurses_prefresh',
            'ncurses_replace_panel',
            'ncurses_show_panel',
            'ncurses_top_panel',
            'ncurses_waddch',
            'ncurses_waddstr',
            'ncurses_wattroff',
            'ncurses_wattron',
            'ncurses_wattrset',
            'ncurses_wborder',
            'ncurses_wclear',
            'ncurses_wcolor_set',
            'ncurses_werase',
            'ncurses_wgetch',
            'ncurses_whline',
            'ncurses_wmouse_trafo',
            'ncurses_wmove',
            'ncurses_wnoutrefresh',
            'ncurses_wrefresh',
            'ncurses_wstandend',
            'ncurses_wstandout',
            'ncurses_wvline',
            'newt_button',
            'newt_button_bar',
            'newt_checkbox',
            'newt_checkbox_get_value',
            'newt_checkbox_set_flags',
            'newt_checkbox_set_value',
            'newt_checkbox_tree',
            'newt_checkbox_tree_add_item',
            'newt_checkbox_tree_find_item',
            'newt_checkbox_tree_get_current',
            'newt_checkbox_tree_get_entry_value',
            'newt_checkbox_tree_get_multi_selection',
            'newt_checkbox_tree_get_selection',
            'newt_checkbox_tree_multi',
            'newt_checkbox_tree_set_current',
            'newt_checkbox_tree_set_entry',
            'newt_checkbox_tree_set_entry_value',
            'newt_checkbox_tree_set_width',
            'newt_compact_button',
            'newt_component_add_callback',
            'newt_component_takes_focus',
            'newt_create_grid',
            'newt_draw_form',
            'newt_entry',
            'newt_entry_get_value',
            'newt_entry_set',
            'newt_entry_set_filter',
            'newt_entry_set_flags',
            'newt_form',
            'newt_form_add_component',
            'newt_form_add_components',
            'newt_form_add_hot_key',
            'newt_form_destroy',
            'newt_form_get_current',
            'newt_form_run',
            'newt_form_set_background',
            'newt_form_set_height',
            'newt_form_set_size',
            'newt_form_set_timer',
            'newt_form_set_width',
            'newt_form_watch_fd',
            'newt_grid_add_components_to_form',
            'newt_grid_basic_window',
            'newt_grid_free',
            'newt_grid_get_size',
            'newt_grid_h_close_stacked',
            'newt_grid_h_stacked',
            'newt_grid_place',
            'newt_grid_set_field',
            'newt_grid_simple_window',
            'newt_grid_v_close_stacked',
            'newt_grid_v_stacked',
            'newt_grid_wrapped_window',
            'newt_grid_wrapped_window_at',
            'newt_label',
            'newt_label_set_text',
            'newt_listbox',
            'newt_listbox_append_entry',
            'newt_listbox_clear',
            'newt_listbox_clear_selection',
            'newt_listbox_delete_entry',
            'newt_listbox_get_current',
            'newt_listbox_get_selection',
            'newt_listbox_insert_entry',
            'newt_listbox_item_count',
            'newt_listbox_select_item',
            'newt_listbox_set_current',
            'newt_listbox_set_current_by_key',
            'newt_listbox_set_data',
            'newt_listbox_set_entry',
            'newt_listbox_set_width',
            'newt_listitem',
            'newt_listitem_get_data',
            'newt_listitem_set',
            'newt_radio_get_current',
            'newt_radiobutton',
            'newt_run_form',
            'newt_scale',
            'newt_scale_set',
            'newt_scrollbar_set',
            'newt_textbox',
            'newt_textbox_get_num_lines',
            'newt_textbox_reflowed',
            'newt_textbox_set_height',
            'newt_textbox_set_text',
            'newt_vertical_scrollbar',
            'oci_bind_array_by_name',
            'oci_bind_by_name',
            'oci_cancel',
            'oci_close',
            'oci_commit',
            'oci_connect',
            'oci_define_by_name',
            'oci_error',
            'oci_execute',
            'oci_fetch',
            'oci_fetch_all',
            'oci_fetch_array',
            'oci_fetch_assoc',
            'oci_fetch_object',
            'oci_fetch_row',
            'oci_field_is_null',
            'oci_field_name',
            'oci_field_precision',
            'oci_field_scale',
            'oci_field_size',
            'oci_field_type',
            'oci_field_type_raw',
            'oci_free_cursor',
            'oci_free_statement',
            'oci_get_implicit_resultset',
            'oci_new_collection',
            'oci_new_connect',
            'oci_new_cursor',
            'oci_new_descriptor',
            'oci_num_fields',
            'oci_num_rows',
            'oci_parse',
            'oci_pconnect',
            'oci_register_taf_callback',
            'oci_result',
            'oci_rollback',
            'oci_server_version',
            'oci_set_action',
            'oci_set_client_identifier',
            'oci_set_client_info',
            'oci_set_module_name',
            'oci_set_prefetch',
            'oci_statement_type',
            'oci_unregister_taf_callback',
            'odbc_autocommit',
            'odbc_close',
            'odbc_columnprivileges',
            'odbc_columns',
            'odbc_commit',
            'odbc_connect',
            'odbc_cursor',
            'odbc_data_source',
            'odbc_do',
            'odbc_error',
            'odbc_errormsg',
            'odbc_exec',
            'odbc_execute',
            'odbc_fetch_array',
            'odbc_fetch_into',
            'odbc_fetch_row',
            'odbc_field_len',
            'odbc_field_name',
            'odbc_field_num',
            'odbc_field_precision',
            'odbc_field_scale',
            'odbc_field_type',
            'odbc_foreignkeys',
            'odbc_free_result',
            'odbc_gettypeinfo',
            'odbc_next_result',
            'odbc_num_fields',
            'odbc_num_rows',
            'odbc_pconnect',
            'odbc_prepare',
            'odbc_primarykeys',
            'odbc_procedurecolumns',
            'odbc_procedures',
            'odbc_result',
            'odbc_result_all',
            'odbc_rollback',
            'odbc_setoption',
            'odbc_specialcolumns',
            'odbc_statistics',
            'odbc_tableprivileges',
            'odbc_tables',
            'openal_buffer_create',
            'openal_buffer_data',
            'openal_buffer_destroy',
            'openal_buffer_get',
            'openal_buffer_loadwav',
            'openal_context_create',
            'openal_context_current',
            'openal_context_destroy',
            'openal_context_process',
            'openal_context_suspend',
            'openal_device_close',
            'openal_device_open',
            'openal_source_create',
            'openal_source_destroy',
            'openal_source_get',
            'openal_source_pause',
            'openal_source_play',
            'openal_source_rewind',
            'openal_source_set',
            'openal_source_stop',
            'openal_stream',
            'opendir',
            'openssl_csr_new',
            'openssl_dh_compute_key',
            'openssl_free_key',
            'openssl_pkey_export',
            'openssl_pkey_free',
            'openssl_pkey_get_details',
            'openssl_spki_new',
            'openssl_x509_free',
            'pclose',
            'pfsockopen',
            'pg_affected_rows',
            'pg_cancel_query',
            'pg_client_encoding',
            'pg_close',
            'pg_connect_poll',
            'pg_connection_busy',
            'pg_connection_reset',
            'pg_connection_status',
            'pg_consume_input',
            'pg_convert',
            'pg_copy_from',
            'pg_copy_to',
            'pg_dbname',
            'pg_delete',
            'pg_end_copy',
            'pg_escape_bytea',
            'pg_escape_identifier',
            'pg_escape_literal',
            'pg_escape_string',
            'pg_execute',
            'pg_fetch_all',
            'pg_fetch_all_columns',
            'pg_fetch_array',
            'pg_fetch_assoc',
            'pg_fetch_row',
            'pg_field_name',
            'pg_field_num',
            'pg_field_size',
            'pg_field_table',
            'pg_field_type',
            'pg_field_type_oid',
            'pg_flush',
            'pg_free_result',
            'pg_get_notify',
            'pg_get_pid',
            'pg_get_result',
            'pg_host',
            'pg_insert',
            'pg_last_error',
            'pg_last_notice',
            'pg_last_oid',
            'pg_lo_close',
            'pg_lo_create',
            'pg_lo_export',
            'pg_lo_import',
            'pg_lo_open',
            'pg_lo_read',
            'pg_lo_read_all',
            'pg_lo_seek',
            'pg_lo_tell',
            'pg_lo_truncate',
            'pg_lo_unlink',
            'pg_lo_write',
            'pg_meta_data',
            'pg_num_fields',
            'pg_num_rows',
            'pg_options',
            'pg_parameter_status',
            'pg_ping',
            'pg_port',
            'pg_prepare',
            'pg_put_line',
            'pg_query',
            'pg_query_params',
            'pg_result_error',
            'pg_result_error_field',
            'pg_result_seek',
            'pg_result_status',
            'pg_select',
            'pg_send_execute',
            'pg_send_prepare',
            'pg_send_query',
            'pg_send_query_params',
            'pg_set_client_encoding',
            'pg_set_error_verbosity',
            'pg_socket',
            'pg_trace',
            'pg_transaction_status',
            'pg_tty',
            'pg_untrace',
            'pg_update',
            'pg_version',
            'php_user_filter::filter',
            'proc_close',
            'proc_get_status',
            'proc_terminate',
            'ps_add_bookmark',
            'ps_add_launchlink',
            'ps_add_locallink',
            'ps_add_note',
            'ps_add_pdflink',
            'ps_add_weblink',
            'ps_arc',
            'ps_arcn',
            'ps_begin_page',
            'ps_begin_pattern',
            'ps_begin_template',
            'ps_circle',
            'ps_clip',
            'ps_close',
            'ps_close_image',
            'ps_closepath',
            'ps_closepath_stroke',
            'ps_continue_text',
            'ps_curveto',
            'ps_delete',
            'ps_end_page',
            'ps_end_pattern',
            'ps_end_template',
            'ps_fill',
            'ps_fill_stroke',
            'ps_findfont',
            'ps_get_buffer',
            'ps_get_parameter',
            'ps_get_value',
            'ps_hyphenate',
            'ps_include_file',
            'ps_lineto',
            'ps_makespotcolor',
            'ps_moveto',
            'ps_new',
            'ps_open_file',
            'ps_open_image',
            'ps_open_image_file',
            'ps_open_memory_image',
            'ps_place_image',
            'ps_rect',
            'ps_restore',
            'ps_rotate',
            'ps_save',
            'ps_scale',
            'ps_set_border_color',
            'ps_set_border_dash',
            'ps_set_border_style',
            'ps_set_info',
            'ps_set_parameter',
            'ps_set_text_pos',
            'ps_set_value',
            'ps_setcolor',
            'ps_setdash',
            'ps_setflat',
            'ps_setfont',
            'ps_setgray',
            'ps_setlinecap',
            'ps_setlinejoin',
            'ps_setlinewidth',
            'ps_setmiterlimit',
            'ps_setoverprintmode',
            'ps_setpolydash',
            'ps_shading',
            'ps_shading_pattern',
            'ps_shfill',
            'ps_show',
            'ps_show2',
            'ps_show_boxed',
            'ps_show_xy',
            'ps_show_xy2',
            'ps_string_geometry',
            'ps_stringwidth',
            'ps_stroke',
            'ps_symbol',
            'ps_symbol_name',
            'ps_symbol_width',
            'ps_translate',
            'px_close',
            'px_create_fp',
            'px_date2string',
            'px_delete',
            'px_delete_record',
            'px_get_field',
            'px_get_info',
            'px_get_parameter',
            'px_get_record',
            'px_get_schema',
            'px_get_value',
            'px_insert_record',
            'px_new',
            'px_numfields',
            'px_numrecords',
            'px_open_fp',
            'px_put_record',
            'px_retrieve_record',
            'px_set_blob_file',
            'px_set_parameter',
            'px_set_tablename',
            'px_set_targetencoding',
            'px_set_value',
            'px_timestamp2string',
            'px_update_record',
            'radius_acct_open',
            'radius_add_server',
            'radius_auth_open',
            'radius_close',
            'radius_config',
            'radius_create_request',
            'radius_demangle',
            'radius_demangle_mppe_key',
            'radius_get_attr',
            'radius_put_addr',
            'radius_put_attr',
            'radius_put_int',
            'radius_put_string',
            'radius_put_vendor_addr',
            'radius_put_vendor_attr',
            'radius_put_vendor_int',
            'radius_put_vendor_string',
            'radius_request_authenticator',
            'radius_salt_encrypt_attr',
            'radius_send_request',
            'radius_server_secret',
            'radius_strerror',
            'readdir',
            'readfile',
            'recode_file',
            'rename',
            'rewind',
            'rewinddir',
            'rmdir',
            'rpm_close',
            'rpm_get_tag',
            'rpm_open',
            'sapi_windows_vt100_support',
            'scandir',
            'sem_acquire',
            'sem_get',
            'sem_release',
            'sem_remove',
            'set_file_buffer',
            'shm_attach',
            'shm_detach',
            'shm_get_var',
            'shm_has_var',
            'shm_put_var',
            'shm_remove',
            'shm_remove_var',
            'shmop_close',
            'shmop_delete',
            'shmop_open',
            'shmop_read',
            'shmop_size',
            'shmop_write',
            'socket_accept',
            'socket_addrinfo_bind',
            'socket_addrinfo_connect',
            'socket_addrinfo_explain',
            'socket_bind',
            'socket_clear_error',
            'socket_close',
            'socket_connect',
            'socket_export_stream',
            'socket_get_option',
            'socket_get_status',
            'socket_getopt',
            'socket_getpeername',
            'socket_getsockname',
            'socket_import_stream',
            'socket_last_error',
            'socket_listen',
            'socket_read',
            'socket_recv',
            'socket_recvfrom',
            'socket_recvmsg',
            'socket_send',
            'socket_sendmsg',
            'socket_sendto',
            'socket_set_block',
            'socket_set_blocking',
            'socket_set_nonblock',
            'socket_set_option',
            'socket_set_timeout',
            'socket_shutdown',
            'socket_write',
            'sqlite_close',
            'sqlite_fetch_string',
            'sqlite_has_more',
            'sqlite_open',
            'sqlite_popen',
            'sqlsrv_begin_transaction',
            'sqlsrv_cancel',
            'sqlsrv_client_info',
            'sqlsrv_close',
            'sqlsrv_commit',
            'sqlsrv_connect',
            'sqlsrv_execute',
            'sqlsrv_fetch',
            'sqlsrv_fetch_array',
            'sqlsrv_fetch_object',
            'sqlsrv_field_metadata',
            'sqlsrv_free_stmt',
            'sqlsrv_get_field',
            'sqlsrv_has_rows',
            'sqlsrv_next_result',
            'sqlsrv_num_fields',
            'sqlsrv_num_rows',
            'sqlsrv_prepare',
            'sqlsrv_query',
            'sqlsrv_rollback',
            'sqlsrv_rows_affected',
            'sqlsrv_send_stream_data',
            'sqlsrv_server_info',
            'ssh2_auth_agent',
            'ssh2_auth_hostbased_file',
            'ssh2_auth_none',
            'ssh2_auth_password',
            'ssh2_auth_pubkey_file',
            'ssh2_disconnect',
            'ssh2_exec',
            'ssh2_fetch_stream',
            'ssh2_fingerprint',
            'ssh2_methods_negotiated',
            'ssh2_publickey_add',
            'ssh2_publickey_init',
            'ssh2_publickey_list',
            'ssh2_publickey_remove',
            'ssh2_scp_recv',
            'ssh2_scp_send',
            'ssh2_sftp',
            'ssh2_sftp_chmod',
            'ssh2_sftp_lstat',
            'ssh2_sftp_mkdir',
            'ssh2_sftp_readlink',
            'ssh2_sftp_realpath',
            'ssh2_sftp_rename',
            'ssh2_sftp_rmdir',
            'ssh2_sftp_stat',
            'ssh2_sftp_symlink',
            'ssh2_sftp_unlink',
            'ssh2_shell',
            'ssh2_tunnel',
            'stomp_connect',
            'streamWrapper::stream_cast',
            'stream_bucket_append',
            'stream_bucket_make_writeable',
            'stream_bucket_new',
            'stream_bucket_prepend',
            'stream_context_create',
            'stream_context_get_default',
            'stream_context_get_options',
            'stream_context_get_params',
            'stream_context_set_default',
            'stream_context_set_params',
            'stream_copy_to_stream',
            'stream_encoding',
            'stream_filter_append',
            'stream_filter_prepend',
            'stream_filter_remove',
            'stream_get_contents',
            'stream_get_line',
            'stream_get_meta_data',
            'stream_isatty',
            'stream_set_blocking',
            'stream_set_chunk_size',
            'stream_set_read_buffer',
            'stream_set_timeout',
            'stream_set_write_buffer',
            'stream_socket_accept',
            'stream_socket_client',
            'stream_socket_enable_crypto',
            'stream_socket_get_name',
            'stream_socket_recvfrom',
            'stream_socket_sendto',
            'stream_socket_server',
            'stream_socket_shutdown',
            'stream_supports_lock',
            'svn_fs_abort_txn',
            'svn_fs_apply_text',
            'svn_fs_begin_txn2',
            'svn_fs_change_node_prop',
            'svn_fs_check_path',
            'svn_fs_contents_changed',
            'svn_fs_copy',
            'svn_fs_delete',
            'svn_fs_dir_entries',
            'svn_fs_file_contents',
            'svn_fs_file_length',
            'svn_fs_is_dir',
            'svn_fs_is_file',
            'svn_fs_make_dir',
            'svn_fs_make_file',
            'svn_fs_node_created_rev',
            'svn_fs_node_prop',
            'svn_fs_props_changed',
            'svn_fs_revision_prop',
            'svn_fs_revision_root',
            'svn_fs_txn_root',
            'svn_fs_youngest_rev',
            'svn_repos_create',
            'svn_repos_fs',
            'svn_repos_fs_begin_txn_for_commit',
            'svn_repos_fs_commit_txn',
            'svn_repos_open',
            'sybase_affected_rows',
            'sybase_close',
            'sybase_connect',
            'sybase_data_seek',
            'sybase_fetch_array',
            'sybase_fetch_assoc',
            'sybase_fetch_field',
            'sybase_fetch_object',
            'sybase_fetch_row',
            'sybase_field_seek',
            'sybase_free_result',
            'sybase_num_fields',
            'sybase_num_rows',
            'sybase_pconnect',
            'sybase_query',
            'sybase_result',
            'sybase_select_db',
            'sybase_set_message_handler',
            'sybase_unbuffered_query',
            'tmpfile',
            'udm_add_search_limit',
            'udm_alloc_agent',
            'udm_alloc_agent_array',
            'udm_cat_list',
            'udm_cat_path',
            'udm_check_charset',
            'udm_clear_search_limits',
            'udm_crc32',
            'udm_errno',
            'udm_error',
            'udm_find',
            'udm_free_agent',
            'udm_free_res',
            'udm_get_doc_count',
            'udm_get_res_field',
            'udm_get_res_param',
            'udm_hash32',
            'udm_load_ispell_data',
            'udm_set_agent_param',
            'unlink',
            'vfprintf',
            'w32api_init_dtype',
            'wddx_add_vars',
            'wddx_packet_end',
            'wddx_packet_start',
            'xml_get_current_byte_index',
            'xml_get_current_column_number',
            'xml_get_current_line_number',
            'xml_get_error_code',
            'xml_parse',
            'xml_parse_into_struct',
            'xml_parser_create',
            'xml_parser_create_ns',
            'xml_parser_free',
            'xml_parser_get_option',
            'xml_parser_set_option',
            'xml_set_character_data_handler',
            'xml_set_default_handler',
            'xml_set_element_handler',
            'xml_set_end_namespace_decl_handler',
            'xml_set_external_entity_ref_handler',
            'xml_set_notation_decl_handler',
            'xml_set_object',
            'xml_set_processing_instruction_handler',
            'xml_set_start_namespace_decl_handler',
            'xml_set_unparsed_entity_decl_handler',
            'xmlrpc_server_add_introspection_data',
            'xmlrpc_server_call_method',
            'xmlrpc_server_create',
            'xmlrpc_server_destroy',
            'xmlrpc_server_register_introspection_callback',
            'xmlrpc_server_register_method',
            'xmlwriter_end_attribute',
            'xmlwriter_end_cdata',
            'xmlwriter_end_comment',
            'xmlwriter_end_document',
            'xmlwriter_end_dtd',
            'xmlwriter_end_dtd_attlist',
            'xmlwriter_end_dtd_element',
            'xmlwriter_end_dtd_entity',
            'xmlwriter_end_element',
            'xmlwriter_end_pi',
            'xmlwriter_flush',
            'xmlwriter_full_end_element',
            'xmlwriter_open_memory',
            'xmlwriter_open_uri',
            'xmlwriter_output_memory',
            'xmlwriter_set_indent',
            'xmlwriter_set_indent_string',
            'xmlwriter_start_attribute',
            'xmlwriter_start_attribute_ns',
            'xmlwriter_start_cdata',
            'xmlwriter_start_comment',
            'xmlwriter_start_document',
            'xmlwriter_start_dtd',
            'xmlwriter_start_dtd_attlist',
            'xmlwriter_start_dtd_element',
            'xmlwriter_start_dtd_entity',
            'xmlwriter_start_element',
            'xmlwriter_start_element_ns',
            'xmlwriter_start_pi',
            'xmlwriter_text',
            'xmlwriter_write_attribute',
            'xmlwriter_write_attribute_ns',
            'xmlwriter_write_cdata',
            'xmlwriter_write_comment',
            'xmlwriter_write_dtd',
            'xmlwriter_write_dtd_attlist',
            'xmlwriter_write_dtd_element',
            'xmlwriter_write_dtd_entity',
            'xmlwriter_write_element',
            'xmlwriter_write_element_ns',
            'xmlwriter_write_pi',
            'xmlwriter_write_raw',
            'xslt_create',
            'yaz_addinfo',
            'yaz_ccl_conf',
            'yaz_ccl_parse',
            'yaz_close',
            'yaz_database',
            'yaz_element',
            'yaz_errno',
            'yaz_error',
            'yaz_es',
            'yaz_es_result',
            'yaz_get_option',
            'yaz_hits',
            'yaz_itemorder',
            'yaz_present',
            'yaz_range',
            'yaz_record',
            'yaz_scan',
            'yaz_scan_result',
            'yaz_schema',
            'yaz_search',
            'yaz_sort',
            'yaz_syntax',
            'zip_close',
            'zip_entry_close',
            'zip_entry_compressedsize',
            'zip_entry_compressionmethod',
            'zip_entry_filesize',
            'zip_entry_name',
            'zip_entry_open',
            'zip_entry_read',
            'zip_open',
            'zip_read',
        ];
    }
}
Copyright (c) 2011 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# CHANGELOG

## 3.9.3 - 2015-03-18

* Ensuring Content-Length is not stripped from a request when it is `0`.
* Added more information to stream wrapper exceptions.
* Message parser will no longer throw warnings for malformed messages.
* Giving a valid cache TTL when max-age is 0.

## 3.9.2 - 2014-09-10

* Retrying "Connection died, retrying a fresh connect" curl errors.
* Automatically extracting the cacert from the phar in client constructor.
* Added EntityBody support for OPTIONS requests.

## 3.9.1 - 2014-05-07

* Added a fix to ReadLimitEntityBody to ensure it doesn't infinitely loop.
* Added a fix to the stream checksum function so that when the first read
  returns a falsey value, it still continues to consume the stream until EOF.

## 3.9.0 - 2014-04-23

* `null`, `false`, and `"_guzzle_blank_"` all now serialize as an empty value
  with no trailing "=". See dc1d824277.
* No longer performing an MD5 check on the cacert each time the phar is used,
  but rather copying the cacert to the temp directory.
* `"0"` can now be added as a URL path
* Deleting cookies that are set to empty
* If-Modified-Since is no longer unnecessarily added to the CachePlugin
* Cookie path matching now follows RFC 6265 s5.1.4
* Updated service descriptions are now added to a service client's composite
  factory.
* MockPlugin now throws an exception if the queue is empty.
* Properly parsing URLs that start with "http" but are not absolute
* Added the ability to configure the curl_multi_select timeout setting
* OAuth parameters are now sorted using lexicographical byte value ordering
* Fixing invalid usage of an out of range PHP feature in the ErrorResponsePlugin

## 3.8.1 -2014-01-28

* Bug: Always using GET requests when redirecting from a 303 response
* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in
  `Guzzle\Http\ClientInterface::setSslVerification()`
* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL
* Bug: The body of a request can now be set to `"0"`
* Sending PHP stream requests no longer forces `HTTP/1.0`
* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of
  each sub-exception
* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than
  clobbering everything).
* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators)
* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`.
  For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`.
* Now properly escaping the regular expression delimiter when matching Cookie domains.
* Network access is now disabled when loading XML documents

## 3.8.0 - 2013-12-05

* Added the ability to define a POST name for a file
* JSON response parsing now properly walks additionalProperties
* cURL error code 18 is now retried automatically in the BackoffPlugin
* Fixed a cURL error when URLs contain fragments
* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were
  CurlExceptions
* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e)
* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS`
* Fixed a bug that was encountered when parsing empty header parameters
* UriTemplate now has a `setRegex()` method to match the docs
* The `debug` request parameter now checks if it is truthy rather than if it exists
* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin
* Added the ability to combine URLs using strict RFC 3986 compliance
* Command objects can now return the validation errors encountered by the command
* Various fixes to cache revalidation (#437 and 29797e5)
* Various fixes to the AsyncPlugin
* Cleaned up build scripts

## 3.7.4 - 2013-10-02

* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430)
* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp
  (see https://github.com/aws/aws-sdk-php/issues/147)
* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots
* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420)
* Updated the bundled cacert.pem (#419)
* OauthPlugin now supports adding authentication to headers or query string (#425)

## 3.7.3 - 2013-09-08

* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and
  `CommandTransferException`.
* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description
* Schemas are only injected into response models when explicitly configured.
* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of
  an EntityBody.
* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator.
* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`.
* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody()
* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin
* Bug fix: Visiting XML attributes first before visting XML children when serializing requests
* Bug fix: Properly parsing headers that contain commas contained in quotes
* Bug fix: mimetype guessing based on a filename is now case-insensitive

## 3.7.2 - 2013-08-02

* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander
  See https://github.com/guzzle/guzzle/issues/371
* Bug fix: Cookie domains are now matched correctly according to RFC 6265
  See https://github.com/guzzle/guzzle/issues/377
* Bug fix: GET parameters are now used when calculating an OAuth signature
* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted
* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched
* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input.
  See https://github.com/guzzle/guzzle/issues/379
* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See
  https://github.com/guzzle/guzzle/pull/380
* cURL multi cleanup and optimizations

## 3.7.1 - 2013-07-05

* Bug fix: Setting default options on a client now works
* Bug fix: Setting options on HEAD requests now works. See #352
* Bug fix: Moving stream factory before send event to before building the stream. See #353
* Bug fix: Cookies no longer match on IP addresses per RFC 6265
* Bug fix: Correctly parsing header parameters that are in `<>` and quotes
* Added `cert` and `ssl_key` as request options
* `Host` header can now diverge from the host part of a URL if the header is set manually
* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter
* OAuth parameters are only added via the plugin if they aren't already set
* Exceptions are now thrown when a URL cannot be parsed
* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails
* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin

## 3.7.0 - 2013-06-10

* See UPGRADING.md for more information on how to upgrade.
* Requests now support the ability to specify an array of $options when creating a request to more easily modify a
  request. You can pass a 'request.options' configuration setting to a client to apply default request options to
  every request created by a client (e.g. default query string variables, headers, curl options, etc).
* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`.
  See `Guzzle\Http\StaticClient::mount`.
* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests
      created by a command (e.g. custom headers, query string variables, timeout settings, etc).
* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the
  headers of a response
* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key
  (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`)
* ServiceBuilders now support storing and retrieving arbitrary data
* CachePlugin can now purge all resources for a given URI
* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource
* CachePlugin now uses the Vary header to determine if a resource is a cache hit
* `Guzzle\Http\Message\Response` now implements `\Serializable`
* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters
* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable
* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()`
* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size
* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message
* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older
  Symfony users can still use the old version of Monolog.
* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`.
  Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`.
* Several performance improvements to `Guzzle\Common\Collection`
* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`:
  createRequest, head, delete, put, patch, post, options, prepareRequest
* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()`
* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface`
* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to
  `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a
  resource, string, or EntityBody into the $options parameter to specify the download location of the response.
* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a
  default `array()`
* Added `Guzzle\Stream\StreamInterface::isRepeatable`
* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use
  $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or
  $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`.
* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`.
* Removed `Guzzle\Http\ClientInterface::expandTemplate()`
* Removed `Guzzle\Http\ClientInterface::setRequestFactory()`
* Removed `Guzzle\Http\ClientInterface::getCurlMulti()`
* Removed `Guzzle\Http\Message\RequestInterface::canCache`
* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`
* Removed `Guzzle\Http\Message\RequestInterface::isRedirect`
* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods.
* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting
  `Guzzle\Common\Version::$emitWarnings` to true.
* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use
      `$request->getResponseBody()->isRepeatable()` instead.
* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use
  `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use
  `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead.
* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead.
* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated
* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand.
  These will work through Guzzle 4.0
* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params].
* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client.
* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`.
* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`.
* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8.
* Marked `Guzzle\Common\Collection::inject()` as deprecated.
* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');`
* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a
  CacheStorageInterface. These two objects and interface will be removed in a future version.
* Always setting X-cache headers on cached responses
* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin
* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface
  $request, Response $response);`
* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);`
* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);`
* Added `CacheStorageInterface::purge($url)`
* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin
  $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache,
  CanCacheStrategyInterface $canCache = null)`
* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)`

## 3.6.0 - 2013-05-29

* ServiceDescription now implements ToArrayInterface
* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters
* Guzzle can now correctly parse incomplete URLs
* Mixed casing of headers are now forced to be a single consistent casing across all values for that header.
* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution
* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader().
* Specific header implementations can be created for complex headers. When a message creates a header, it uses a
  HeaderFactory which can map specific headers to specific header classes. There is now a Link header and
  CacheControl header implementation.
* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate
* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti()
* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in
  Guzzle\Http\Curl\RequestMediator
* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string.
* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface
* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders()
* Removed Guzzle\Parser\ParserRegister::get(). Use getParser()
* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser().
* All response header helper functions return a string rather than mixing Header objects and strings inconsistently
* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc are managed by Guzzle
  directly via interfaces
* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist
  but are a no-op until removed.
* Most classes that used to require a ``Guzzle\Service\Command\CommandInterface` typehint now request a
  `Guzzle\Service\Command\ArrayCommandInterface`.
* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response
  on a request while the request is still being transferred
* The ability to case-insensitively search for header values
* Guzzle\Http\Message\Header::hasExactHeader
* Guzzle\Http\Message\Header::raw. Use getAll()
* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object
  instead.
* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess
* Added the ability to cast Model objects to a string to view debug information.

## 3.5.0 - 2013-05-13

* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times
* Bug: Better cleanup of one-time events accross the board (when an event is meant to fire once, it will now remove
  itself from the EventDispatcher)
* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values
* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too
* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a
  non-existent key
* Bug: All __call() method arguments are now required (helps with mocking frameworks)
* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference
  to help with refcount based garbage collection of resources created by sending a request
* Deprecating ZF1 cache and log adapters. These will be removed in the next major version.
* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it'sdeprecated). Use the
  HistoryPlugin for a history.
* Added a `responseBody` alias for the `response_body` location
* Refactored internals to no longer rely on Response::getRequest()
* HistoryPlugin can now be cast to a string
* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests
  and responses that are sent over the wire
* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects

## 3.4.3 - 2013-04-30

* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response
* Added a check to re-extract the temp cacert bundle from the phar before sending each request

## 3.4.2 - 2013-04-29

* Bug fix: Stream objects now work correctly with "a" and "a+" modes
* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present
* Bug fix: AsyncPlugin no longer forces HEAD requests
* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter
* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails
* Setting a response on a request will write to the custom request body from the response body if one is specified
* LogPlugin now writes to php://output when STDERR is undefined
* Added the ability to set multiple POST files for the same key in a single call
* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default
* Added the ability to queue CurlExceptions to the MockPlugin
* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send)
* Configuration loading now allows remote files

## 3.4.1 - 2013-04-16

* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti
  handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost.
* Exceptions are now properly grouped when sending requests in parallel
* Redirects are now properly aggregated when a multi transaction fails
* Redirects now set the response on the original object even in the event of a failure
* Bug fix: Model names are now properly set even when using $refs
* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax
* Added support for oauth_callback in OAuth signatures
* Added support for oauth_verifier in OAuth signatures
* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection

## 3.4.0 - 2013-04-11

* Bug fix: URLs are now resolved correctly based on http://tools.ietf.org/html/rfc3986#section-5.2. #289
* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289
* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263
* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264.
* Bug fix: Added `number` type to service descriptions.
* Bug fix: empty parameters are removed from an OAuth signature
* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header
* Bug fix: Fixed "array to string" error when validating a union of types in a service description
* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream
* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin.
* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs.
* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections.
* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if
  the Content-Type can be determined based on the entity body or the path of the request.
* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder.
* Added support for a PSR-3 LogAdapter.
* Added a `command.after_prepare` event
* Added `oauth_callback` parameter to the OauthPlugin
* Added the ability to create a custom stream class when using a stream factory
* Added a CachingEntityBody decorator
* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized.
* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar.
* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies
* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This
  means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use
  POST fields or files (the latter is only used when emulating a form POST in the browser).
* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest

## 3.3.1 - 2013-03-10

* Added the ability to create PHP streaming responses from HTTP requests
* Bug fix: Running any filters when parsing response headers with service descriptions
* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing
* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across
  response location visitors.
* Bug fix: Removed the possibility of creating configuration files with circular dependencies
* RequestFactory::create() now uses the key of a POST file when setting the POST file name
* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set

## 3.3.0 - 2013-03-03

* A large number of performance optimizations have been made
* Bug fix: Added 'wb' as a valid write mode for streams
* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned
* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()`
* BC: Removed `Guzzle\Http\Utils` class
* BC: Setting a service description on a client will no longer modify the client's command factories.
* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using
  the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io'
* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to
  lowercase
* Operation parameter objects are now lazy loaded internally
* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses
* Added support for instantiating responseType=class responseClass classes. Classes must implement
  `Guzzle\Service\Command\ResponseClassInterface`
* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These
  additional properties also support locations and can be used to parse JSON responses where the outermost part of the
  JSON is an array
* Added support for nested renaming of JSON models (rename sentAs to name)
* CachePlugin
    * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error
    * Debug headers can now added to cached response in the CachePlugin

## 3.2.0 - 2013-02-14

* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients.
* URLs with no path no longer contain a "/" by default
* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url.
* BadResponseException no longer includes the full request and response message
* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface
* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface
* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription
* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list
* xmlEncoding can now be customized for the XML declaration of a XML service description operation
* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value
  aggregation and no longer uses callbacks
* The URL encoding implementation of Guzzle\Http\QueryString can now be customized
* Bug fix: Filters were not always invoked for array service description parameters
* Bug fix: Redirects now use a target response body rather than a temporary response body
* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded
* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives

## 3.1.2 - 2013-01-27

* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the
  response body. For example, the XmlVisitor now parses the XML response into an array in the before() method.
* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent
* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444)
* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse()
* Setting default headers on a client after setting the user-agent will not erase the user-agent setting

## 3.1.1 - 2013-01-20

* Adding wildcard support to Guzzle\Common\Collection::getPath()
* Adding alias support to ServiceBuilder configs
* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface

## 3.1.0 - 2013-01-12

* BC: CurlException now extends from RequestException rather than BadResponseException
* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse()
* Added getData to ServiceDescriptionInterface
* Added context array to RequestInterface::setState()
* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http
* Bug: Adding required content-type when JSON request visitor adds JSON to a command
* Bug: Fixing the serialization of a service description with custom data
* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing
  an array of successful and failed responses
* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection
* Added Guzzle\Http\IoEmittingEntityBody
* Moved command filtration from validators to location visitors
* Added `extends` attributes to service description parameters
* Added getModels to ServiceDescriptionInterface

## 3.0.7 - 2012-12-19

* Fixing phar detection when forcing a cacert to system if null or true
* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()`
* Cleaning up `Guzzle\Common\Collection::inject` method
* Adding a response_body location to service descriptions

## 3.0.6 - 2012-12-09

* CurlMulti performance improvements
* Adding setErrorResponses() to Operation
* composer.json tweaks

## 3.0.5 - 2012-11-18

* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin
* Bug: Response body can now be a string containing "0"
* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert
* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs
* Added support for XML attributes in service description responses
* DefaultRequestSerializer now supports array URI parameter values for URI template expansion
* Added better mimetype guessing to requests and post files

## 3.0.4 - 2012-11-11

* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value
* Bug: Cookies can now be added that have a name, domain, or value set to "0"
* Bug: Using the system cacert bundle when using the Phar
* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures
* Enhanced cookie jar de-duplication
* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added
* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies
* Added the ability to create any sort of hash for a stream rather than just an MD5 hash

## 3.0.3 - 2012-11-04

* Implementing redirects in PHP rather than cURL
* Added PECL URI template extension and using as default parser if available
* Bug: Fixed Content-Length parsing of Response factory
* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams.
* Adding ToArrayInterface throughout library
* Fixing OauthPlugin to create unique nonce values per request

## 3.0.2 - 2012-10-25

* Magic methods are enabled by default on clients
* Magic methods return the result of a command
* Service clients no longer require a base_url option in the factory
* Bug: Fixed an issue with URI templates where null template variables were being expanded

## 3.0.1 - 2012-10-22

* Models can now be used like regular collection objects by calling filter, map, etc
* Models no longer require a Parameter structure or initial data in the constructor
* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator`

## 3.0.0 - 2012-10-15

* Rewrote service description format to be based on Swagger
    * Now based on JSON schema
    * Added nested input structures and nested response models
    * Support for JSON and XML input and output models
    * Renamed `commands` to `operations`
    * Removed dot class notation
    * Removed custom types
* Broke the project into smaller top-level namespaces to be more component friendly
* Removed support for XML configs and descriptions. Use arrays or JSON files.
* Removed the Validation component and Inspector
* Moved all cookie code to Guzzle\Plugin\Cookie
* Magic methods on a Guzzle\Service\Client now return the command un-executed.
* Calling getResult() or getResponse() on a command will lazily execute the command if needed.
* Now shipping with cURL's CA certs and using it by default
* Added previousResponse() method to response objects
* No longer sending Accept and Accept-Encoding headers on every request
* Only sending an Expect header by default when a payload is greater than 1MB
* Added/moved client options:
    * curl.blacklist to curl.option.blacklist
    * Added ssl.certificate_authority
* Added a Guzzle\Iterator component
* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin
* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin)
* Added a more robust caching plugin
* Added setBody to response objects
* Updating LogPlugin to use a more flexible MessageFormatter
* Added a completely revamped build process
* Cleaning up Collection class and removing default values from the get method
* Fixed ZF2 cache adapters

## 2.8.8 - 2012-10-15

* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did

## 2.8.7 - 2012-09-30

* Bug: Fixed config file aliases for JSON includes
* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests
* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload
* Bug: Hardening request and response parsing to account for missing parts
* Bug: Fixed PEAR packaging
* Bug: Fixed Request::getInfo
* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail
* Adding the ability for the namespace Iterator factory to look in multiple directories
* Added more getters/setters/removers from service descriptions
* Added the ability to remove POST fields from OAuth signatures
* OAuth plugin now supports 2-legged OAuth

## 2.8.6 - 2012-09-05

* Added the ability to modify and build service descriptions
* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command
* Added a `json` parameter location
* Now allowing dot notation for classes in the CacheAdapterFactory
* Using the union of two arrays rather than an array_merge when extending service builder services and service params
* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references
  in service builder config files.
* Services defined in two different config files that include one another will by default replace the previously
  defined service, but you can now create services that extend themselves and merge their settings over the previous
* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like
  '_default' with a default JSON configuration file.

## 2.8.5 - 2012-08-29

* Bug: Suppressed empty arrays from URI templates
* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching
* Added support for HTTP responses that do not contain a reason phrase in the start-line
* AbstractCommand commands are now invokable
* Added a way to get the data used when signing an Oauth request before a request is sent

## 2.8.4 - 2012-08-15

* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin
* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable.
* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream
* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream
* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5())
* Added additional response status codes
* Removed SSL information from the default User-Agent header
* DELETE requests can now send an entity body
* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries
* Added the ability of the MockPlugin to consume mocked request bodies
* LogPlugin now exposes request and response objects in the extras array

## 2.8.3 - 2012-07-30

* Bug: Fixed a case where empty POST requests were sent as GET requests
* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body
* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new
* Added multiple inheritance to service description commands
* Added an ApiCommandInterface and added ``getParamNames()`` and ``hasParam()``
* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything
* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles

## 2.8.2 - 2012-07-24

* Bug: Query string values set to 0 are no longer dropped from the query string
* Bug: A Collection object is no longer created each time a call is made to ``Guzzle\Service\Command\AbstractCommand::getRequestHeaders()``
* Bug: ``+`` is now treated as an encoded space when parsing query strings
* QueryString and Collection performance improvements
* Allowing dot notation for class paths in filters attribute of a service descriptions

## 2.8.1 - 2012-07-16

* Loosening Event Dispatcher dependency
* POST redirects can now be customized using CURLOPT_POSTREDIR

## 2.8.0 - 2012-07-15

* BC: Guzzle\Http\Query
    * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl)
    * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding()
    * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool)
    * Changed the aggregation functions of QueryString to be static methods
    * Can now use fromString() with querystrings that have a leading ?
* cURL configuration values can be specified in service descriptions using ``curl.`` prefixed parameters
* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body
* Cookies are no longer URL decoded by default
* Bug: URI template variables set to null are no longer expanded

## 2.7.2 - 2012-07-02

* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser.
* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty()
* CachePlugin now allows for a custom request parameter function to check if a request can be cached
* Bug fix: CachePlugin now only caches GET and HEAD requests by default
* Bug fix: Using header glue when transferring headers over the wire
* Allowing deeply nested arrays for composite variables in URI templates
* Batch divisors can now return iterators or arrays

## 2.7.1 - 2012-06-26

* Minor patch to update version number in UA string
* Updating build process

## 2.7.0 - 2012-06-25

* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes.
* BC: Removed magic setX methods from commands
* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method
* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable.
* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity)
* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace
* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin
* Added the ability to set POST fields and files in a service description
* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method
* Adding a command.before_prepare event to clients
* Added BatchClosureTransfer and BatchClosureDivisor
* BatchTransferException now includes references to the batch divisor and transfer strategies
* Fixed some tests so that they pass more reliably
* Added Guzzle\Common\Log\ArrayLogAdapter

## 2.6.6 - 2012-06-10

* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin
* BC: Removing Guzzle\Service\Command\CommandSet
* Adding generic batching system (replaces the batch queue plugin and command set)
* Updating ZF cache and log adapters and now using ZF's composer repository
* Bug: Setting the name of each ApiParam when creating through an ApiCommand
* Adding result_type, result_doc, deprecated, and doc_url to service descriptions
* Bug: Changed the default cookie header casing back to 'Cookie'

## 2.6.5 - 2012-06-03

* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource()
* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from
* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data
* BC: Renaming methods in the CookieJarInterface
* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations
* Making the default glue for HTTP headers ';' instead of ','
* Adding a removeValue to Guzzle\Http\Message\Header
* Adding getCookies() to request interface.
* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber()

## 2.6.4 - 2012-05-30

* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class.
* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand
* Bug: Fixing magic method command calls on clients
* Bug: Email constraint only validates strings
* Bug: Aggregate POST fields when POST files are present in curl handle
* Bug: Fixing default User-Agent header
* Bug: Only appending or prepending parameters in commands if they are specified
* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes
* Allowing the use of dot notation for class namespaces when using instance_of constraint
* Added any_match validation constraint
* Added an AsyncPlugin
* Passing request object to the calculateWait method of the ExponentialBackoffPlugin
* Allowing the result of a command object to be changed
* Parsing location and type sub values when instantiating a service description rather than over and over at runtime

## 2.6.3 - 2012-05-23

* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options.
* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields.
* You can now use an array of data when creating PUT request bodies in the request factory.
* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable.
* [Http] Adding support for Content-Type in multipart POST uploads per upload
* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1])
* Adding more POST data operations for easier manipulation of POST data.
* You can now set empty POST fields.
* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files.
* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate.
* CS updates

## 2.6.2 - 2012-05-19

* [Http] Better handling of nested scope requests in CurlMulti.  Requests are now always prepares in the send() method rather than the addRequest() method.

## 2.6.1 - 2012-05-19

* [BC] Removing 'path' support in service descriptions.  Use 'uri'.
* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache.
* [BC] Removing Guzzle\Common\NullObject.  Use https://github.com/mtdowling/NullObject if you need it.
* [BC] Removing Guzzle\Common\XmlElement.
* All commands, both dynamic and concrete, have ApiCommand objects.
* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits.
* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored.
* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible.

## 2.6.0 - 2012-05-15

* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder
* [BC] Executing a Command returns the result of the command rather than the command
* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed.
* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args.
* [BC] Moving ResourceIterator* to Guzzle\Service\Resource
* [BC] Completely refactored ResourceIterators to iterate over a cloned command object
* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate
* [BC] Guzzle\Guzzle is now deprecated
* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject
* Adding Guzzle\Version class to give version information about Guzzle
* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate()
* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data
* ServiceDescription and ServiceBuilder are now cacheable using similar configs
* Changing the format of XML and JSON service builder configs.  Backwards compatible.
* Cleaned up Cookie parsing
* Trimming the default Guzzle User-Agent header
* Adding a setOnComplete() method to Commands that is called when a command completes
* Keeping track of requests that were mocked in the MockPlugin
* Fixed a caching bug in the CacheAdapterFactory
* Inspector objects can be injected into a Command object
* Refactoring a lot of code and tests to be case insensitive when dealing with headers
* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL
* Adding the ability to set global option overrides to service builder configs
* Adding the ability to include other service builder config files from within XML and JSON files
* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method.

## 2.5.0 - 2012-05-08

* Major performance improvements
* [BC] Simplifying Guzzle\Common\Collection.  Please check to see if you are using features that are now deprecated.
* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component.
* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates.  Use "{}"
* Added the ability to passed parameters to all requests created by a client
* Added callback functionality to the ExponentialBackoffPlugin
* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies.
* Rewinding request stream bodies when retrying requests
* Exception is thrown when JSON response body cannot be decoded
* Added configurable magic method calls to clients and commands.  This is off by default.
* Fixed a defect that added a hash to every parsed URL part
* Fixed duplicate none generation for OauthPlugin.
* Emitting an event each time a client is generated by a ServiceBuilder
* Using an ApiParams object instead of a Collection for parameters of an ApiCommand
* cache.* request parameters should be renamed to params.cache.*
* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc). See CurlHandle.
* Added the ability to disable type validation of service descriptions
* ServiceDescriptions and ServiceBuilders are now Serializable
<?xml version="1.0" encoding="UTF-8"?>
<project name="guzzle" default="test">
    <!-- set local values, like git location -->
    <property file="phing/build.properties.dist" override="true" />
    <property file="phing/build.properties" override="true" />

    <property name="dir.output" value="${project.basedir}/build/artifacts" />
    <property name="dir.imports" value="${project.basedir}/phing/imports" />
    <property name="dir.bin" value="${project.basedir}/bin" />
    <property name="repo.dir" value="${project.basedir}" />

    <import file="${dir.imports}/dependencies.xml"/>
    <import file="${dir.imports}/deploy.xml"/>

    <target name="composer-lint" description="lint-check composer.json only">
        <composerlint dir="${project.basedir}/src" file="{$project.basedir}/composer.json" />
    </target>

    <target name="test" description="Run unit tests">
        <exec passthru="true" command="vendor/bin/phpunit" checkReturn="true" />
    </target>

    <target name="build-init" description="Initialize local phing properties">
        <copy file="phing/build.properties.dist" tofile="phing/build.properties" overwrite="false" />
    </target>

    <target name="clean">
        <delete dir="${dir.output}"/>
        <delete dir="${project.basedir}/build/pearwork"/>
    </target>

    <target name="prepare" depends="clean,build-init">
        <mkdir dir="${dir.output}"/>
        <mkdir dir="${dir.output}/logs" />
    </target>

    <target name="coverage" depends="prepare">
        <exec passthru="true" command="vendor/bin/phpunit --coverage-html=${dir.output}/coverage" />
    </target>

    <target name="view-coverage">
        <exec passthru="true" command="open ${dir.output}/coverage/index.html" />
    </target>

</project>
<?php

Phar::mapPhar('guzzle.phar');

require_once 'phar://guzzle.phar/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php';

$classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$classLoader->registerNamespaces(array(
    'Guzzle' => 'phar://guzzle.phar/src',
    'Symfony\\Component\\EventDispatcher' => 'phar://guzzle.phar/vendor/symfony/event-dispatcher',
    'Doctrine' => 'phar://guzzle.phar/vendor/doctrine/common/lib',
    'Monolog' => 'phar://guzzle.phar/vendor/monolog/monolog/src'
));
$classLoader->register();

__HALT_COMPILER();
<?php
error_reporting(E_ALL | E_STRICT);

require_once 'PHPUnit/TextUI/TestRunner.php';
require dirname(__DIR__) . '/vendor/autoload.php';

// Add the services file to the default service builder
$servicesFile = __DIR__ . '/Guzzle/Tests/TestData/services/services.json';
$builder = Guzzle\Service\Builder\ServiceBuilder::factory($servicesFile);
Guzzle\Tests\GuzzleTestCase::setServiceBuilder($builder);
{
    "operations": {
        "abstract": {
            "uri": "/abstract"
        }
    }
}
HTTP/1.1 200 OK
Content-Length: 0

{
    "includes": [ "test_service2.json" ],
    "operations": {
        "test": {
            "uri": "/path"
        },
        "concrete": {
            "extends": "abstract"
        },
        "baz_qux": {
            "uri": "/testing",
            "parameters": {
                "other": {
                    "location": "json",
                    "location_key": "Other"
                },
                "test": {
                    "type": "object",
                    "location": "json",
                    "properties": {
                        "baz": {
                            "type": "boolean",
                            "default": true
                        },
                        "bar": {
                            "type": "string",
                            "filters": [
                                {
                                    "method": "strtolower",
                                    "args": ["test", "@value"]
                                },
                                "strtoupper"
                            ]
                        }
                    }
                }
            }
        }
    }
}
{
    "includes": ["foo.json", "bar.json"]
}
{
    "includes": ["foo.json"]
}
{
    "includes": ["recursive.json"],
    "operations": {
        "abstract": {
            "httpMethod": "POST"
        }
    }
}
{
    "includes": ["foo.json"]
}
{
    "includes": [ "test_service2.json" ],
    "operations": {
        "test": {
            "uri": "/path"
        },
        "concrete": {
            "extends": "abstract"
        },
        "foo_bar": {
            "uri": "/testing",
            "parameters": {
                "other": {
                    "location": "json",
                    "location_key": "Other"
                },
                "test": {
                    "type": "object",
                    "location": "json",
                    "properties": {
                        "baz": {
                            "type": "boolean",
                            "default": true
                        },
                        "bar": {
                            "type": "string",
                            "filters": [
                                {
                                    "method": "strtolower",
                                    "args": ["test", "@value"]
                                },
                                "strtoupper"
                            ]
                        }
                    }
                }
            }
        }
    }
}
{
    "abstract": {
        "access_key": "xyz",
        "secret": "abc"
    },
    "mock": {
        "class": "Guzzle\\Tests\\Service\\Mock\\MockClient",
        "extends": "abstract",
        "params": {
            "username": "foo",
            "password": "baz",
            "subdomain": "bar"
        }
    },

    "test.abstract.aws": {
        "params": {
            "access_key": "12345",
            "secret_key": "abcd"
        }
    },

    "test.s3": {
        "class": "Guzzle\\Service\\Aws\\S3Client",
        "extends": "test.abstract.aws",
        "params": {
            "devpay_product_token": "",
            "devpay_user_token": ""
        }
    },

    "test.simple_db": {
        "class":   "Guzzle\\Service\\Aws\\SimpleDb\\SimpleDbClient",
        "extends": "test.abstract.aws"
    },

    "test.sqs": {
        "class":   "Guzzle\\Service\\Aws\\Sqs\\SqsClient",
        "extends": "test.abstract.aws"
    },

    "test.centinel": {
        "class": "Guzzle\\Service\\CardinalCommerce\\Centinel.CentinelClient",
        "params": {
            "password": "test",
            "processor_id": "123",
            "merchant_id": "456"
        }
    },

    "test.mws": {
        "class": "Guzzle\\Service\\Mws\\MwsClient",
        "extends": "test.abstract.aws",
        "params": {
            "merchant_id": "ABCDE",
            "marketplace_id": "FGHIJ",
            "application_name": "GuzzleTest",
            "application_version": "0.1",
            "base_url": "https://mws.amazonservices.com"
        }
    },

    "mock": {
        "class": "Guzzle\\Tests\\Service\\Mock\\MockClient",
        "params": {
            "username": "test_user",
            "password": "****",
            "subdomain": "test"
        }
    }
}
{
    "includes": [ "json2.json" ],
    "services": {
        "abstract": {
            "access_key": "xyz",
            "secret": "abc"
        },
        "mock": {
            "class": "Guzzle\\Tests\\Service\\Mock\\MockClient",
            "extends": "abstract",
            "params": {
                "username": "foo",
                "password": "baz",
                "subdomain": "bar"
            }
        }
    }
}
{
    "services": {
        "foo": {
            "class": "Guzzle\\Tests\\Service\\Mock\\MockClient",
            "extends": "abstract",
            "params": {
                "baz": "bar"
            }
        }
    }
}
<?php

namespace Guzzle\Tests\Cache;

use Guzzle\Cache\Zf2CacheAdapter;
use Zend\Cache\StorageFactory;

/**
 * @covers Guzzle\Cache\Zf2CacheAdapter
 */
class Zf2CacheAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    private $cache;
    private $adapter;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->cache = StorageFactory::factory(array(
            'adapter' => 'memory'
        ));
        $this->adapter = new Zf2CacheAdapter($this->cache);
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->adapter = null;
        $this->cache = null;
        parent::tearDown();
    }

    public function testCachesDataUsingCallables()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
        $this->assertEquals('data', $this->adapter->fetch('test'));
    }

    public function testChecksIfCacheContainsKeys()
    {
        $this->adapter->save('test', 'data', 1000);
        $this->assertTrue($this->adapter->contains('test'));
        $this->assertFalse($this->adapter->contains('foo'));
    }

    public function testDeletesFromCacheByKey()
    {
        $this->adapter->save('test', 'data', 1000);
        $this->assertTrue($this->adapter->contains('test'));
        $this->adapter->delete('test');
        $this->assertFalse($this->adapter->contains('test'));
    }
}
<?php

namespace Guzzle\Tests\Cache;

use Guzzle\Cache\ClosureCacheAdapter;

/**
 * @covers Guzzle\Cache\ClosureCacheAdapter
 */
class ClosureCacheAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var ClosureCacheAdapter */
    private $adapter;

    /** Array of callables to use for testing */
    private $callables;

    /** Cache data for testing */
    public $data = array();

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();

        $that = $this;
        $this->callables = array(
            'contains' => function($id, $options = array()) use ($that) {
                return array_key_exists($id, $that->data);
            },
            'delete' => function($id, $options = array()) use ($that) {
                unset($that->data[$id]);
                return true;
            },
            'fetch' => function($id, $options = array()) use ($that) {
                return array_key_exists($id, $that->data) ? $that->data[$id] : null;
            },
            'save' => function($id, $data, $lifeTime, $options = array()) use ($that) {
                $that->data[$id] = $data;
                return true;
            }
        );

        $this->adapter = new ClosureCacheAdapter($this->callables);
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->cache = null;
        $this->callables = null;
        parent::tearDown();
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testEnsuresCallablesArePresent()
    {
        $callables = $this->callables;
        unset($callables['delete']);
        $cache = new ClosureCacheAdapter($callables);
    }

    public function testAllCallablesMustBePresent()
    {
        $cache = new ClosureCacheAdapter($this->callables);
    }

    public function testCachesDataUsingCallables()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
        $this->assertEquals('data', $this->adapter->fetch('test'));
    }

    public function testChecksIfCacheContainsKeys()
    {
        $this->adapter->save('test', 'data', 1000);
        $this->assertTrue($this->adapter->contains('test'));
        $this->assertFalse($this->adapter->contains('foo'));
    }

    public function testDeletesFromCacheByKey()
    {
        $this->adapter->save('test', 'data', 1000);
        $this->assertTrue($this->adapter->contains('test'));
        $this->adapter->delete('test');
        $this->assertFalse($this->adapter->contains('test'));
    }
}
<?php

namespace Guzzle\Tests\Cache;

use Guzzle\Cache\DoctrineCacheAdapter;
use Doctrine\Common\Cache\ArrayCache;

/**
 * @covers Guzzle\Cache\DoctrineCacheAdapter
 * @covers Guzzle\Cache\AbstractCacheAdapter
 */
class CacheAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var ArrayCache */
    private $cache;

    /** @var DoctrineCacheAdapter */
    private $adapter;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->cache = new ArrayCache();
        $this->adapter = new DoctrineCacheAdapter($this->cache);
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->adapter = null;
        $this->cache = null;
        parent::tearDown();
    }

    public function testGetCacheObject()
    {
        $this->assertEquals($this->cache, $this->adapter->getCacheObject());
    }

    public function testSave()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
    }

    public function testFetch()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
        $this->assertEquals('data', $this->adapter->fetch('test'));
    }

    public function testContains()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
        $this->assertTrue($this->adapter->contains('test'));
    }

    public function testDelete()
    {
        $this->assertTrue($this->adapter->save('test', 'data', 1000));
        $this->assertTrue($this->adapter->delete('test'));
        $this->assertFalse($this->adapter->contains('test'));
    }
}
<?php

namespace Guzzle\Tests\Cache;

use Guzzle\Cache\CacheAdapterFactory;
use Guzzle\Cache\DoctrineCacheAdapter;
use Doctrine\Common\Cache\ArrayCache;
use Zend\Cache\StorageFactory;

/**
 * @covers Guzzle\Cache\CacheAdapterFactory
 */
class CacheAdapterFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var ArrayCache */
    private $cache;

    /** @var DoctrineCacheAdapter */
    private $adapter;

    /**
     * Prepares the environment before running a test.
     */
    protected function setup()
    {
        parent::setUp();
        $this->cache = new ArrayCache();
        $this->adapter = new DoctrineCacheAdapter($this->cache);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testEnsuresConfigIsObject()
    {
        CacheAdapterFactory::fromCache(array());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testEnsuresKnownType()
    {
        CacheAdapterFactory::fromCache(new \stdClass());
    }

    public function cacheProvider()
    {
        return array(
            array(new DoctrineCacheAdapter(new ArrayCache()), 'Guzzle\Cache\DoctrineCacheAdapter'),
            array(new ArrayCache(), 'Guzzle\Cache\DoctrineCacheAdapter'),
            array(StorageFactory::factory(array('adapter' => 'memory')), 'Guzzle\Cache\Zf2CacheAdapter'),
        );
    }

    /**
     * @dataProvider cacheProvider
     */
    public function testCreatesNullCacheAdapterByDefault($cache, $type)
    {
        $adapter = CacheAdapterFactory::fromCache($cache);
        $this->assertInstanceOf($type, $adapter);
    }
}
<?php

namespace Guzzle\Tests\Common\Cache;

use Guzzle\Cache\NullCacheAdapter;

/**
 * @covers Guzzle\Cache\NullCacheAdapter
 */
class NullCacheAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testNullCacheAdapter()
    {
        $c = new NullCacheAdapter();
        $this->assertEquals(false, $c->contains('foo'));
        $this->assertEquals(true, $c->delete('foo'));
        $this->assertEquals(false, $c->fetch('foo'));
        $this->assertEquals(true, $c->save('foo', 'bar'));
    }
}
<?php

namespace Guzzle\Tests;

use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Tests\Http\Message\HeaderComparison;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\Client;
use Guzzle\Service\Builder\ServiceBuilderInterface;
use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Tests\Mock\MockObserver;
use Guzzle\Tests\Http\Server;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Base testcase class for all Guzzle testcases.
 */
abstract class GuzzleTestCase extends \PHPUnit_Framework_TestCase
{
    protected static $mockBasePath;
    public static $serviceBuilder;
    public static $server;

    private $requests = array();
    public $mockObserver;

    /**
     * Get the global server object used throughout the unit tests of Guzzle
     *
     * @return Server
     */
    public static function getServer()
    {
        if (!self::$server) {
            self::$server = new Server();
            if (self::$server->isRunning()) {
                self::$server->flush();
            } else {
                self::$server->start();
            }
        }

        return self::$server;
    }

    /**
     * Set the service builder to use for tests
     *
     * @param ServiceBuilderInterface $builder Service builder
     */
    public static function setServiceBuilder(ServiceBuilderInterface $builder)
    {
        self::$serviceBuilder = $builder;
    }

    /**
     * Get a service builder object that can be used throughout the service tests
     *
     * @return ServiceBuilder
     */
    public static function getServiceBuilder()
    {
        if (!self::$serviceBuilder) {
            throw new RuntimeException('No service builder has been set via setServiceBuilder()');
        }

        return self::$serviceBuilder;
    }

    /**
     * Check if an event dispatcher has a subscriber
     *
     * @param HasDispatcherInterface $dispatcher
     * @param EventSubscriberInterface $subscriber
     *
     * @return bool
     */
    protected function hasSubscriber(HasDispatcherInterface $dispatcher, EventSubscriberInterface $subscriber)
    {
        $class = get_class($subscriber);
        $all = array_keys(call_user_func(array($class, 'getSubscribedEvents')));

        foreach ($all as $i => $event) {
            foreach ($dispatcher->getEventDispatcher()->getListeners($event) as $e) {
                if ($e[0] === $subscriber) {
                    unset($all[$i]);
                    break;
                }
            }
        }

        return count($all) == 0;
    }

    /**
     * Get a wildcard observer for an event dispatcher
     *
     * @param HasDispatcherInterface $hasDispatcher
     *
     * @return MockObserver
     */
    public function getWildcardObserver(HasDispatcherInterface $hasDispatcher)
    {
        $class = get_class($hasDispatcher);
        $o = new MockObserver();
        $events = call_user_func(array($class, 'getAllEvents'));
        foreach ($events as $event) {
            $hasDispatcher->getEventDispatcher()->addListener($event, array($o, 'update'));
        }

        return $o;
    }

    /**
     * Set the mock response base path
     *
     * @param string $path Path to mock response folder
     *
     * @return GuzzleTestCase
     */
    public static function setMockBasePath($path)
    {
        self::$mockBasePath = $path;
    }

    /**
     * Mark a request as being mocked
     *
     * @param RequestInterface $request
     *
     * @return self
     */
    public function addMockedRequest(RequestInterface $request)
    {
        $this->requests[] = $request;

        return $this;
    }

    /**
     * Get all of the mocked requests
     *
     * @return array
     */
    public function getMockedRequests()
    {
        return $this->requests;
    }

    /**
     * Get a mock response for a client by mock file name
     *
     * @param string $path Relative path to the mock response file
     *
     * @return Response
     */
    public function getMockResponse($path)
    {
        return $path instanceof Response
            ? $path
            : MockPlugin::getMockFile(self::$mockBasePath . DIRECTORY_SEPARATOR . $path);
    }

    /**
     * Set a mock response from a mock file on the next client request.
     *
     * This method assumes that mock response files are located under the
     * Command/Mock/ directory of the Service being tested
     * (e.g. Unfuddle/Command/Mock/).  A mock response is added to the next
     * request sent by the client.
     *
     * @param Client $client Client object to modify
     * @param string $paths  Path to files within the Mock folder of the service
     *
     * @return MockPlugin returns the created mock plugin
     */
    public function setMockResponse(Client $client, $paths)
    {
        $this->requests = array();
        $that = $this;
        $mock = new MockPlugin(null, true);
        $client->getEventDispatcher()->removeSubscriber($mock);
        $mock->getEventDispatcher()->addListener('mock.request', function(Event $event) use ($that) {
            $that->addMockedRequest($event['request']);
        });

        if ($paths instanceof Response) {
            // A single response instance has been specified, create an array with that instance
            // as the only element for the following loop to work as expected
            $paths = array($paths);
        }

        foreach ((array) $paths as $path) {
            $mock->addResponse($this->getMockResponse($path));
        }

        $client->getEventDispatcher()->addSubscriber($mock);

        return $mock;
    }

    /**
     * Compare HTTP headers and use special markup to filter values
     * A header prefixed with '!' means it must not exist
     * A header prefixed with '_' means it must be ignored
     * A header value of '*' means anything after the * will be ignored
     *
     * @param array $filteredHeaders Array of special headers
     * @param array $actualHeaders Array of headers to check against
     *
     * @return array|bool Returns an array of the differences or FALSE if none
     */
    public function compareHeaders($filteredHeaders, $actualHeaders)
    {
        $comparison = new HeaderComparison();

        return $comparison->compare($filteredHeaders, $actualHeaders);
    }

    /**
     * Case insensitive assertContains
     *
     * @param string $needle Search string
     * @param string $haystack Search this
     * @param string $message Optional failure message
     */
    public function assertContainsIns($needle, $haystack, $message = null)
    {
        $this->assertContains(strtolower($needle), strtolower($haystack), $message);
    }
}
<?php

namespace Guzzle\Tests\Mock;

class MockMulti extends \Guzzle\Http\Curl\CurlMulti
{
    public function getHandle()
    {
        return $this->multiHandle;
    }
}
<?php

namespace Guzzle\Tests\Mock;

class ExceptionMock
{
    public function __construct()
    {
        throw new \Exception('Oh no!');
    }
}
<?php

namespace Guzzle\Tests\Mock;

use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MockObserver implements \Countable, EventSubscriberInterface
{
    public $events = array();

    public static function getSubscribedEvents()
    {
        return array();
    }

    public function has($eventName)
    {
        foreach ($this->events as $event) {
            if ($event->getName() == $eventName) {
                return true;
            }
        }

        return false;
    }

    public function getLastEvent()
    {
        return end($this->events);
    }

    public function count()
    {
        return count($this->events);
    }

    public function getGrouped()
    {
        $events = array();
        foreach ($this->events as $event) {
            if (!isset($events[$event->getName()])) {
                $events[$event->getName()] = array();
            }
            $events[$event->getName()][] = $event;
        }

        return $events;
    }

    public function getData($event, $key, $occurrence = 0)
    {
        $grouped = $this->getGrouped();
        if (isset($grouped[$event])) {
            return $grouped[$event][$occurrence][$key];
        }

        return null;
    }

    public function update(Event $event)
    {
        $this->events[] = $event;
    }
}
<?php

namespace Guzzle\Tests\Mock;

use Guzzle\Plugin\ErrorResponse\ErrorResponseExceptionInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;

class ErrorResponseMock extends \Exception implements ErrorResponseExceptionInterface
{
    public $command;
    public $response;

    public static function fromCommand(CommandInterface $command, Response $response)
    {
        return new self($command, $response);
    }

    public function __construct($command, $response)
    {
        $this->command = $command;
        $this->response = $response;
        $this->message = 'Error from ' . $response;
    }
}
<?php

namespace Guzzle\Tests\Mock;

use Guzzle\Service\Command\ResponseClassInterface;
use Guzzle\Service\Command\OperationCommand;

class CustomResponseModel implements ResponseClassInterface
{
    public $command;

    public static function fromCommand(OperationCommand $command)
    {
        return new self($command);
    }

    public function __construct($command)
    {
        $this->command = $command;
    }
}
<?php

namespace Guzzle\Tests\Mock;

class MockSubject extends \Guzzle\Common\Event\AbstractSubject
{
}
<?php

namespace Guzzle\Tests\Stream;

use Guzzle\Stream\Stream;

/**
 * @group server
 * @covers Guzzle\Stream\Stream
 */
class StreamTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorThrowsExceptionOnInvalidArgument()
    {
        $stream = new Stream(true);
    }

    public function testConstructor()
    {
        $handle = fopen('php://temp', 'r+');
        fwrite($handle, 'data');
        $stream = new Stream($handle);
        $this->assertEquals($handle, $stream->getStream());
        $this->assertTrue($stream->isReadable());
        $this->assertTrue($stream->isWritable());
        $this->assertTrue($stream->isLocal());
        $this->assertTrue($stream->isSeekable());
        $this->assertEquals('PHP', $stream->getWrapper());
        $this->assertEquals('TEMP', $stream->getStreamType());
        $this->assertEquals(4, $stream->getSize());
        $this->assertEquals('php://temp', $stream->getUri());
        $this->assertEquals(array(), $stream->getWrapperData());
        $this->assertFalse($stream->isConsumed());
        unset($stream);
    }

    public function testCanModifyStream()
    {
        $handle1 = fopen('php://temp', 'r+');
        $handle2 = fopen('php://temp', 'r+');
        $stream = new Stream($handle1);
        $this->assertSame($handle1, $stream->getStream());
        $stream->setStream($handle2, 10);
        $this->assertEquals(10, $stream->getSize());
        $this->assertSame($handle2, $stream->getStream());
    }

    public function testStreamClosesHandleOnDestruct()
    {
        $handle = fopen('php://temp', 'r');
        $stream = new Stream($handle);
        unset($stream);
        $this->assertFalse(is_resource($handle));
    }

    public function testConvertsToString()
    {
        $handle = fopen('php://temp', 'w+');
        fwrite($handle, 'data');
        $stream = new Stream($handle);
        $this->assertEquals('data', (string) $stream);
        unset($stream);

        $handle = fopen(__DIR__ . '/../TestData/FileBody.txt', 'r');
        $stream = new Stream($handle);
        $this->assertEquals('', (string) $stream);
        unset($stream);
    }

    public function testConvertsToStringAndRestoresCursorPos()
    {
        $handle = fopen('php://temp', 'w+');
        $stream = new Stream($handle);
        $stream->write('foobazbar');
        $stream->seek(3);
        $this->assertEquals('foobazbar', (string) $stream);
        $this->assertEquals(3, $stream->ftell());
    }

    public function testIsConsumed()
    {
        $handle = fopen('php://temp', 'w+');
        fwrite($handle, 'data');
        $stream = new Stream($handle);
        $this->assertFalse($stream->isConsumed());
        $stream->read(4);
        $this->assertTrue($stream->isConsumed());
    }

    public function testAllowsSettingManualSize()
    {
        $handle = fopen('php://temp', 'w+');
        fwrite($handle, 'data');
        $stream = new Stream($handle);
        $stream->setSize(10);
        $this->assertEquals(10, $stream->getSize());
        unset($stream);
    }

    public function testWrapsStream()
    {
        $handle = fopen('php://temp', 'w+');
        fwrite($handle, 'data');
        $stream = new Stream($handle);
        $this->assertTrue($stream->isSeekable());
        $this->assertTrue($stream->isReadable());
        $this->assertTrue($stream->seek(0));
        $this->assertEquals('da', $stream->read(2));
        $this->assertEquals('ta', $stream->read(2));
        $this->assertTrue($stream->seek(0));
        $this->assertEquals('data', $stream->read(4));
        $stream->write('_appended');
        $stream->seek(0);
        $this->assertEquals('data_appended', $stream->read(13));
    }

    public function testGetSize()
    {
        $size = filesize(__DIR__ . '/../../../bootstrap.php');
        $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r');
        $stream = new Stream($handle);
        $this->assertEquals($handle, $stream->getStream());
        $this->assertEquals($size, $stream->getSize());
        $this->assertEquals($size, $stream->getSize());
        unset($stream);

        // Make sure that false is returned when the size cannot be determined
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $handle = fopen('http://127.0.0.1:' . $this->getServer()->getPort(), 'r');
        $stream = new Stream($handle);
        $this->assertEquals(false, $stream->getSize());
        unset($stream);
    }

    public function testEnsuresSizeIsConsistent()
    {
        $h = fopen('php://temp', 'r+');
        fwrite($h, 'foo');
        $stream = new Stream($h);
        $this->assertEquals(3, $stream->getSize());
        $stream->write('test');
        $this->assertEquals(7, $stream->getSize());
        fclose($h);
    }

    public function testAbstractsMetaData()
    {
        $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r');
        $stream = new Stream($handle);
        $this->assertEquals('plainfile', $stream->getMetaData('wrapper_type'));
        $this->assertEquals(null, $stream->getMetaData('wrapper_data'));
        $this->assertInternalType('array', $stream->getMetaData());
    }

    public function testDoesNotAttemptToWriteToReadonlyStream()
    {
        $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r');
        $stream = new Stream($handle);
        $this->assertEquals(0, $stream->write('foo'));
    }

    public function testProvidesStreamPosition()
    {
        $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r');
        $stream = new Stream($handle);
        $stream->read(2);
        $this->assertSame(ftell($handle), $stream->ftell());
        $this->assertEquals(2, $stream->ftell());
    }

    public function testRewindIsSeekZero()
    {
        $stream = new Stream(fopen('php://temp', 'w+'));
        $stream->write('foobazbar');
        $this->assertTrue($stream->rewind());
        $this->assertEquals('foobazbar', $stream->read(9));
    }

    public function testCanDetachStream()
    {
        $r = fopen('php://temp', 'w+');
        $stream = new Stream($r);
        $stream->detachStream();
        $this->assertNull($stream->getStream());
    }
}
<?php

namespace Guzzle\Tests\Stream;

use Guzzle\Stream\Stream;
use Guzzle\Stream\PhpStreamRequestFactory;
use Guzzle\Http\Client;

/**
 * @group server
 * @covers \Guzzle\Stream\PhpStreamRequestFactory
 */
class PhpStreamRequestFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Client */
    protected $client;

    /** @var PhpStreamRequestFactory */
    protected $factory;

    protected function setUp()
    {
        $this->client = new Client($this->getServer()->getUrl());
        $this->factory = new PhpStreamRequestFactory();
    }

    public function testOpensValidStreamByCreatingContext()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");
        $request = $this->client->get('/');
        $stream = $this->factory->fromRequest($request);
        $this->assertEquals('hi', (string) $stream);
        $headers = $this->factory->getLastResponseHeaders();
        $this->assertContains('HTTP/1.1 200 OK', $headers);
        $this->assertContains('Content-Length: 2', $headers);
        $this->assertSame($headers, $stream->getCustomData('response_headers'));
        $this->assertEquals(2, $stream->getSize());
    }

    public function testOpensValidStreamByPassingContextAndMerging()
    {
        $request = $this->client->get('/');
        $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory')
            ->setMethods(array('createContext', 'createStream'))
            ->getMock();
        $this->factory->expects($this->never())
            ->method('createContext');
        $this->factory->expects($this->once())
            ->method('createStream')
            ->will($this->returnValue(new Stream(fopen('php://temp', 'r'))));

        $context = array('http' => array('method' => 'HEAD', 'ignore_errors' => false));
        $this->factory->fromRequest($request, stream_context_create($context));
        $options = stream_context_get_options($this->readAttribute($this->factory, 'context'));
        $this->assertEquals('HEAD', $options['http']['method']);
        $this->assertFalse($options['http']['ignore_errors']);
        $this->assertEquals('1.1', $options['http']['protocol_version']);
    }

    public function testAppliesProxySettings()
    {
        $request = $this->client->get('/');
        $request->getCurlOptions()->set(CURLOPT_PROXY, 'tcp://foo.com');
        $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory')
            ->setMethods(array('createStream'))
            ->getMock();
        $this->factory->expects($this->once())
            ->method('createStream')
            ->will($this->returnValue(new Stream(fopen('php://temp', 'r'))));
        $this->factory->fromRequest($request);
        $options = stream_context_get_options($this->readAttribute($this->factory, 'context'));
        $this->assertEquals('tcp://foo.com', $options['http']['proxy']);
    }

    public function testAddsPostFields()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");
        $request = $this->client->post('/', array('Foo' => 'Bar'), array('foo' => 'baz bar'));
        $stream = $this->factory->fromRequest($request);
        $this->assertEquals('hi', (string) $stream);

        $headers = $this->factory->getLastResponseHeaders();
        $this->assertContains('HTTP/1.1 200 OK', $headers);
        $this->assertContains('Content-Length: 2', $headers);
        $this->assertSame($headers, $stream->getCustomData('response_headers'));

        $received = $this->getServer()->getReceivedRequests();
        $this->assertEquals(1, count($received));
        $this->assertContains('POST / HTTP/1.1', $received[0]);
        $this->assertContains('host: ', $received[0]);
        $this->assertContains('user-agent: Guzzle/', $received[0]);
        $this->assertContains('foo: Bar', $received[0]);
        $this->assertContains('content-length: 13', $received[0]);
        $this->assertContains('foo=baz%20bar', $received[0]);
    }

    public function testAddsBody()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");
        $request = $this->client->put('/', array('Foo' => 'Bar'), 'Testing...123');
        $stream = $this->factory->fromRequest($request);
        $this->assertEquals('hi', (string) $stream);

        $headers = $this->factory->getLastResponseHeaders();
        $this->assertContains('HTTP/1.1 200 OK', $headers);
        $this->assertContains('Content-Length: 2', $headers);
        $this->assertSame($headers, $stream->getCustomData('response_headers'));

        $received = $this->getServer()->getReceivedRequests();
        $this->assertEquals(1, count($received));
        $this->assertContains('PUT / HTTP/1.1', $received[0]);
        $this->assertContains('host: ', $received[0]);
        $this->assertContains('user-agent: Guzzle/', $received[0]);
        $this->assertContains('foo: Bar', $received[0]);
        $this->assertContains('content-length: 13', $received[0]);
        $this->assertContains('Testing...123', $received[0]);
    }

    public function testCanDisableSslValidation()
    {
        $request = $this->client->get('/');
        $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
        $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory')
            ->setMethods(array('createStream'))
            ->getMock();
        $this->factory->expects($this->once())
            ->method('createStream')
            ->will($this->returnValue(new Stream(fopen('php://temp', 'r'))));
        $this->factory->fromRequest($request);
        $options = stream_context_get_options($this->readAttribute($this->factory, 'context'));
        $this->assertFalse($options['ssl']['verify_peer']);
    }

    public function testUsesSslValidationByDefault()
    {
        $request = $this->client->get('/');
        $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory')
            ->setMethods(array('createStream'))
            ->getMock();
        $this->factory->expects($this->once())
            ->method('createStream')
            ->will($this->returnValue(new Stream(fopen('php://temp', 'r'))));
        $this->factory->fromRequest($request);
        $options = stream_context_get_options($this->readAttribute($this->factory, 'context'));
        $this->assertTrue($options['ssl']['verify_peer']);
        $this->assertSame($request->getCurlOptions()->get(CURLOPT_CAINFO), $options['ssl']['cafile']);
    }

    public function testBasicAuthAddsUserAndPassToUrl()
    {
        $request = $this->client->get('/');
        $request->setAuth('Foo', 'Bar');
        $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory')
            ->setMethods(array('createStream'))
            ->getMock();
        $this->factory->expects($this->once())
            ->method('createStream')
            ->will($this->returnValue(new Stream(fopen('php://temp', 'r'))));
        $this->factory->fromRequest($request);
        $this->assertContains('Foo:Bar@', (string) $this->readAttribute($this->factory, 'url'));
    }

    public function testCanCreateCustomStreamClass()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");
        $request = $this->client->get('/');
        $stream = $this->factory->fromRequest($request, array(), array('stream_class' => 'Guzzle\Http\EntityBody'));
        $this->assertInstanceOf('Guzzle\Http\EntityBody', $stream);
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Common\Event;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Client;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Curl\CurlMulti;
use Guzzle\Http\Curl\CurlMultiInterface;
use Guzzle\Plugin\Backoff\ConstantBackoffStrategy;
use Guzzle\Plugin\Backoff\CurlBackoffStrategy;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * @group server
 * @covers Guzzle\Plugin\Backoff\BackoffPlugin
 */
class BackoffPluginTest extends \Guzzle\Tests\GuzzleTestCase implements EventSubscriberInterface
{
    protected $retried;

    public function setUp()
    {
        $this->retried = false;
    }

    public static function getSubscribedEvents()
    {
        return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry');
    }

    public function onRequestRetry(Event $event)
    {
        $this->retried = $event;
    }

    public function testHasEventList()
    {
        $this->assertEquals(1, count(BackoffPlugin::getAllEvents()));
    }

    public function testCreatesDefaultExponentialBackoffPlugin()
    {
        $plugin = BackoffPlugin::getExponentialBackoff(3, array(204), array(10));
        $this->assertInstanceOf('Guzzle\Plugin\Backoff\BackoffPlugin', $plugin);
        $strategy = $this->readAttribute($plugin, 'strategy');
        $this->assertInstanceOf('Guzzle\Plugin\Backoff\TruncatedBackoffStrategy', $strategy);
        $this->assertEquals(3, $this->readAttribute($strategy, 'max'));
        $strategy = $this->readAttribute($strategy, 'next');
        $this->assertInstanceOf('Guzzle\Plugin\Backoff\HttpBackoffStrategy', $strategy);
        $this->assertEquals(array(204 => true), $this->readAttribute($strategy, 'errorCodes'));
        $strategy = $this->readAttribute($strategy, 'next');
        $this->assertInstanceOf('Guzzle\Plugin\Backoff\CurlBackoffStrategy', $strategy);
        $this->assertEquals(array(10 => true), $this->readAttribute($strategy, 'errorCodes'));
        $strategy = $this->readAttribute($strategy, 'next');
        $this->assertInstanceOf('Guzzle\Plugin\Backoff\ExponentialBackoffStrategy', $strategy);
    }

    public function testDoesNotRetryUnlessStrategyReturnsNumber()
    {
        $request = new Request('GET', 'http://www.example.com');
        $request->setState('transfer');

        $mock = $this->getMockBuilder('Guzzle\Plugin\Backoff\BackoffStrategyInterface')
            ->setMethods(array('getBackoffPeriod'))
            ->getMockForAbstractClass();

        $mock->expects($this->once())
            ->method('getBackoffPeriod')
            ->will($this->returnValue(false));

        $plugin = new BackoffPlugin($mock);
        $plugin->addSubscriber($this);
        $plugin->onRequestSent(new Event(array('request' => $request)));
        $this->assertFalse($this->retried);
    }

    public function testUpdatesRequestForRetry()
    {
        $request = new Request('GET', 'http://www.example.com');
        $request->setState('transfer');
        $response = new Response(500);
        $handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle')->disableOriginalConstructor()->getMock();
        $e = new CurlException();
        $e->setCurlHandle($handle);

        $plugin = new BackoffPlugin(new ConstantBackoffStrategy(10));
        $plugin->addSubscriber($this);

        $event = new Event(array(
            'request'   => $request,
            'response'  => $response,
            'exception' => $e
        ));

        $plugin->onRequestSent($event);
        $this->assertEquals(array(
            'request'  => $request,
            'response' => $response,
            'handle'   => $handle,
            'retries'  => 1,
            'delay'    => 10
        ), $this->readAttribute($this->retried, 'context'));

        $plugin->onRequestSent($event);
        $this->assertEquals(array(
            'request'  => $request,
            'response' => $response,
            'handle'   => $handle,
            'retries'  => 2,
            'delay'    => 10
        ), $this->readAttribute($this->retried, 'context'));
    }

    public function testDoesNothingWhenNotRetryingAndPollingRequest()
    {
        $request = new Request('GET', 'http://www.foo.com');
        $plugin = new BackoffPlugin(new ConstantBackoffStrategy(10));
        $plugin->onRequestPoll(new Event(array('request' => $request)));
    }

    public function testRetriesRequests()
    {
        // Create a script to return several 500 and 503 response codes
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"
        ));

        $plugin = new BackoffPlugin(
            new TruncatedBackoffStrategy(3,
                new HttpBackoffStrategy(null,
                    new CurlBackoffStrategy(null,
                        new ConstantBackoffStrategy(0.05)
                    )
                )
            )
        );

        $client = new Client($this->getServer()->getUrl());
        $client->getEventDispatcher()->addSubscriber($plugin);
        $request = $client->get();
        $request->send();

        // Make sure it eventually completed successfully
        $this->assertEquals(200, $request->getResponse()->getStatusCode());
        $this->assertEquals('data', $request->getResponse()->getBody(true));

        // Check that three requests were made to retry this request
        $this->assertEquals(3, count($this->getServer()->getReceivedRequests(false)));
        $this->assertEquals(2, $request->getParams()->get(BackoffPlugin::RETRY_PARAM));
    }

    /**
     * @expectedException \Guzzle\Http\Exception\ServerErrorResponseException
     */
    public function testFailsOnTruncation()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"
        ));

        $plugin = new BackoffPlugin(
            new TruncatedBackoffStrategy(2,
                new HttpBackoffStrategy(null,
                    new ConstantBackoffStrategy(0.05)
                )
            )
        );

        $client = new Client($this->getServer()->getUrl());
        $client->addSubscriber($plugin);
        $client->get()->send();
    }

    public function testRetriesRequestsWhenInParallel()
    {
        // Create a script to return several 500 and 503 response codes
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"
        ));

        $plugin = new BackoffPlugin(
            new HttpBackoffStrategy(null,
                new TruncatedBackoffStrategy(3,
                    new CurlBackoffStrategy(null,
                        new ConstantBackoffStrategy(0.1)
                    )
                )
            )
        );
        $client = new Client($this->getServer()->getUrl());
        $client->getEventDispatcher()->addSubscriber($plugin);
        $requests = array();
        for ($i = 0; $i < 5; $i++) {
            $requests[] = $client->get();
        }
        $client->send($requests);

        $this->assertEquals(15, count($this->getServer()->getReceivedRequests(false)));
    }

    /**
     * @covers Guzzle\Plugin\Backoff\BackoffPlugin
     * @covers Guzzle\Http\Curl\CurlMulti
     */
    public function testRetriesPooledRequestsUsingDelayAndPollingEvent()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"
        ));
        // Need to sleep for some time ensure that the polling works correctly in the observer
        $plugin = new BackoffPlugin(new HttpBackoffStrategy(null,
            new TruncatedBackoffStrategy(1,
                new ConstantBackoffStrategy(0.5))));

        $client = new Client($this->getServer()->getUrl());
        $client->getEventDispatcher()->addSubscriber($plugin);
        $request = $client->get();
        $request->send();
        // Make sure it eventually completed successfully
        $this->assertEquals('data', $request->getResponse()->getBody(true));
        // Check that two requests were made to retry this request
        $this->assertEquals(2, count($this->getServer()->getReceivedRequests(false)));
    }

    public function testSeeksToBeginningOfRequestBodyWhenRetrying()
    {
        // Create a request with a body
        $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
        $request->setBody('abc');
        // Set the retry time to be something that will be retried always
        $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2);
        // Seek to the end of the stream
        $request->getBody()->seek(3);
        $this->assertEquals('', $request->getBody()->read(1));
        // Create a plugin that does not delay when retrying
        $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0));
        $plugin->onRequestPoll($this->getMockEvent($request));
        // Ensure that the stream was seeked to 0
        $this->assertEquals('a', $request->getBody()->read(1));
    }

    public function testDoesNotSeekOnRequestsWithNoBodyWhenRetrying()
    {
        // Create a request with a body
        $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
        $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2);
        $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0));
        $plugin->onRequestPoll($this->getMockEvent($request));
    }

    protected function getMockEvent(RequestInterface $request)
    {
        // Create a mock curl multi object
        $multi = $this->getMockBuilder('Guzzle\Http\Curl\CurlMulti')
            ->setMethods(array('remove', 'add'))
            ->getMock();

        // Create an event that is expected for the Poll event
        $event = new Event(array(
            'request'    => $request,
            'curl_multi' => $multi
        ));
        $event->setName(CurlMultiInterface::POLLING_REQUEST);

        return $event;
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\ExponentialBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\ExponentialBackoffStrategy
 */
class ExponentialBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWithExponentialDelay()
    {
        $strategy = new ExponentialBackoffStrategy();
        $this->assertFalse($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(1, $strategy->getBackoffPeriod(0, $request));
        $this->assertEquals(2, $strategy->getBackoffPeriod(1, $request));
        $this->assertEquals(4, $strategy->getBackoffPeriod(2, $request));
        $this->assertEquals(8, $strategy->getBackoffPeriod(3, $request));
        $this->assertEquals(16, $strategy->getBackoffPeriod(4, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\LinearBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\LinearBackoffStrategy
 */
class LinearBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWithLinearDelay()
    {
        $strategy = new LinearBackoffStrategy(5);
        $this->assertFalse($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request));
        $this->assertEquals(5, $strategy->getBackoffPeriod(1, $request));
        $this->assertEquals(10, $strategy->getBackoffPeriod(2, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\ReasonPhraseBackoffStrategy;
use Guzzle\Http\Message\Response;

/**
 * @covers Guzzle\Plugin\Backoff\ReasonPhraseBackoffStrategy
 * @covers Guzzle\Plugin\Backoff\AbstractErrorCodeBackoffStrategy
 */
class ReasonPhraseBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWhenCodeMatches()
    {
        $this->assertEmpty(ReasonPhraseBackoffStrategy::getDefaultFailureCodes());
        $strategy = new ReasonPhraseBackoffStrategy(array('Foo', 'Internal Server Error'));
        $this->assertTrue($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $response = new Response(200);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response));
        $response->setStatus(200, 'Foo');
        $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response));
    }

    public function testIgnoresNonErrors()
    {
        $strategy = new ReasonPhraseBackoffStrategy();
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Common\Event;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Plugin\Backoff\BackoffLogger;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestFactory;

/**
 * @covers Guzzle\Plugin\Backoff\BackoffLogger
 */
class BackoffLoggerTest extends \Guzzle\Tests\GuzzleTestCase
{
    public $message;

    public function setUp()
    {
        $this->message = '';
    }

    public function testHasEventList()
    {
        $this->assertEquals(1, count(BackoffLogger::getSubscribedEvents()));
    }

    public function testLogsEvents()
    {
        list($logPlugin, $request, $response) = $this->getMocks();

        $response = $this->getMockBuilder('Guzzle\Http\Message\Response')
            ->setConstructorArgs(array(503))
            ->setMethods(array('getInfo'))
            ->getMock();

        $response->expects($this->any())
            ->method('getInfo')
            ->will($this->returnValue(2));

        $handle = $this->getMockHandle();

        $event = new Event(array(
            'request'  => $request,
            'response' => $response,
            'retries'  => 1,
            'delay'    => 3,
            'handle'   => $handle
        ));

        $logPlugin->onRequestRetry($event);
        $this->assertContains(
            '] PUT http://www.example.com - 503 Service Unavailable - Retries: 1, Delay: 3, Time: 2, 2, cURL: 30 Foo',
            $this->message
        );
    }

    public function testCanSetTemplate()
    {
        $l = new BackoffLogger(new ClosureLogAdapter(function () {}));
        $l->setTemplate('foo');
        $t = $this->readAttribute($l, 'formatter');
        $this->assertEquals('foo', $this->readAttribute($t, 'template'));
    }

    /**
     * @return array
     */
    protected function getMocks()
    {
        $that = $this;
        $logger = new ClosureLogAdapter(function ($message) use ($that) {
            $that->message .= $message . "\n";
        });
        $logPlugin = new BackoffLogger($logger);
        $response = new Response(503);
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com', array(
            'Content-Length' => 3,
            'Foo'            => 'Bar'
        ));

        return array($logPlugin, $request, $response);
    }

    /**
     * @return CurlHandle
     */
    protected function getMockHandle()
    {
        $handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle')
            ->disableOriginalConstructor()
            ->setMethods(array('getError', 'getErrorNo', 'getInfo'))
            ->getMock();

        $handle->expects($this->once())
            ->method('getError')
            ->will($this->returnValue('Foo'));

        $handle->expects($this->once())
            ->method('getErrorNo')
            ->will($this->returnValue(30));

        $handle->expects($this->any())
            ->method('getInfo')
            ->will($this->returnValue(2));

        return $handle;
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Http\Message\Request;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Guzzle\Plugin\Backoff\CallbackBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\AbstractBackoffStrategy
 */
class AbstractBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getMockStrategy()
    {
        return $this->getMockBuilder('Guzzle\Plugin\Backoff\AbstractBackoffStrategy')
            ->setMethods(array('getDelay', 'makesDecision'))
            ->getMockForAbstractClass();
    }

    public function testReturnsZeroWhenNoNextAndGotNull()
    {
        $request = new Request('GET', 'http://www.foo.com');
        $mock = $this->getMockStrategy();
        $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(null));
        $this->assertEquals(0, $mock->getBackoffPeriod(0, $request));
    }

    public function testReturnsFalse()
    {
        $request = new Request('GET', 'http://www.foo.com');
        $mock = $this->getMockStrategy();
        $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(false));
        $this->assertEquals(false, $mock->getBackoffPeriod(0, $request));
    }

    public function testReturnsNextValueWhenNullOrTrue()
    {
        $request = new Request('GET', 'http://www.foo.com');
        $mock = $this->getMockStrategy();
        $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(null));
        $mock->expects($this->any())->method('makesDecision')->will($this->returnValue(false));

        $mock2 = $this->getMockStrategy();
        $mock2->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(10));
        $mock2->expects($this->atLeastOnce())->method('makesDecision')->will($this->returnValue(true));
        $mock->setNext($mock2);

        $this->assertEquals(10, $mock->getBackoffPeriod(0, $request));
    }

    public function testReturnsFalseWhenNullAndNoNext()
    {
        $request = new Request('GET', 'http://www.foo.com');
        $s = new TruncatedBackoffStrategy(2);
        $this->assertFalse($s->getBackoffPeriod(0, $request));
    }

    public function testHasNext()
    {
        $a = new TruncatedBackoffStrategy(2);
        $b = new TruncatedBackoffStrategy(2);
        $a->setNext($b);
        $this->assertSame($b, $a->getNext());
    }

    public function testSkipsOtherDecisionsInChainWhenOneReturnsTrue()
    {
        $a = new CallbackBackoffStrategy(function () { return null; }, true);
        $b = new CallbackBackoffStrategy(function () { return true; }, true);
        $c = new CallbackBackoffStrategy(function () { return null; }, true);
        $d = new CallbackBackoffStrategy(function () { return 10; }, false);
        $a->setNext($b);
        $b->setNext($c);
        $c->setNext($d);
        $this->assertEquals(10, $a->getBackoffPeriod(2, new Request('GET', 'http://www.foo.com')));
    }

    public function testReturnsZeroWhenDecisionMakerReturnsTrueButNoFurtherStrategiesAreInTheChain()
    {
        $a = new CallbackBackoffStrategy(function () { return null; }, true);
        $b = new CallbackBackoffStrategy(function () { return true; }, true);
        $a->setNext($b);
        $this->assertSame(0, $a->getBackoffPeriod(2, new Request('GET', 'http://www.foo.com')));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\CurlBackoffStrategy;
use Guzzle\Http\Exception\CurlException;

/**
 * @covers Guzzle\Plugin\Backoff\CurlBackoffStrategy
 * @covers Guzzle\Plugin\Backoff\AbstractErrorCodeBackoffStrategy
 */
class CurlBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWithExponentialDelay()
    {
        $this->assertNotEmpty(CurlBackoffStrategy::getDefaultFailureCodes());
        $strategy = new CurlBackoffStrategy();
        $this->assertTrue($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $e = new CurlException();
        $e->setError('foo', CURLE_BAD_CALLING_ORDER);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, null, $e));

        foreach (CurlBackoffStrategy::getDefaultFailureCodes() as $code) {
            $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, null, $e->setError('foo', $code)));
        }
    }

    public function testIgnoresNonErrors()
    {
        $strategy = new CurlBackoffStrategy();
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, new Response(200)));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\CallbackBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\CallbackBackoffStrategy
 */
class CallbackBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresIsCallable()
    {
        $strategy = new CallbackBackoffStrategy(new \stdClass(), true);
    }

    public function testRetriesWithCallable()
    {
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $strategy = new CallbackBackoffStrategy(function () { return 10; }, true);
        $this->assertTrue($strategy->makesDecision());
        $this->assertEquals(10, $strategy->getBackoffPeriod(0, $request));
        // Ensure it chains correctly when null is returned
        $strategy = new CallbackBackoffStrategy(function () { return null; }, false);
        $this->assertFalse($strategy->makesDecision());
        $this->assertFalse($strategy->getBackoffPeriod(0, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Http\Message\Response;

/**
 * @covers Guzzle\Plugin\Backoff\HttpBackoffStrategy
 * @covers Guzzle\Plugin\Backoff\AbstractErrorCodeBackoffStrategy
 */
class HttpBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWhenCodeMatches()
    {
        $this->assertNotEmpty(HttpBackoffStrategy::getDefaultFailureCodes());
        $strategy = new HttpBackoffStrategy();
        $this->assertTrue($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);

        $response = new Response(200);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response));
        $response->setStatus(400);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response));

        foreach (HttpBackoffStrategy::getDefaultFailureCodes() as $code) {
            $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response->setStatus($code)));
        }
    }

    public function testAllowsCustomCodes()
    {
        $strategy = new HttpBackoffStrategy(array(204));
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $response = new Response(204);
        $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response));
        $response->setStatus(500);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response));
    }

    public function testIgnoresNonErrors()
    {
        $strategy = new HttpBackoffStrategy();
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Plugin\Backoff\ConstantBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\TruncatedBackoffStrategy
 */
class TruncatedBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWhenLessThanMax()
    {
        $strategy = new TruncatedBackoffStrategy(2);
        $this->assertTrue($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertFalse($strategy->getBackoffPeriod(0, $request));
        $this->assertFalse($strategy->getBackoffPeriod(1, $request));
        $this->assertFalse($strategy->getBackoffPeriod(2, $request));

        $response = new Response(500);
        $strategy->setNext(new HttpBackoffStrategy(null, new ConstantBackoffStrategy(10)));
        $this->assertEquals(10, $strategy->getBackoffPeriod(0, $request, $response));
        $this->assertEquals(10, $strategy->getBackoffPeriod(1, $request, $response));
        $this->assertFalse($strategy->getBackoffPeriod(2, $request, $response));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Backoff;

use Guzzle\Plugin\Backoff\ConstantBackoffStrategy;

/**
 * @covers Guzzle\Plugin\Backoff\ConstantBackoffStrategy
 */
class ConstantBackoffStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRetriesWithConstantDelay()
    {
        $strategy = new ConstantBackoffStrategy(3.5);
        $this->assertFalse($strategy->makesDecision());
        $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false);
        $this->assertEquals(3.5, $strategy->getBackoffPeriod(0, $request));
        $this->assertEquals(3.5, $strategy->getBackoffPeriod(1, $request));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Md5;

use Guzzle\Common\Event;
use Guzzle\Plugin\Md5\CommandContentMd5Plugin;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Client;

/**
 * @covers Guzzle\Plugin\Md5\CommandContentMd5Plugin
 */
class CommandContentMd5PluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getClient()
    {
        $description = new ServiceDescription(array(
            'operations' => array(
                'test' => array(
                    'httpMethod' => 'PUT',
                    'parameters' => array(
                        'ContentMD5' => array(),
                        'Body'       => array(
                            'location' => 'body'
                        )
                    )
                )
            )
        ));

        $client = new Client();
        $client->setDescription($description);

        return $client;
    }

    public function testHasEvents()
    {
        $this->assertNotEmpty(CommandContentMd5Plugin::getSubscribedEvents());
    }

    public function testValidatesMd5WhenParamExists()
    {
        $client = $this->getClient();
        $command = $client->getCommand('test', array(
            'Body'       => 'Foo',
            'ContentMD5' => true
        ));
        $event = new Event(array('command' => $command));
        $request = $command->prepare();
        $plugin = new CommandContentMd5Plugin();
        $plugin->onCommandBeforeSend($event);
        $this->assertEquals('E1bGfXrRY42Ba/uCLdLCXQ==', (string) $request->getHeader('Content-MD5'));
    }

    public function testDoesNothingWhenNoPayloadExists()
    {
        $client = $this->getClient();
        $client->getDescription()->getOperation('test')->setHttpMethod('GET');
        $command = $client->getCommand('test');
        $event = new Event(array('command' => $command));
        $request = $command->prepare();
        $plugin = new CommandContentMd5Plugin();
        $plugin->onCommandBeforeSend($event);
        $this->assertNull($request->getHeader('Content-MD5'));
    }

    public function testAddsValidationToResponsesOfContentMd5()
    {
        $client = $this->getClient();
        $client->getDescription()->getOperation('test')->setHttpMethod('GET');
        $command = $client->getCommand('test', array(
            'ValidateMD5' => true
        ));
        $event = new Event(array('command' => $command));
        $request = $command->prepare();
        $plugin = new CommandContentMd5Plugin();
        $plugin->onCommandBeforeSend($event);
        $listeners = $request->getEventDispatcher()->getListeners('request.complete');
        $this->assertNotEmpty($listeners);
    }

    public function testIgnoresValidationWhenDisabled()
    {
        $client = $this->getClient();
        $client->getDescription()->getOperation('test')->setHttpMethod('GET');
        $command = $client->getCommand('test', array(
            'ValidateMD5' => false
        ));
        $event = new Event(array('command' => $command));
        $request = $command->prepare();
        $plugin = new CommandContentMd5Plugin();
        $plugin->onCommandBeforeSend($event);
        $listeners = $request->getEventDispatcher()->getListeners('request.complete');
        $this->assertEmpty($listeners);
    }
}
<?php

namespace Guzzle\Tests\Plugin\Md5;

use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Md5\Md5ValidatorPlugin;

/**
 * @covers Guzzle\Plugin\Md5\Md5ValidatorPlugin
 */
class Md5ValidatorPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testValidatesMd5()
    {
        $plugin = new Md5ValidatorPlugin();
        $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
        $request->getEventDispatcher()->addSubscriber($plugin);

        $body = 'abc';
        $hash = md5($body);
        $response = new Response(200, array(
            'Content-MD5' => $hash,
            'Content-Length' => 3
        ), 'abc');

        $request->dispatch('request.complete', array(
            'response' => $response
        ));

        // Try again with no Content-MD5
        $response->removeHeader('Content-MD5');
        $request->dispatch('request.complete', array(
            'response' => $response
        ));
    }

    /**
     * @expectedException UnexpectedValueException
     */
    public function testThrowsExceptionOnInvalidMd5()
    {
        $plugin = new Md5ValidatorPlugin();
        $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
        $request->getEventDispatcher()->addSubscriber($plugin);

        $request->dispatch('request.complete', array(
            'response' => new Response(200, array(
                'Content-MD5' => 'foobar',
                'Content-Length' => 3
            ), 'abc')
        ));
    }

    public function testSkipsWhenContentLengthIsTooLarge()
    {
        $plugin = new Md5ValidatorPlugin(false, 1);
        $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
        $request->getEventDispatcher()->addSubscriber($plugin);

        $request->dispatch('request.complete', array(
            'response' => new Response(200, array(
                'Content-MD5' => 'foobar',
                'Content-Length' => 3
            ), 'abc')
        ));
    }

    public function testProperlyValidatesWhenUsingContentEncoding()
    {
        $plugin = new Md5ValidatorPlugin(true);
        $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
        $request->getEventDispatcher()->addSubscriber($plugin);

        // Content-MD5 is the MD5 hash of the canonical content after all
        // content-encoding has been applied.  Because cURL will automatically
        // decompress entity bodies, we need to re-compress it to calculate.
        $body = EntityBody::factory('abc');
        $body->compress();
        $hash = $body->getContentMd5();
        $body->uncompress();

        $response = new Response(200, array(
            'Content-MD5' => $hash,
            'Content-Encoding' => 'gzip'
        ), 'abc');
        $request->dispatch('request.complete', array(
            'response' => $response
        ));
        $this->assertEquals('abc', $response->getBody(true));

        // Try again with an unknown encoding
        $response = new Response(200, array(
            'Content-MD5' => $hash,
            'Content-Encoding' => 'foobar'
        ), 'abc');
        $request->dispatch('request.complete', array(
            'response' => $response
        ));

        // Try again with compress
        $body->compress('bzip2.compress');
        $response = new Response(200, array(
            'Content-MD5' => $body->getContentMd5(),
            'Content-Encoding' => 'compress'
        ), 'abc');
        $request->dispatch('request.complete', array(
            'response' => $response
        ));

        // Try again with encoding and disabled content-encoding checks
        $request->getEventDispatcher()->removeSubscriber($plugin);
        $plugin = new Md5ValidatorPlugin(false);
        $request->getEventDispatcher()->addSubscriber($plugin);
        $request->dispatch('request.complete', array(
            'response' => $response
        ));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Oauth;

use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\QueryAggregator\CommaAggregator;
use Guzzle\Plugin\Oauth\OauthPlugin;
use Guzzle\Common\Event;

/**
 * @covers Guzzle\Plugin\Oauth\OauthPlugin
 */
class OauthPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    const TIMESTAMP = '1327274290';
    const NONCE = 'e7aa11195ca58349bec8b5ebe351d3497eb9e603';

    protected $config = array(
        'consumer_key'    => 'foo',
        'consumer_secret' => 'bar',
        'token'           => 'count',
        'token_secret'    => 'dracula'
    );

    protected function getRequest()
    {
        return RequestFactory::getInstance()->create('POST', 'http://www.test.com/path?a=b&c=d', null, array(
            'e' => 'f'
        ));
    }

    public function testSubscribesToEvents()
    {
        $events = OauthPlugin::getSubscribedEvents();
        $this->assertArrayHasKey('request.before_send', $events);
    }

    public function testAcceptsConfigurationData()
    {
        $p = new OauthPlugin($this->config);

        // Access the config object
        $class = new \ReflectionClass($p);
        $property = $class->getProperty('config');
        $property->setAccessible(true);
        $config = $property->getValue($p);

        $this->assertEquals('foo', $config['consumer_key']);
        $this->assertEquals('bar', $config['consumer_secret']);
        $this->assertEquals('count', $config['token']);
        $this->assertEquals('dracula', $config['token_secret']);
        $this->assertEquals('1.0', $config['version']);
        $this->assertEquals('HMAC-SHA1', $config['signature_method']);
        $this->assertEquals('header', $config['request_method']);
    }

    public function testCreatesStringToSignFromPostRequest()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $signString = $p->getStringToSign($request, self::TIMESTAMP, self::NONCE);

        $this->assertContains('&e=f', rawurldecode($signString));

        $expectedSignString =
            // Method and URL
            'POST&http%3A%2F%2Fwww.test.com%2Fpath' .
            // Sorted parameters from query string and body
            '&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' .
            '%26oauth_nonce%3De7aa11195ca58349bec8b5ebe351d3497eb9e603%26' .
            'oauth_signature_method%3DHMAC-SHA1' .
            '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0';

        $this->assertEquals($expectedSignString, $signString);
    }

    public function testCreatesStringToSignIgnoringPostFields()
    {
        $config = $this->config;
        $config['disable_post_params'] = true;
        $p = new OauthPlugin($config);
        $request = $this->getRequest();
        $sts = rawurldecode($p->getStringToSign($request, self::TIMESTAMP, self::NONCE));
        $this->assertNotContains('&e=f', $sts);
    }

    public function testCreatesStringToSignFromPostRequestWithCustomContentType()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $request->setHeader('Content-Type', 'Foo');
        $this->assertEquals(
            // Method and URL
            'POST&http%3A%2F%2Fwww.test.com%2Fpath' .
            // Sorted parameters from query string and body
            '&a%3Db%26c%3Dd%26oauth_consumer_key%3Dfoo' .
            '%26oauth_nonce%3D'. self::NONCE .'%26' .
            'oauth_signature_method%3DHMAC-SHA1' .
            '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0',
            $p->getStringToSign($request, self::TIMESTAMP, self::NONCE)
        );
    }

    /**
     * @depends testCreatesStringToSignFromPostRequest
     */
    public function testConvertsBooleansToStrings()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $request->getQuery()->set('a', true);
        $request->getQuery()->set('c', false);
        $this->assertContains('&a%3Dtrue%26c%3Dfalse', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE));
    }

    public function testCreatesStringToSignFromPostRequestWithNullValues()
    {
        $config = array(
            'consumer_key'    => 'foo',
            'consumer_secret' => 'bar',
            'token'           => null,
            'token_secret'    => 'dracula'
        );

        $p          = new OauthPlugin($config);
        $request    = $this->getRequest();
        $signString = $p->getStringToSign($request, self::TIMESTAMP, self::NONCE);

        $this->assertContains('&e=f', rawurldecode($signString));

        $expectedSignString = // Method and URL
                'POST&http%3A%2F%2Fwww.test.com%2Fpath' .
                // Sorted parameters from query string and body
                '&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' .
                '%26oauth_nonce%3De7aa11195ca58349bec8b5ebe351d3497eb9e603%26' .
                'oauth_signature_method%3DHMAC-SHA1' .
                '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_version%3D1.0';

        $this->assertEquals($expectedSignString, $signString);
    }

    /**
     * @depends testCreatesStringToSignFromPostRequest
     */
    public function testMultiDimensionalArray()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $request->getQuery()->set('a', array('b' => array('e' => 'f', 'c' => 'd')));
        $this->assertContains('a%255Bb%255D%255Bc%255D%3Dd%26a%255Bb%255D%255Be%255D%3Df%26c%3Dd%26e%3Df%26', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE));
    }

    /**
     * @depends testMultiDimensionalArray
     */
    public function testMultiDimensionalArrayWithNonDefaultQueryAggregator()
    {
        $p = new OauthPlugin($this->config);
        $request = $this->getRequest();
        $aggregator = new CommaAggregator();
        $query = $request->getQuery()->setAggregator($aggregator)
            ->set('g', array('h', 'i', 'j'))
            ->set('k', array('l'))
            ->set('m', array('n', 'o'));
        $this->assertContains('a%3Db%26c%3Dd%26e%3Df%26g%3Dh%2Ci%2Cj%26k%3Dl%26m%3Dn%2Co', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE));
    }

    /**
     * @depends testCreatesStringToSignFromPostRequest
     */
    public function testSignsStrings()
    {
        $p = new OauthPlugin(array_merge($this->config, array(
            'signature_callback' => function($string, $key) {
                return "_{$string}|{$key}_";
            }
        )));
        $request = $this->getRequest();
        $sig = $p->getSignature($request, self::TIMESTAMP, self::NONCE);
        $this->assertEquals(
            '_POST&http%3A%2F%2Fwww.test.com%2Fpath&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' .
            '%26oauth_nonce%3D'. self::NONCE .'%26oauth_signature_method%3DHMAC-SHA1' .
            '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0|' .
            'bar&dracula_',
            base64_decode($sig)
        );
    }

    /**
     * Test that the Oauth is signed correctly and that extra strings haven't been added
     * to the authorization header.
     */
    public function testSignsOauthRequests()
    {
        $p = new OauthPlugin($this->config);
        $event = new Event(array(
            'request' => $this->getRequest(),
            'timestamp' => self::TIMESTAMP
        ));
        $params = $p->onRequestBeforeSend($event);

        $this->assertTrue($event['request']->hasHeader('Authorization'));

        $authorizationHeader = (string)$event['request']->getHeader('Authorization');

        $this->assertStringStartsWith('OAuth ', $authorizationHeader);

        $stringsToCheck = array(
            'oauth_consumer_key="foo"',
            'oauth_nonce="'.urlencode($params['oauth_nonce']).'"',
            'oauth_signature="'.urlencode($params['oauth_signature']).'"',
            'oauth_signature_method="HMAC-SHA1"',
            'oauth_timestamp="' . self::TIMESTAMP . '"',
            'oauth_token="count"',
            'oauth_version="1.0"',
        );

        $totalLength = strlen('OAuth ');

        //Separator is not used before first parameter.
        $separator = '';

        foreach ($stringsToCheck as $stringToCheck) {
            $this->assertContains($stringToCheck, $authorizationHeader);
            $totalLength += strlen($separator);
            $totalLength += strlen($stringToCheck);
            $separator = ', ';
        }

        // Technically this test is not universally valid. It would be allowable to have extra \n characters
        // in the Authorization header. However Guzzle does not do this, so we just perform a simple check
        // on length to validate the Authorization header is composed of only the strings above.
        $this->assertEquals($totalLength, strlen($authorizationHeader), 'Authorization has extra characters i.e. contains extra elements compared to stringsToCheck.');
    }

    public function testSignsOauthQueryStringRequest()
    {
        $config = array_merge(
            $this->config,
            array('request_method' => OauthPlugin::REQUEST_METHOD_QUERY)
        );

        $p = new OauthPlugin($config);
        $event = new Event(array(
            'request' => $this->getRequest(),
            'timestamp' => self::TIMESTAMP
        ));
        $params = $p->onRequestBeforeSend($event);

        $this->assertFalse($event['request']->hasHeader('Authorization'));

        $stringsToCheck = array(
            'a=b',
            'c=d',
            'oauth_consumer_key=foo',
            'oauth_nonce='.urlencode($params['oauth_nonce']),
            'oauth_signature='.urlencode($params['oauth_signature']),
            'oauth_signature_method=HMAC-SHA1',
            'oauth_timestamp='.self::TIMESTAMP,
            'oauth_token=count',
            'oauth_version=1.0',
        );

        $queryString = (string) $event['request']->getQuery();

        $totalLength = strlen('?');

        //Separator is not used before first parameter.
        $separator = '';

        foreach ($stringsToCheck as $stringToCheck) {
            $this->assertContains($stringToCheck, $queryString);
            $totalLength += strlen($separator);
            $totalLength += strlen($stringToCheck);
            $separator = '&';
        }

        // Removes the last query string separator '&'
        $totalLength -= 1;

        $this->assertEquals($totalLength, strlen($queryString), 'Query string has extra characters i.e. contains extra elements compared to stringsToCheck.');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidArgumentExceptionOnMethodError()
    {
        $config = array_merge(
            $this->config,
            array('request_method' => 'FakeMethod')
        );

        $p = new OauthPlugin($config);
        $event = new Event(array(
            'request' => $this->getRequest(),
            'timestamp' => self::TIMESTAMP
        ));

        $p->onRequestBeforeSend($event);
    }

    public function testDoesNotAddFalseyValuesToAuthorization()
    {
        unset($this->config['token']);
        $p = new OauthPlugin($this->config);
        $event = new Event(array('request' => $this->getRequest(), 'timestamp' => self::TIMESTAMP));
        $p->onRequestBeforeSend($event);
        $this->assertTrue($event['request']->hasHeader('Authorization'));
        $this->assertNotContains('oauth_token=', (string) $event['request']->getHeader('Authorization'));
    }

    public function testOptionalOauthParametersAreNotAutomaticallyAdded()
    {
        // The only required Oauth parameters are the consumer key and secret. That is enough credentials
        // for signing oauth requests.
         $config = array(
            'consumer_key'    => 'foo',
            'consumer_secret' => 'bar',
        );

        $plugin = new OauthPlugin($config);
        $event = new Event(array(
            'request' => $this->getRequest(),
            'timestamp' => self::TIMESTAMP
        ));

        $timestamp = $plugin->getTimestamp($event);
        $request = $event['request'];
        $nonce = $plugin->generateNonce($request);

        $paramsToSign = $plugin->getParamsToSign($request, $timestamp, $nonce);

        $optionalParams = array(
            'callback'      => 'oauth_callback',
            'token'         => 'oauth_token',
            'verifier'      => 'oauth_verifier',
            'token_secret'  => 'token_secret'
        );

        foreach ($optionalParams as $optionName => $oauthName) {
            $this->assertArrayNotHasKey($oauthName, $paramsToSign, "Optional Oauth param '$oauthName' was not set via config variable '$optionName', but it is listed in getParamsToSign().");
        }
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Doctrine\Common\Cache\ArrayCache;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\CachePlugin;
use Guzzle\Plugin\Cache\CallbackCanCacheStrategy;

/**
 * @covers Guzzle\Plugin\Cache\CallbackCanCacheStrategy
 */
class CallbackCanCacheStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testConstructorEnsuresCallbackIsCallable()
    {
        $p = new CallbackCanCacheStrategy(new \stdClass());
    }

    public function testUsesCallback()
    {
        $c = new CallbackCanCacheStrategy(function ($request) { return true; });
        $this->assertTrue($c->canCacheRequest(new Request('DELETE', 'http://www.foo.com')));
    }

    /**
     * The following is a bit of an integration test to ensure that the CachePlugin honors a
     * custom can cache strategy.
     */
    public function testIntegrationWithCachePlugin()
    {
        $c = new CallbackCanCacheStrategy(
            function ($request) { return true; },
            function ($response) { return true; }
        );

        // Make a request and response that have no business being cached
        $request = new Request('DELETE', 'http://www.foo.com');
        $response = Response::fromMessage(
            "HTTP/1.1 200 OK\r\n"
            . "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"
            . "Last-Modified: Wed, 09 Jan 2013 08:48:53 GMT\r\n"
            . "Content-Length: 2\r\n"
            . "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n\r\n"
            . "hi"
        );

        $this->assertTrue($c->canCacheRequest($request));
        $this->assertTrue($c->canCacheResponse($response));

        $s = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultCacheStorage')
            ->setConstructorArgs(array(new DoctrineCacheAdapter(new ArrayCache())))
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();

        $s->expects($this->once())
            ->method('fetch')
            ->will($this->returnValue($response));

        $plugin = new CachePlugin(array('can_cache' => $c, 'storage' => $s));
        $plugin->onRequestBeforeSend(new Event(array('request' => $request)));

        $this->assertEquals(200, $request->getResponse()->getStatusCode());
        $this->assertEquals('hi', $request->getResponse()->getBody(true));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\DefaultCanCacheStrategy;

/**
 * @covers Guzzle\Plugin\Cache\DefaultCanCacheStrategy
 */
class DefaultCanCacheStrategyTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testReturnsRequestcanCacheRequest()
    {
        $strategy = new DefaultCanCacheStrategy();
        $request = new Request('GET', 'http://foo.com');
        $this->assertTrue($strategy->canCacheRequest($request));
    }

    public function testDoesNotCacheNoStore()
    {
        $strategy = new DefaultCanCacheStrategy();
        $request = new Request('GET', 'http://foo.com', array('cache-control' => 'no-store'));
        $this->assertFalse($strategy->canCacheRequest($request));
    }

    public function testCanCacheResponse()
    {
        $response = $this->getMockBuilder('Guzzle\Http\Message\Response')
            ->setMethods(array('canCache'))
            ->setConstructorArgs(array(200))
            ->getMock();
        $response->expects($this->once())
            ->method('canCache')
            ->will($this->returnValue(true));
        $strategy = new DefaultCanCacheStrategy();
        $this->assertTrue($strategy->canCacheResponse($response));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Common\Event;
use Guzzle\Common\Version;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\CachePlugin;
use Guzzle\Plugin\Cache\DefaultCacheStorage;
use Guzzle\Plugin\Cache\CallbackCanCacheStrategy;
use Doctrine\Common\Cache\ArrayCache;

/**
 * @group server
 * @covers Guzzle\Plugin\Cache\CachePlugin
 * @covers Guzzle\Plugin\Cache\DefaultRevalidation
 */
class CachePluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testAddsDefaultStorage()
    {
        $plugin = new CachePlugin();
        $this->assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage'));
    }

    public function testAddsDefaultCollaborators()
    {
        $this->assertNotEmpty(CachePlugin::getSubscribedEvents());
        $plugin = new CachePlugin(array(
            'storage' => $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass()
        ));
        $this->assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage'));
        $this->assertInstanceOf(
            'Guzzle\Plugin\Cache\CanCacheStrategyInterface',
            $this->readAttribute($plugin, 'canCache')
        );
        $this->assertInstanceOf(
            'Guzzle\Plugin\Cache\RevalidationInterface',
            $this->readAttribute($plugin, 'revalidation')
        );
    }

    public function testAddsCallbackCollaborators()
    {
        $this->assertNotEmpty(CachePlugin::getSubscribedEvents());
        $plugin = new CachePlugin(array('can_cache' => function () {}));
        $this->assertInstanceOf(
            'Guzzle\Plugin\Cache\CallbackCanCacheStrategy',
            $this->readAttribute($plugin, 'canCache')
        );
    }

    public function testCanPassCacheAsOnlyArgumentToConstructor()
    {
        $p = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache()));
        $p = new CachePlugin(new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache())));
    }

    public function testUsesCreatedCacheStorage()
    {
        $plugin = new CachePlugin(array(
            'adapter' => $this->getMockBuilder('Guzzle\Cache\CacheAdapterInterface')->getMockForAbstractClass()
        ));
        $this->assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage'));
    }

    public function testUsesProvidedOptions()
    {
        $can = $this->getMockBuilder('Guzzle\Plugin\Cache\CanCacheStrategyInterface')->getMockForAbstractClass();
        $revalidate = $this->getMockBuilder('Guzzle\Plugin\Cache\RevalidationInterface')->getMockForAbstractClass();
        $plugin = new CachePlugin(array(
            'storage' => $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass(),
            'can_cache' => $can,
            'revalidation' => $revalidate
        ));
        $this->assertSame($can, $this->readAttribute($plugin, 'canCache'));
        $this->assertSame($revalidate, $this->readAttribute($plugin, 'revalidation'));
    }

    public function satisfyProvider()
    {
        $req1 = new Request('GET', 'http://foo.com', array('Cache-Control' => 'no-cache'));

        return array(
            // The response is too old to satisfy the request
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-age=20')), new Response(200, array('Age' => 100)), false, false),
            // The response cannot satisfy the request because it is stale
            array(new Request('GET', 'http://foo.com'), new Response(200, array('Cache-Control' => 'max-age=10', 'Age' => 100)), false, false),
            // Allows the expired response to satisfy the request because of the max-stale
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale=15')), new Response(200, array('Cache-Control' => 'max-age=90', 'Age' => 100)), true, false),
            // Max stale is > than the allowed staleness
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale=5')), new Response(200, array('Cache-Control' => 'max-age=90', 'Age' => 100)), false, false),
            // Performs cache revalidation
            array($req1, new Response(200), true, true),
            // Performs revalidation due to ETag on the response and no cache-control on the request
            array(new Request('GET', 'http://foo.com'), new Response(200, array(
                'ETag' => 'ABC',
                'Expires' => date('c', strtotime('+1 year'))
            )), true, true),
        );
    }

    /**
     * @dataProvider satisfyProvider
     */
    public function testChecksIfResponseCanSatisfyRequest($request, $response, $can, $revalidates)
    {
        $didRevalidate = false;
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass();
        $revalidate = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultRevalidation')
            ->setMethods(array('revalidate'))
            ->setConstructorArgs(array($storage))
            ->getMockForAbstractClass();

        $revalidate->expects($this->any())
            ->method('revalidate')
            ->will($this->returnCallback(function () use (&$didRevalidate) {
                $didRevalidate = true;
                return true;
            }));

        $plugin = new CachePlugin(array(
            'storage' => $storage,
            'revalidation' => $revalidate
        ));

        $this->assertEquals($can, $plugin->canResponseSatisfyRequest($request, $response));
        $this->assertEquals($didRevalidate, $revalidates);
    }

    public function satisfyFailedProvider()
    {
        return array(
            // Neither has stale-if-error
            array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100)), false),
            // Request has stale-if-error
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), true),
            // Request has valid stale-if-error
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=50')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), true),
            // Request has expired stale-if-error
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=20')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), false),
            // Response has permanent stale-if-error
            array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error', )), true),
            // Response has valid stale-if-error
            array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=50')), true),
            // Response has expired stale-if-error
            array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=20')), false),
            // Request has valid stale-if-error but response does not
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=50')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=20')), false),
            // Response has valid stale-if-error but request does not
            array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=20')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=50')), false),
        );
    }

    /**
     * @dataProvider satisfyFailedProvider
     */
    public function testChecksIfResponseCanSatisfyFailedRequest($request, $response, $can)
    {
        $plugin = new CachePlugin();

        $this->assertEquals($can, $plugin->canResponseSatisfyFailedRequest($request, $response));
    }

    public function testDoesNothingWhenRequestIsNotCacheable()
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();
        $storage->expects($this->never())->method('fetch');

        $plugin = new CachePlugin(array(
            'storage'   => $storage,
            'can_cache' => new CallbackCanCacheStrategy(function () { return false; })
        ));

        $plugin->onRequestBeforeSend(new Event(array(
            'request' => new Request('GET', 'http://foo.com')
        )));
    }

    public function satisfiableProvider()
    {
        $date = new \DateTime('-10 seconds');

        return array(
            // Fresh response
            array(new Response(200, array(), 'foo')),
            // Stale response
            array(new Response(200, array('Date' => $date->format('c'), 'Cache-Control' => 'max-age=5'), 'foo'))
        );
    }

    /**
     * @dataProvider satisfiableProvider
     */
    public function testInjectsSatisfiableResponses($response)
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();

        $storage->expects($this->once())->method('fetch')->will($this->returnValue($response));
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale'));
        $plugin->onRequestBeforeSend(new Event(array('request' => $request)));
        $plugin->onRequestSent(new Event(array('request' => $request, 'response' => $request->getResponse())));
        $this->assertEquals($response->getStatusCode(), $request->getResponse()->getStatusCode());
        $this->assertEquals((string) $response->getBody(), (string) $request->getResponse()->getBody());
        $this->assertTrue($request->getResponse()->hasHeader('Age'));
        if ($request->getResponse()->isFresh() === false) {
            $this->assertContains('110', (string) $request->getResponse()->getHeader('Warning'));
        }
        $this->assertSame(
            sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION),
            (string) $request->getHeader('Via')
        );
        $this->assertSame(
            sprintf('%s GuzzleCache/%s',$request->getProtocolVersion(), Version::VERSION),
            (string) $request->getResponse()->getHeader('Via')
        );
        $this->assertTrue($request->getParams()->get('cache.lookup'));
        $this->assertTrue($request->getParams()->get('cache.hit'));
        $this->assertTrue($request->getResponse()->hasHeader('X-Cache-Lookup'));
        $this->assertTrue($request->getResponse()->hasHeader('X-Cache'));
        $this->assertEquals('HIT from GuzzleCache', (string) $request->getResponse()->getHeader('X-Cache'));
        $this->assertEquals('HIT from GuzzleCache', (string) $request->getResponse()->getHeader('X-Cache-Lookup'));
    }

    public function satisfiableOnErrorProvider()
    {
        $date = new \DateTime('-10 seconds');
        return array(
            array(
                new Response(200, array(
                    'Date' => $date->format('c'),
                    'Cache-Control' => 'max-age=5, stale-if-error'
                ), 'foo'),
            )
        );
    }

    /**
     * @dataProvider satisfiableOnErrorProvider
     */
    public function testInjectsSatisfiableResponsesOnError($cacheResponse)
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();
        $storage->expects($this->exactly(2))->method('fetch')->will($this->returnValue($cacheResponse));
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale'));
        $plugin->onRequestBeforeSend(new Event(array('request' => $request)));
        $plugin->onRequestError(
            $event = new Event(array(
                'request' => $request,
                'response' => $request->getResponse(),
            ))
        );
        $response = $event['response'];
        $this->assertEquals($cacheResponse->getStatusCode(), $response->getStatusCode());
        $this->assertEquals((string) $cacheResponse->getBody(), (string) $response->getBody());
        $this->assertTrue($response->hasHeader('Age'));
        if ($response->isFresh() === false) {
            $this->assertContains('110', (string) $response->getHeader('Warning'));
        }
        $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $request->getHeader('Via'));
        $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $response->getHeader('Via'));
        $this->assertTrue($request->getParams()->get('cache.lookup'));
        $this->assertSame('error', $request->getParams()->get('cache.hit'));
        $this->assertTrue($response->hasHeader('X-Cache-Lookup'));
        $this->assertTrue($response->hasHeader('X-Cache'));
        $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup'));
        $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache'));
    }

    /**
     * @dataProvider satisfiableOnErrorProvider
     */
    public function testInjectsSatisfiableResponsesOnException($cacheResponse)
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();
        $storage->expects($this->exactly(2))->method('fetch')->will($this->returnValue($cacheResponse));
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale'));
        $plugin->onRequestBeforeSend(new Event(array(
            'request' => $request
        )));
        $plugin->onRequestException(
            new Event(array(
                'request' => $request,
                'response' => $request->getResponse(),
                'exception' => $this->getMock('Guzzle\Http\Exception\CurlException'),
            ))
        );
        $plugin->onRequestSent(
            new Event(array(
                'request' => $request,
                'response' => $response = $request->getResponse(),
            ))
        );
        $this->assertEquals($cacheResponse->getStatusCode(), $response->getStatusCode());
        $this->assertEquals((string) $cacheResponse->getBody(), (string) $response->getBody());
        $this->assertTrue($response->hasHeader('Age'));
        if ($response->isFresh() === false) {
            $this->assertContains('110', (string) $response->getHeader('Warning'));
        }
        $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $request->getHeader('Via'));
        $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $response->getHeader('Via'));
        $this->assertTrue($request->getParams()->get('cache.lookup'));
        $this->assertSame('error', $request->getParams()->get('cache.hit'));
        $this->assertTrue($response->hasHeader('X-Cache-Lookup'));
        $this->assertTrue($response->hasHeader('X-Cache'));
        $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup'));
        $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache'));
    }

    public function unsatisfiableOnErrorProvider()
    {
        $date = new \DateTime('-10 seconds');

        return array(
            // no-store on request
            array(
                false,
                array('Cache-Control' => 'no-store'),
                new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error'), 'foo'),
            ),
            // request expired
            array(
                true,
                array('Cache-Control' => 'stale-if-error=4'),
                new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error'), 'foo'),
            ),
            // response expired
            array(
                true,
                array('Cache-Control' => 'stale-if-error'),
                new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error=4'), 'foo'),
            ),
        );
    }

    /**
     * @dataProvider unsatisfiableOnErrorProvider
     */
    public function testDoesNotInjectUnsatisfiableResponsesOnError($requestCanCache, $requestHeaders, $cacheResponse)
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();
        $storage->expects($this->exactly($requestCanCache ? 2 : 0))->method('fetch')->will($this->returnValue($cacheResponse));
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', $requestHeaders);
        $plugin->onRequestBeforeSend(new Event(array(
            'request' => $request
        )));
        $plugin->onRequestError(
            $event = new Event(array(
                'request' => $request,
                'response' => $response = $request->getResponse(),
            ))
        );

        $this->assertSame($response, $event['response']);
    }

    /**
     * @dataProvider unsatisfiableOnErrorProvider
     */
    public function testDoesNotInjectUnsatisfiableResponsesOnException($requestCanCache, $requestHeaders, $responseParts)
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('fetch'))
            ->getMockForAbstractClass();
        $storage->expects($this->exactly($requestCanCache ? 2 : 0))->method('fetch')->will($this->returnValue($responseParts));
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', $requestHeaders);
        $plugin->onRequestBeforeSend(new Event(array(
            'request' => $request
        )));
        $plugin->onRequestException(
            $event = new Event(array(
                'request' => $request,
                'response' => $response = $request->getResponse(),
                'exception' => $this->getMock('Guzzle\Http\Exception\CurlException'),
            ))
        );

        $this->assertSame($response, $request->getResponse());
    }

    public function testCachesResponsesWhenCacheable()
    {
        $cache = new ArrayCache();
        $plugin = new CachePlugin($cache);

        $request = new Request('GET', 'http://foo.com');
        $response = new Response(200, array(), 'Foo');
        $plugin->onRequestBeforeSend(new Event(array(
            'request' => $request
        )));
        $plugin->onRequestSent(new Event(array(
            'request'  => $request,
            'response' => $response
        )));
        $data = $this->readAttribute($cache, 'data');
        $this->assertNotEmpty($data);
    }

    public function testPurgesRequests()
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('purge'))
            ->getMockForAbstractClass();
        $storage->expects($this->atLeastOnce())->method('purge');
        $plugin = new CachePlugin(array('storage' => $storage));
        $request = new Request('GET', 'http://foo.com', array('X-Foo' => 'Bar'));
        $plugin->purge($request);
    }

    public function testAutoPurgesRequests()
    {
        $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')
            ->setMethods(array('purge'))
            ->getMockForAbstractClass();
        $storage->expects($this->atLeastOnce())->method('purge');
        $plugin = new CachePlugin(array('storage' => $storage, 'auto_purge' => true));
        $client = new Client();
        $request = $client->put('http://foo.com', array('X-Foo' => 'Bar'));
        $request->addSubscriber($plugin);
        $request->setResponse(new Response(200), true);
        $request->send();
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\DenyRevalidation;

/**
 * @covers Guzzle\Plugin\Cache\DenyRevalidation
 */
class DenyRevalidationTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDeniesRequestRevalidation()
    {
        $deny = new DenyRevalidation();
        $this->assertFalse($deny->revalidate(new Request('GET', 'http://foo.com'), new Response(200)));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\SkipRevalidation;

/**
 * @covers Guzzle\Plugin\Cache\SkipRevalidation
 */
class SkipRevalidationTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testSkipsRequestRevalidation()
    {
        $skip = new SkipRevalidation();
        $this->assertTrue($skip->revalidate(new Request('GET', 'http://foo.com'), new Response(200)));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Plugin\Cache\CachePlugin;
use Guzzle\Cache\DoctrineCacheAdapter;
use Doctrine\Common\Cache\ArrayCache;
use Guzzle\Plugin\Cache\DefaultCacheStorage;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Tests\Http\Server;

/**
 * @covers Guzzle\Plugin\Cache\DefaultRevalidation
 * @group server
 */
class DefaultRevalidationTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getHttpDate($time)
    {
        return gmdate(ClientInterface::HTTP_DATE, strtotime($time));
    }

    /**
     * Data provider to test cache revalidation
     *
     * @return array
     */
    public function cacheRevalidationDataProvider()
    {
        return array(
            // Forces revalidation that passes
            array(
                true,
                "Pragma: no-cache\r\n\r\n",
                "HTTP/1.1 200 OK\r\nDate: " . $this->getHttpDate('-100 hours') . "\r\nContent-Length: 4\r\n\r\nData",
                "HTTP/1.1 304 NOT MODIFIED\r\nCache-Control: max-age=2000000\r\nContent-Length: 0\r\n\r\n",
            ),
            // Forces revalidation that overwrites what is in cache
            array(
                false,
                "\r\n",
                "HTTP/1.1 200 OK\r\nCache-Control: must-revalidate, no-cache\r\nDate: " . $this->getHttpDate('-10 hours') . "\r\nContent-Length: 4\r\n\r\nData",
                "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nDatas",
                "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nDate: " . $this->getHttpDate('now') . "\r\n\r\nDatas"
            ),
            // Throws an exception during revalidation
            array(
                false,
                "\r\n",
                "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . $this->getHttpDate('-3 hours') . "\r\n\r\nData",
                "HTTP/1.1 500 INTERNAL SERVER ERROR\r\nContent-Length: 0\r\n\r\n"
            ),
            // ETag mismatch
            array(
                false,
                "\r\n",
                "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nETag: \"123\"\r\nDate: " . $this->getHttpDate('-10 hours') . "\r\n\r\nData",
                "HTTP/1.1 304 NOT MODIFIED\r\nETag: \"123456\"\r\n\r\n",
            ),
        );
    }

    /**
     * @dataProvider cacheRevalidationDataProvider
     */
    public function testRevalidatesResponsesAgainstOriginServer($can, $request, $response, $validate = null, $result = null)
    {
        // Send some responses to the test server for cache validation
        $server = $this->getServer();
        $server->flush();

        if ($validate) {
            $server->enqueue($validate);
        }

        $request = RequestFactory::getInstance()->fromMessage("GET / HTTP/1.1\r\nHost: 127.0.0.1:" . $server->getPort() . "\r\n" . $request);
        $response = Response::fromMessage($response);
        $request->setClient(new Client());

        $plugin = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache()));
        $this->assertEquals(
            $can,
            $plugin->canResponseSatisfyRequest($request, $response),
            '-> ' . $request . "\n" . $response
        );

        if ($result) {
            $result = Response::fromMessage($result);
            $result->removeHeader('Date');
            $request->getResponse()->removeHeader('Date');
            $request->getResponse()->removeHeader('Connection');
            // Get rid of dates
            $this->assertEquals((string) $result, (string) $request->getResponse());
        }

        if ($validate) {
            $this->assertEquals(1, count($server->getReceivedRequests()));
        }
    }

    public function testHandles404RevalidationResponses()
    {
        $request = new Request('GET', 'http://foo.com');
        $request->setClient(new Client());
        $badResponse = new Response(404, array(), 'Oh no!');
        $badRequest = clone $request;
        $badRequest->setResponse($badResponse, true);
        $response = new Response(200, array(), 'foo');

        // Seed the cache
        $s = new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache()));
        $s->cache($request, $response);
        $this->assertNotNull($s->fetch($request));

        $rev = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultRevalidation')
            ->setConstructorArgs(array($s))
            ->setMethods(array('createRevalidationRequest'))
            ->getMock();

        $rev->expects($this->once())
            ->method('createRevalidationRequest')
            ->will($this->returnValue($badRequest));

        try {
            $rev->revalidate($request, $response);
            $this->fail('Should have thrown an exception');
        } catch (BadResponseException $e) {
            $this->assertSame($badResponse, $e->getResponse());
            $this->assertNull($s->fetch($request));
        }
    }

    public function testCanRevalidateWithPlugin()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" .
            "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Content-Length: 2\r\n\r\nhi",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
        ));
        $client = new Client($this->getServer()->getUrl());
        $client->addSubscriber(new CachePlugin());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(3, count($this->getServer()->getReceivedRequests()));
    }

    public function testCanHandleRevalidationFailures()
    {
        $client = new Client($this->getServer()->getUrl());
        $lm = gmdate('c', time() - 60);
        $mock = new MockPlugin(array(
            new Response(200, array(
                'Date'           => $lm,
                'Cache-Control'  => 'max-age=100, must-revalidate, stale-if-error=9999',
                'Last-Modified'  => $lm,
                'Content-Length' => 2
            ), 'hi'),
            new CurlException('Bleh'),
            new CurlException('Bleh')
        ));
        $client->addSubscriber(new CachePlugin());
        $client->addSubscriber($mock);
        $client->get()->send();
        $response = $client->get()->send();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('hi', $response->getBody(true));
        $this->assertEquals(3, count($mock->getReceivedRequests()));
        $this->assertEquals(0, count($mock->getQueue()));
    }

    public function testCanHandleStaleIfErrorWhenRevalidating()
    {
        $lm = gmdate('c', time() - 60);
        $mock = new MockPlugin(array(
            new Response(200, array(
                'Date' => $lm,
                'Cache-Control' => 'must-revalidate, max-age=0, stale-if-error=1200',
                'Last-Modified' => $lm,
                'Content-Length' => 2
            ), 'hi'),
            new CurlException('Oh no!'),
            new CurlException('Oh no!')
        ));
        $cache = new CachePlugin();
        $client = new Client('http://www.example.com');
        $client->addSubscriber($cache);
        $client->addSubscriber($mock);
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $response = $client->get()->send();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertCount(0, $mock);
        $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup'));
        $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache'));
    }

    /**
     * @group issue-437
     */
    public function testDoesNotTouchClosureListeners()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" .
            "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Content-Length: 2\r\n\r\nhi",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
        ));
        $client = new Client($this->getServer()->getUrl());
        $client->addSubscriber(new CachePlugin());
        $client->getEventDispatcher()->addListener('command.after_send', function(){});
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
    }

}
<?php

namespace Guzzle\Tests\Plugin\Cache;

use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cache\DefaultCacheStorage;
use Doctrine\Common\Cache\ArrayCache;

/**
 * @covers Guzzle\Plugin\Cache\DefaultCacheStorage
 */
class DefaultCacheStorageTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getCache()
    {
        $a = new ArrayCache();
        $c = new DoctrineCacheAdapter($a);
        $s = new DefaultCacheStorage($c);
        $request = new Request('GET', 'http://foo.com', array('Accept' => 'application/json'));
        $response = new Response(200, array(
            'Content-Type' => 'application/json',
            'Connection' => 'close',
            'X-Foo' => 'Bar',
            'Vary' => 'Accept'
        ), 'test');
        $s->cache($request, $response);
        $data = $this->readAttribute($a, 'data');

        return array(
            'cache' => $a,
            'adapter' => $c,
            'storage' => $s,
            'request' => $request,
            'response' => $response,
            'serialized' => end($data)
        );
    }

    public function testReturnsNullForCacheMiss()
    {
        $cache = $this->getCache();
        $this->assertNull($cache['storage']->fetch(new Request('GET', 'http://test.com')));
    }

    public function testCachesRequests()
    {
        $cache = $this->getCache();
        $foundRequest = $foundBody = $bodyKey = false;
        foreach ($this->readAttribute($cache['cache'], 'data') as $key => $v) {
            if (strpos($v, 'foo.com')) {
                $foundRequest = true;
                $data = unserialize($v);
                $bodyKey = $data[0][3];
                $this->assertInternalType('integer', $data[0][4]);
                $this->assertFalse(isset($data[0][0]['connection']));
                $this->assertEquals('foo.com', $data[0][0]['host']);
            } elseif ($v == 'test') {
                $foundBody = $key;
            }
        }
        $this->assertContains($bodyKey, $foundBody);
        $this->assertTrue($foundRequest);
    }

    public function testFetchesResponse()
    {
        $cache = $this->getCache();
        $response = $cache['storage']->fetch($cache['request']);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertFalse($response->hasHeader('Connection'));
        $this->assertEquals('Bar', (string) $response->getHeader('X-Foo'));
        $this->assertEquals('test', (string) $response->getBody());
        $this->assertTrue(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data')));
    }

    public function testDeletesRequestItemsAndBody()
    {
        $cache = $this->getCache();
        $cache['storage']->delete($cache['request']);
        $this->assertFalse(in_array('test', $this->readAttribute($cache['cache'], 'data')));
        $this->assertFalse(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data')));
    }

    public function testCachesMultipleRequestsWithVary()
    {
        $cache = $this->getCache();
        $cache['request']->setHeader('Accept', 'application/xml');
        $response = $cache['response']->setHeader('Content-Type', 'application/xml');
        $response->setBody('123');
        $cache['storage']->cache($cache['request'], $response);
        $data = $this->readAttribute($cache['cache'], 'data');
        foreach ($data as $v) {
            if (strpos($v, 'foo.com')) {
                $u = unserialize($v);
                $this->assertEquals(2, count($u));
                $this->assertEquals($u[0][0]['accept'], 'application/xml');
                $this->assertEquals($u[0][1]['content-type'], 'application/xml');
                $this->assertEquals($u[1][0]['accept'], 'application/json');
                $this->assertEquals($u[1][1]['content-type'], 'application/json');
                $this->assertNotSame($u[0][3], $u[1][3]);
                break;
            }
        }
    }

    public function testPurgeRemovesAllMethodCaches()
    {
        $cache = $this->getCache();
        foreach (array('HEAD', 'POST', 'PUT', 'DELETE') as $method) {
            $request = RequestFactory::getInstance()->cloneRequestWithMethod($cache['request'], $method);
            $cache['storage']->cache($request, $cache['response']);
        }
        $cache['storage']->purge('http://foo.com');
        $this->assertFalse(in_array('test', $this->readAttribute($cache['cache'], 'data')));
        $this->assertFalse(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data')));
        $this->assertEquals(
            array('DoctrineNamespaceCacheKey[]'),
            array_keys($this->readAttribute($cache['cache'], 'data'))
        );
    }

    public function testRemovesExpiredResponses()
    {
        $cache = $this->getCache();
        $request = new Request('GET', 'http://xyz.com');
        $response = new Response(200, array('Age' => 1000, 'Cache-Control' => 'max-age=-10000'));
        $cache['storage']->cache($request, $response);
        $this->assertNull($cache['storage']->fetch($request));
        $data = $this->readAttribute($cache['cache'], 'data');
        $this->assertFalse(in_array('xyz.com', $data));
        $this->assertTrue(in_array($cache['serialized'], $data));
    }

    public function testUsesVaryToDetermineResult()
    {
        $cache = $this->getCache();
        $this->assertInstanceOf('Guzzle\Http\Message\Response', $cache['storage']->fetch($cache['request']));
        $request = new Request('GET', 'http://foo.com', array('Accept' => 'application/xml'));
        $this->assertNull($cache['storage']->fetch($request));
    }

    public function testEnsuresResponseIsStillPresent()
    {
        $cache = $this->getCache();
        $data = $this->readAttribute($cache['cache'], 'data');
        $key = array_search('test', $data);
        $cache['cache']->delete(substr($key, 1, -4));
        $this->assertNull($cache['storage']->fetch($cache['request']));
    }

    public function staleProvider()
    {
        return array(
            array(
                new Request('GET', 'http://foo.com', array('Accept' => 'foo')),
                new Response(200, array('Cache-Control' => 'stale-if-error=100', 'Vary' => 'Accept'))
            ),
            array(
                new Request('GET', 'http://foo.com', array('Accept' => 'foo')),
                new Response(200, array('Cache-Control' => 'stale-if-error', 'Vary' => 'Accept'))
            )
        );
    }

    /**
     * @dataProvider staleProvider
     */
    public function testUsesStaleTimeDirectiveForTtd($request, $response)
    {
        $cache = $this->getCache();
        $cache['storage']->cache($request, $response);
        $data = $this->readAttribute($cache['cache'], 'data');
        foreach ($data as $v) {
            if (strpos($v, 'foo.com')) {
                $u = unserialize($v);
                $this->assertGreaterThan($u[1][4], $u[0][4]);
                break;
            }
        }
    }

    public function testCanFilterCacheKeys()
    {
        $cache = $this->getCache();
        $cache['request']->getQuery()->set('auth', 'foo');
        $this->assertNull($cache['storage']->fetch($cache['request']));
        $cache['request']->getParams()->set('cache.key_filter', 'auth');
        $this->assertNotNull($cache['storage']->fetch($cache['request']));
    }
}
<?php

namespace Guzzle\Tests\Plugin\ErrorResponse;

use Guzzle\Service\Client;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\ErrorResponse\ErrorResponsePlugin;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Tests\Mock\ErrorResponseMock;

/**
 * @covers \Guzzle\Plugin\ErrorResponse\ErrorResponsePlugin
 */
class ErrorResponsePluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $client;

    public static function tearDownAfterClass()
    {
        self::getServer()->flush();
    }

    public function setUp()
    {
        $mockError = 'Guzzle\Tests\Mock\ErrorResponseMock';
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'works' => array(
                    'httpMethod' => 'GET',
                    'errorResponses' => array(
                        array('code' => 500, 'class' => $mockError),
                        array('code' => 503, 'reason' => 'foo', 'class' => $mockError),
                        array('code' => 200, 'reason' => 'Error!', 'class' => $mockError)
                    )
                ),
                'bad_class' => array(
                    'httpMethod' => 'GET',
                    'errorResponses' => array(
                        array('code' => 500, 'class' => 'Does\\Not\\Exist')
                    )
                ),
                'does_not_implement' => array(
                    'httpMethod' => 'GET',
                    'errorResponses' => array(
                        array('code' => 500, 'class' => __CLASS__)
                    )
                ),
                'no_errors' => array('httpMethod' => 'GET'),
                'no_class' => array(
                    'httpMethod' => 'GET',
                    'errorResponses' => array(
                        array('code' => 500)
                    )
                ),
            )
        ));
        $this->client = new Client($this->getServer()->getUrl());
        $this->client->setDescription($description);
    }

    /**
     * @expectedException \Guzzle\Http\Exception\ServerErrorResponseException
     */
    public function testSkipsWhenErrorResponsesIsNotSet()
    {
        $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('no_errors')->execute();
    }

    public function testSkipsWhenErrorResponsesIsNotSetAndAllowsSuccess()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('no_errors')->execute();
    }

    /**
     * @expectedException \Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException
     * @expectedExceptionMessage Does\Not\Exist does not exist
     */
    public function testEnsuresErrorResponseExists()
    {
        $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('bad_class')->execute();
    }

    /**
     * @expectedException \Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException
     * @expectedExceptionMessage must implement Guzzle\Plugin\ErrorResponse\ErrorResponseExceptionInterface
     */
    public function testEnsuresErrorResponseImplementsInterface()
    {
        $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('does_not_implement')->execute();
    }

    public function testThrowsSpecificErrorResponseOnMatch()
    {
        try {
            $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n");
            $this->client->addSubscriber(new ErrorResponsePlugin());
            $command = $this->client->getCommand('works');
            $command->execute();
            $this->fail('Exception not thrown');
        } catch (ErrorResponseMock $e) {
            $this->assertSame($command, $e->command);
            $this->assertEquals(500, $e->response->getStatusCode());
        }
    }

    /**
     * @expectedException \Guzzle\Tests\Mock\ErrorResponseMock
     */
    public function testThrowsWhenCodeAndPhraseMatch()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 Error!\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('works')->execute();
    }

    public function testSkipsWhenReasonDoesNotMatch()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('works')->execute();
    }

    public function testSkipsWhenNoClassIsSet()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $this->client->addSubscriber(new ErrorResponsePlugin());
        $this->client->getCommand('no_class')->execute();
    }
}
<?php

namespace Guzzle\Tests\Plugin\Mock;

use Guzzle\Common\Event;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\Client;
use Guzzle\Http\Exception\CurlException;

/**
 * @covers Guzzle\Plugin\Mock\MockPlugin
 */
class MockPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDescribesSubscribedEvents()
    {
        $this->assertInternalType('array', MockPlugin::getSubscribedEvents());
    }

    public function testDescribesEvents()
    {
        $this->assertInternalType('array', MockPlugin::getAllEvents());
    }

    public function testCanBeTemporary()
    {
        $plugin = new MockPlugin();
        $this->assertFalse($plugin->isTemporary());
        $plugin = new MockPlugin(null, true);
        $this->assertTrue($plugin->isTemporary());
    }

    public function testIsCountable()
    {
        $plugin = new MockPlugin();
        $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"));
        $this->assertEquals(1, count($plugin));
    }

    /**
     * @depends testIsCountable
     */
    public function testCanClearQueue()
    {
        $plugin = new MockPlugin();
        $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"));
        $plugin->clearQueue();
        $this->assertEquals(0, count($plugin));
    }

    public function testCanInspectQueue()
    {
        $plugin = new MockPlugin();
        $this->assertInternalType('array', $plugin->getQueue());
        $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"));
        $queue = $plugin->getQueue();
        $this->assertInternalType('array', $queue);
        $this->assertEquals(1, count($queue));
    }

    public function testRetrievesResponsesFromFiles()
    {
        $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response');
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response);
        $this->assertEquals(200, $response->getStatusCode());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testThrowsExceptionWhenResponseFileIsNotFound()
    {
        MockPlugin::getMockFile('missing/filename');
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvalidResponsesThrowAnException()
    {
        $p = new MockPlugin();
        $p->addResponse($this);
    }

    public function testAddsResponseObjectsToQueue()
    {
        $p = new MockPlugin();
        $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $p->addResponse($response);
        $this->assertEquals(array($response), $p->getQueue());
    }

    public function testAddsResponseFilesToQueue()
    {
        $p = new MockPlugin();
        $p->addResponse(__DIR__ . '/../../TestData/mock_response');
        $this->assertEquals(1, count($p));
    }

    /**
     * @depends testAddsResponseFilesToQueue
     */
    public function testAddsMockResponseToRequestFromClient()
    {
        $p = new MockPlugin();
        $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response');
        $p->addResponse($response);

        $client = new Client('http://127.0.0.1:123/');
        $client->getEventDispatcher()->addSubscriber($p, 9999);
        $request = $client->get();
        $request->send();

        $this->assertSame($response, $request->getResponse());
        $this->assertEquals(0, count($p));
    }

    /**
     * @depends testAddsResponseFilesToQueue
     * @expectedException \OutOfBoundsException
     */
    public function testUpdateThrowsExceptionWhenEmpty()
    {
        $p = new MockPlugin();
        $p->onRequestBeforeSend(new Event());
    }

    /**
     * @depends testAddsMockResponseToRequestFromClient
     */
    public function testDetachesTemporaryWhenEmpty()
    {
        $p = new MockPlugin(null, true);
        $p->addResponse(MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response'));
        $client = new Client('http://127.0.0.1:123/');
        $client->getEventDispatcher()->addSubscriber($p, 9999);
        $request = $client->get();
        $request->send();

        $this->assertFalse($this->hasSubscriber($client, $p));
    }

    public function testLoadsResponsesFromConstructor()
    {
        $p = new MockPlugin(array(new Response(200)));
        $this->assertEquals(1, $p->count());
    }

    public function testStoresMockedRequests()
    {
        $p = new MockPlugin(array(new Response(200), new Response(200)));
        $client = new Client('http://127.0.0.1:123/');
        $client->getEventDispatcher()->addSubscriber($p, 9999);

        $request1 = $client->get();
        $request1->send();
        $this->assertEquals(array($request1), $p->getReceivedRequests());

        $request2 = $client->get();
        $request2->send();
        $this->assertEquals(array($request1, $request2), $p->getReceivedRequests());

        $p->flush();
        $this->assertEquals(array(), $p->getReceivedRequests());
    }

    public function testReadsBodiesFromMockedRequests()
    {
        $p = new MockPlugin(array(new Response(200)));
        $p->readBodies(true);
        $client = new Client('http://127.0.0.1:123/');
        $client->getEventDispatcher()->addSubscriber($p, 9999);

        $body = EntityBody::factory('foo');
        $request = $client->put();
        $request->setBody($body);
        $request->send();
        $this->assertEquals(3, $body->ftell());
    }

    public function testCanMockBadRequestExceptions()
    {
        $client = new Client('http://127.0.0.1:123/');
        $ex = new CurlException('Foo');
        $mock = new MockPlugin(array($ex));
        $client->addSubscriber($mock);
        $request = $client->get('foo');

        try {
            $request->send();
            $this->fail('Did not dequeue an exception');
        } catch (CurlException $e) {
            $this->assertSame($e, $ex);
            $this->assertSame($request, $ex->getRequest());
        }
    }
}
<?php

namespace Guzzle\Tests\Plugin\Async;

use Guzzle\Plugin\Async\AsyncPlugin;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Common\Event;
use Guzzle\Http\Client;

/**
 * @covers Guzzle\Plugin\Async\AsyncPlugin
 */
class AsyncPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testSubscribesToEvents()
    {
        $events = AsyncPlugin::getSubscribedEvents();
        $this->assertArrayHasKey('request.before_send', $events);
        $this->assertArrayHasKey('request.exception', $events);
        $this->assertArrayHasKey('curl.callback.progress', $events);
    }

    public function testEnablesProgressCallbacks()
    {
        $p = new AsyncPlugin();
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com');
        $event = new Event(array(
            'request' => $request
        ));
        $p->onBeforeSend($event);
        $this->assertEquals(true, $request->getCurlOptions()->get('progress'));
    }

    public function testAddsTimesOutAfterSending()
    {
        $p = new AsyncPlugin();
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com');
        $handle = CurlHandle::factory($request);
        $event = new Event(array(
            'request'     => $request,
            'handle'      => $handle->getHandle(),
            'uploaded'    => 10,
            'upload_size' => 10,
            'downloaded'  => 0
        ));
        $p->onCurlProgress($event);
    }

    public function testEnsuresRequestIsSet()
    {
        $p = new AsyncPlugin();
        $event = new Event(array(
            'uploaded'    => 10,
            'upload_size' => 10,
            'downloaded'  => 0
        ));
        $p->onCurlProgress($event);
    }

    public function testMasksCurlExceptions()
    {
        $p = new AsyncPlugin();
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com');
        $e = new CurlException('Error');
        $event = new Event(array(
            'request'   => $request,
            'exception' => $e
        ));
        $p->onRequestTimeout($event);
        $this->assertEquals(RequestInterface::STATE_COMPLETE, $request->getState());
        $this->assertEquals(200, $request->getResponse()->getStatusCode());
        $this->assertTrue($request->getResponse()->hasHeader('X-Guzzle-Async'));
    }

    public function testEnsuresIntegration()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 204 FOO\r\nContent-Length: 4\r\n\r\ntest");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->post('/', null, array(
            'foo' => 'bar'
        ));
        $request->getEventDispatcher()->addSubscriber(new AsyncPlugin());
        $request->send();
        $this->assertEquals('', $request->getResponse()->getBody(true));
        $this->assertTrue($request->getResponse()->hasHeader('X-Guzzle-Async'));
        $received = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('POST', $received[0]->getMethod());
    }
}
<?php

namespace Guzzle\Tests\Plugin\CurlAuth;

use Guzzle\Common\Version;
use Guzzle\Plugin\CurlAuth\CurlAuthPlugin;
use Guzzle\Http\Client;

/**
 * @covers Guzzle\Plugin\CurlAuth\CurlAuthPlugin
 */
class CurlAuthPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testAddsBasicAuthentication()
    {
        Version::$emitWarnings = false;
        $plugin = new CurlAuthPlugin('michael', 'test');
        $client = new Client('http://www.test.com/');
        $client->getEventDispatcher()->addSubscriber($plugin);
        $request = $client->get('/');
        $this->assertEquals('michael', $request->getUsername());
        $this->assertEquals('test', $request->getPassword());
        Version::$emitWarnings = true;
    }

    public function testAddsDigestAuthentication()
    {
        Version::$emitWarnings = false;
        $plugin = new CurlAuthPlugin('julian', 'test', CURLAUTH_DIGEST);
        $client = new Client('http://www.test.com/');
        $client->getEventDispatcher()->addSubscriber($plugin);
        $request = $client->get('/');
        $this->assertEquals('julian', $request->getUsername());
        $this->assertEquals('test', $request->getPassword());
        $this->assertEquals('julian:test', $request->getCurlOptions()->get(CURLOPT_USERPWD));
        $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH));
        Version::$emitWarnings = true;
    }
}
<?php

namespace Guzzle\Tests\Plugin\History;

use Guzzle\Http\Client;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\History\HistoryPlugin;
use Guzzle\Plugin\Mock\MockPlugin;

/**
 * @covers Guzzle\Plugin\History\HistoryPlugin
 */
class HistoryPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * Adds multiple requests to a plugin
     *
     * @param HistoryPlugin $h Plugin
     * @param int $num Number of requests to add
     *
     * @return array
     */
    protected function addRequests(HistoryPlugin $h, $num)
    {
        $requests = array();
        $client = new Client('http://127.0.0.1/');
        for ($i = 0; $i < $num; $i++) {
            $requests[$i] = $client->get();
            $requests[$i]->setResponse(new Response(200), true);
            $requests[$i]->send();
            $h->add($requests[$i]);
        }

        return $requests;
    }

    public function testDescribesSubscribedEvents()
    {
        $this->assertInternalType('array', HistoryPlugin::getSubscribedEvents());
    }

    public function testMaintainsLimitValue()
    {
        $h = new HistoryPlugin();
        $this->assertSame($h, $h->setLimit(10));
        $this->assertEquals(10, $h->getLimit());
    }

    public function testAddsRequests()
    {
        $h = new HistoryPlugin();
        $requests = $this->addRequests($h, 1);
        $this->assertEquals(1, count($h));
        $i = $h->getIterator();
        $this->assertEquals(1, count($i));
        $this->assertEquals($requests[0], $i[0]);
    }

    /**
     * @depends testAddsRequests
     */
    public function testMaintainsLimit()
    {
        $h = new HistoryPlugin();
        $h->setLimit(2);
        $requests = $this->addRequests($h, 3);
        $this->assertEquals(2, count($h));
        $i = 0;
        foreach ($h as $request) {
            if ($i > 0) {
                $this->assertSame($requests[$i], $request);
            }
        }
    }

    public function testReturnsLastRequest()
    {
        $h = new HistoryPlugin();
        $requests = $this->addRequests($h, 5);
        $this->assertSame(end($requests), $h->getLastRequest());
    }

    public function testReturnsLastResponse()
    {
        $h = new HistoryPlugin();
        $requests = $this->addRequests($h, 5);
        $this->assertSame(end($requests)->getResponse(), $h->getLastResponse());
    }

    public function testClearsHistory()
    {
        $h = new HistoryPlugin();
        $requests = $this->addRequests($h, 5);
        $this->assertEquals(5, count($h));
        $h->clear();
        $this->assertEquals(0, count($h));
    }

    /**
     * @depends testAddsRequests
     */
    public function testUpdatesAddRequests()
    {
        $h = new HistoryPlugin();
        $client = new Client('http://127.0.0.1/');
        $client->getEventDispatcher()->addSubscriber($h);

        $request = $client->get();
        $request->setResponse(new Response(200), true);
        $request->send();

        $this->assertSame($request, $h->getLastRequest());
    }

    public function testCanCastToString()
    {
        $client = new Client('http://127.0.0.1/');
        $h = new HistoryPlugin();
        $client->getEventDispatcher()->addSubscriber($h);

        $mock = new MockPlugin(array(
            new Response(301, array('Location' => '/redirect1', 'Content-Length' => 0)),
            new Response(307, array('Location' => '/redirect2', 'Content-Length' => 0)),
            new Response(200, array('Content-Length' => '2'), 'HI')
        ));

        $client->getEventDispatcher()->addSubscriber($mock);
        $request = $client->get();
        $request->send();
        $this->assertEquals(3, count($h));
        $this->assertEquals(3, count($mock->getReceivedRequests()));

        $h = str_replace("\r", '', $h);
        $this->assertContains("> GET / HTTP/1.1\nHost: 127.0.0.1\nUser-Agent:", $h);
        $this->assertContains("< HTTP/1.1 301 Moved Permanently\nLocation: /redirect1", $h);
        $this->assertContains("< HTTP/1.1 307 Temporary Redirect\nLocation: /redirect2", $h);
        $this->assertContains("< HTTP/1.1 200 OK\nContent-Length: 2\n\nHI", $h);
    }
}
<?php

namespace Guzzle\Tests\Plugin\Log;

use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Http\Client;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Common\Event;

/**
 * @group server
 * @covers Guzzle\Plugin\Log\LogPlugin
 */
class LogPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $adapter;

    public function setUp()
    {
        $this->adapter = new ClosureLogAdapter(function ($message) {
            echo $message;
        });
    }

    public function testIgnoresCurlEventsWhenNotWiringBodies()
    {
        $p = new LogPlugin($this->adapter);
        $this->assertNotEmpty($p->getSubscribedEvents());
        $event = new Event(array('request' => new Request('GET', 'http://foo.com')));
        $p->onCurlRead($event);
        $p->onCurlWrite($event);
        $p->onRequestBeforeSend($event);
    }

    public function testLogsWhenComplete()
    {
        $output = '';
        $p = new LogPlugin(new ClosureLogAdapter(function ($message) use (&$output) {
            $output = $message;
        }), '{method} {resource} | {code} {res_body}');

        $p->onRequestSent(new Event(array(
            'request'  => new Request('GET', 'http://foo.com'),
            'response' => new Response(200, array(), 'Foo')
        )));

        $this->assertEquals('GET / | 200 Foo', $output);
    }

    public function testWiresBodiesWhenNeeded()
    {
        $client = new Client($this->getServer()->getUrl());
        $plugin = new LogPlugin($this->adapter, '{req_body} | {res_body}', true);
        $client->getEventDispatcher()->addSubscriber($plugin);
        $request = $client->put();

        // Send the response from the dummy server as the request body
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nsend");
        $stream = fopen($this->getServer()->getUrl(), 'r');
        $request->setBody(EntityBody::factory($stream, 4));

        $tmpFile = tempnam(sys_get_temp_dir(), 'non_repeatable');
        $request->setResponseBody(EntityBody::factory(fopen($tmpFile, 'w')));

        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nresponse");

        ob_start();
        $request->send();
        $message = ob_get_clean();

        unlink($tmpFile);
        $this->assertContains("send", $message);
        $this->assertContains("response", $message);
    }

    public function testHasHelpfulStaticFactoryMethod()
    {
        $s = fopen('php://temp', 'r+');
        $client = new Client();
        $client->addSubscriber(LogPlugin::getDebugPlugin(true, $s));
        $request = $client->put('http://foo.com', array('Content-Type' => 'Foo'), 'Bar');
        $request->setresponse(new Response(200), true);
        $request->send();
        rewind($s);
        $contents = stream_get_contents($s);
        $this->assertContains('# Request:', $contents);
        $this->assertContainsIns('PUT / HTTP/1.1', $contents);
        $this->assertContains('# Response:', $contents);
        $this->assertContainsIns('HTTP/1.1 200 OK', $contents);
        $this->assertContains('# Errors:', $contents);
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cookie;

use Guzzle\Plugin\Cookie\Cookie;

/**
 * @covers Guzzle\Plugin\Cookie\Cookie
 */
class CookieTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testInitializesDefaultValues()
    {
        $cookie = new Cookie();
        $this->assertEquals('/', $cookie->getPath());
        $this->assertEquals(array(), $cookie->getPorts());
    }

    public function testConvertsDateTimeMaxAgeToUnixTimestamp()
    {
        $cookie = new Cookie(array(
           'expires' => 'November 20, 1984'
        ));
        $this->assertTrue(is_numeric($cookie->getExpires()));
    }

    public function testAddsExpiresBasedOnMaxAge()
    {
        $t = time();
        $cookie = new Cookie(array(
            'max_age' => 100
        ));
        $this->assertEquals($t + 100, $cookie->getExpires());
    }

    public function testHoldsValues()
    {
        $t = time();
        $data = array(
            'name'        => 'foo',
            'value'       => 'baz',
            'path'        => '/bar',
            'domain'      => 'baz.com',
            'expires'     => $t,
            'max_age'     => 100,
            'comment'     => 'Hi',
            'comment_url' => 'foo.com',
            'port'        => array(1, 2),
            'version'     => 2,
            'secure'      => true,
            'discard'     => true,
            'http_only'   => true,
            'data'        => array(
                'foo' => 'baz',
                'bar' => 'bam'
            )
        );

        $cookie = new Cookie($data);
        $this->assertEquals($data, $cookie->toArray());

        $this->assertEquals('foo', $cookie->getName());
        $this->assertEquals('baz', $cookie->getValue());
        $this->assertEquals('baz.com', $cookie->getDomain());
        $this->assertEquals('/bar', $cookie->getPath());
        $this->assertEquals($t, $cookie->getExpires());
        $this->assertEquals(100, $cookie->getMaxAge());
        $this->assertEquals('Hi', $cookie->getComment());
        $this->assertEquals('foo.com', $cookie->getCommentUrl());
        $this->assertEquals(array(1, 2), $cookie->getPorts());
        $this->assertEquals(2, $cookie->getVersion());
        $this->assertTrue($cookie->getSecure());
        $this->assertTrue($cookie->getDiscard());
        $this->assertTrue($cookie->getHttpOnly());
        $this->assertEquals('baz', $cookie->getAttribute('foo'));
        $this->assertEquals('bam', $cookie->getAttribute('bar'));
        $this->assertEquals(array(
            'foo' => 'baz',
            'bar' => 'bam'
        ), $cookie->getAttributes());

        $cookie->setName('a')
            ->setValue('b')
            ->setPath('c')
            ->setDomain('bar.com')
            ->setExpires(10)
            ->setMaxAge(200)
            ->setComment('e')
            ->setCommentUrl('f')
            ->setPorts(array(80))
            ->setVersion(3)
            ->setSecure(false)
            ->setHttpOnly(false)
            ->setDiscard(false)
            ->setAttribute('snoop', 'dog');

        $this->assertEquals('a', $cookie->getName());
        $this->assertEquals('b', $cookie->getValue());
        $this->assertEquals('c', $cookie->getPath());
        $this->assertEquals('bar.com', $cookie->getDomain());
        $this->assertEquals(10, $cookie->getExpires());
        $this->assertEquals(200, $cookie->getMaxAge());
        $this->assertEquals('e', $cookie->getComment());
        $this->assertEquals('f', $cookie->getCommentUrl());
        $this->assertEquals(array(80), $cookie->getPorts());
        $this->assertEquals(3, $cookie->getVersion());
        $this->assertFalse($cookie->getSecure());
        $this->assertFalse($cookie->getDiscard());
        $this->assertFalse($cookie->getHttpOnly());
        $this->assertEquals('dog', $cookie->getAttribute('snoop'));
    }

    public function testDeterminesIfExpired()
    {
        $c = new Cookie();
        $c->setExpires(10);
        $this->assertTrue($c->isExpired());
        $c->setExpires(time() + 10000);
        $this->assertFalse($c->isExpired());
    }

    public function testMatchesPorts()
    {
        $cookie = new Cookie();
        // Always matches when nothing is set
        $this->assertTrue($cookie->matchesPort(2));

        $cookie->setPorts(array(1, 2));
        $this->assertTrue($cookie->matchesPort(2));
        $this->assertFalse($cookie->matchesPort(100));
    }

    public function testMatchesDomain()
    {
        $cookie = new Cookie();
        $this->assertTrue($cookie->matchesDomain('baz.com'));

        $cookie->setDomain('baz.com');
        $this->assertTrue($cookie->matchesDomain('baz.com'));
        $this->assertFalse($cookie->matchesDomain('bar.com'));

        $cookie->setDomain('.baz.com');
        $this->assertTrue($cookie->matchesDomain('.baz.com'));
        $this->assertTrue($cookie->matchesDomain('foo.baz.com'));
        $this->assertFalse($cookie->matchesDomain('baz.bar.com'));
        $this->assertTrue($cookie->matchesDomain('baz.com'));

        $cookie->setDomain('.127.0.0.1');
        $this->assertTrue($cookie->matchesDomain('127.0.0.1'));

        $cookie->setDomain('127.0.0.1');
        $this->assertTrue($cookie->matchesDomain('127.0.0.1'));

        $cookie->setDomain('.com.');
        $this->assertFalse($cookie->matchesDomain('baz.com'));

        $cookie->setDomain('.local');
        $this->assertTrue($cookie->matchesDomain('example.local'));
    }

    public function testMatchesPath()
    {
        $cookie = new Cookie();
        $this->assertTrue($cookie->matchesPath('/foo'));

        $cookie->setPath('/foo');

        // o  The cookie-path and the request-path are identical.
        $this->assertTrue($cookie->matchesPath('/foo'));
        $this->assertFalse($cookie->matchesPath('/bar'));

        // o  The cookie-path is a prefix of the request-path, and the first
        // character of the request-path that is not included in the cookie-
        // path is a %x2F ("/") character.
        $this->assertTrue($cookie->matchesPath('/foo/bar'));
        $this->assertFalse($cookie->matchesPath('/fooBar'));

        // o  The cookie-path is a prefix of the request-path, and the last
        // character of the cookie-path is %x2F ("/").
        $cookie->setPath('/foo/');
        $this->assertTrue($cookie->matchesPath('/foo/bar'));
        $this->assertFalse($cookie->matchesPath('/fooBaz'));
        $this->assertFalse($cookie->matchesPath('/foo'));

    }

    public function cookieValidateProvider()
    {
        return array(
            array('foo', 'baz', 'bar', true),
            array('0', '0', '0', true),
            array('', 'baz', 'bar', 'The cookie name must not be empty'),
            array('foo', '', 'bar', 'The cookie value must not be empty'),
            array('foo', 'baz', '', 'The cookie domain must not be empty'),
            array('foo\\', 'baz', '0', 'The cookie name must not contain invalid characters: foo\\'),
        );
    }

    /**
     * @dataProvider cookieValidateProvider
     */
    public function testValidatesCookies($name, $value, $domain, $result)
    {
        $cookie = new Cookie(array(
            'name'   => $name,
            'value'  => $value,
            'domain' => $domain
        ));
        $this->assertSame($result, $cookie->validate());
    }

    public function testCreatesInvalidCharacterString()
    {
        $m = new \ReflectionMethod('Guzzle\Plugin\Cookie\Cookie', 'getInvalidCharacters');
        $m->setAccessible(true);
        $p = new \ReflectionProperty('Guzzle\Plugin\Cookie\Cookie', 'invalidCharString');
        $p->setAccessible(true);
        $p->setValue('');
        // Expects a string containing 51 invalid characters
        $this->assertEquals(51, strlen($m->invoke($m)));
        $this->assertContains('@', $m->invoke($m));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cookie;

use Guzzle\Common\Event;
use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Cookie\CookiePlugin;

/**
 * @group server
 * @covers Guzzle\Plugin\Cookie\CookiePlugin
 */
class CookiePluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testExtractsAndStoresCookies()
    {
        $response = new Response(200);
        $mock = $this->getMockBuilder('Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar')
            ->setMethods(array('addCookiesFromResponse'))
            ->getMock();

        $mock->expects($this->exactly(1))
            ->method('addCookiesFromResponse')
            ->with($response);

        $plugin = new CookiePlugin($mock);
        $plugin->onRequestSent(new Event(array(
            'response' => $response
        )));
    }

    public function testAddsCookiesToRequests()
    {
        $cookie = new Cookie(array(
            'name'  => 'foo',
            'value' => 'bar'
        ));

        $mock = $this->getMockBuilder('Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar')
            ->setMethods(array('getMatchingCookies'))
            ->getMock();

        $mock->expects($this->once())
            ->method('getMatchingCookies')
            ->will($this->returnValue(array($cookie)));

        $plugin = new CookiePlugin($mock);

        $client = new Client();
        $client->getEventDispatcher()->addSubscriber($plugin);

        $request = $client->get('http://www.example.com');
        $plugin->onRequestBeforeSend(new Event(array(
            'request' => $request
        )));

        $this->assertEquals('bar', $request->getCookie('foo'));
    }

    public function testCookiesAreExtractedFromRedirectResponses()
    {
        $plugin = new CookiePlugin(new ArrayCookieJar());
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 302 Moved Temporarily\r\n" .
            "Set-Cookie: test=583551; expires=Wednesday, 23-Mar-2050 19:49:45 GMT; path=/\r\n" .
            "Location: /redirect\r\n\r\n",
            "HTTP/1.1 200 OK\r\n" .
            "Content-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\n" .
            "Content-Length: 0\r\n\r\n"
        ));

        $client = new Client($this->getServer()->getUrl());
        $client->getEventDispatcher()->addSubscriber($plugin);

        $client->get()->send();
        $request = $client->get();
        $request->send();
        $this->assertEquals('test=583551', $request->getHeader('Cookie'));

        $requests = $this->getServer()->getReceivedRequests(true);
        // Confirm subsequent requests have the cookie.
        $this->assertEquals('test=583551', $requests[2]->getHeader('Cookie'));
        // Confirm the redirected request has the cookie.
        $this->assertEquals('test=583551', $requests[1]->getHeader('Cookie'));
    }

    public function testCookiesAreNotAddedWhenParamIsSet()
    {
        $jar = new ArrayCookieJar();
        $plugin = new CookiePlugin($jar);

        $jar->add(new Cookie(array(
            'domain'  => 'example.com',
            'path'    => '/',
            'name'    => 'test',
            'value'   => 'hi',
            'expires' => time() + 3600
        )));

        $client = new Client('http://example.com');
        $client->getEventDispatcher()->addSubscriber($plugin);

        // Ensure that it is normally added
        $request = $client->get();
        $request->setResponse(new Response(200), true);
        $request->send();
        $this->assertEquals('hi', $request->getCookie('test'));

        // Now ensure that it is not added
        $request = $client->get();
        $request->getParams()->set('cookies.disable', true);
        $request->setResponse(new Response(200), true);
        $request->send();
        $this->assertNull($request->getCookie('test'));
    }

    public function testProvidesCookieJar()
    {
        $jar = new ArrayCookieJar();
        $plugin = new CookiePlugin($jar);
        $this->assertSame($jar, $plugin->getCookieJar());
    }

    public function testEscapesCookieDomains()
    {
        $cookie = new Cookie(array('domain' => '/foo/^$[A-Z]+/'));
        $this->assertFalse($cookie->matchesDomain('foo'));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cookie\CookieJar;

use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\Request;

/**
 * @covers Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar
 */
class ArrayCookieJarTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @var ArrayCookieJar
     */
    private $jar;

    public function setUp()
    {
        $this->jar = new ArrayCookieJar();
    }

    protected function getTestCookies()
    {
        return array(
            new Cookie(array('name' => 'foo',  'value' => 'bar', 'domain' => 'foo.com', 'path' => '/',    'discard' => true)),
            new Cookie(array('name' => 'test', 'value' => '123', 'domain' => 'baz.com', 'path' => '/foo', 'expires' => 2)),
            new Cookie(array('name' => 'you',  'value' => '123', 'domain' => 'bar.com', 'path' => '/boo', 'expires' => time() + 1000))
        );
    }

    /**
     * Provides test data for cookie cookieJar retrieval
     */
    public function getCookiesDataProvider()
    {
        return array(
            array(array('foo', 'baz', 'test', 'muppet', 'googoo'), '', '', '', false),
            array(array('foo', 'baz', 'muppet', 'googoo'), '', '', '', true),
            array(array('googoo'), 'www.example.com', '', '', false),
            array(array('muppet', 'googoo'), 'test.y.example.com', '', '', false),
            array(array('foo', 'baz'), 'example.com', '', '', false),
            array(array('muppet'), 'x.y.example.com', '/acme/', '', false),
            array(array('muppet'), 'x.y.example.com', '/acme/test/', '', false),
            array(array('googoo'), 'x.y.example.com', '/test/acme/test/', '', false),
            array(array('foo', 'baz'), 'example.com', '', '', false),
            array(array('baz'), 'example.com', '', 'baz', false),
        );
    }

    public function testStoresAndRetrievesCookies()
    {
        $cookies = $this->getTestCookies();
        foreach ($cookies as $cookie) {
            $this->assertTrue($this->jar->add($cookie));
        }

        $this->assertEquals(3, count($this->jar));
        $this->assertEquals(3, count($this->jar->getIterator()));
        $this->assertEquals($cookies, $this->jar->all(null, null, null, false, false));
    }

    public function testRemovesExpiredCookies()
    {
        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->add($cookie);
        }
        $this->jar->removeExpired();
        $this->assertEquals(array($cookies[0], $cookies[2]), $this->jar->all());
    }

    public function testRemovesTemporaryCookies()
    {
        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->add($cookie);
        }
        $this->jar->removeTemporary();
        $this->assertEquals(array($cookies[2]), $this->jar->all());
    }

    public function testIsSerializable()
    {
        $this->assertEquals('[]', $this->jar->serialize());
        $this->jar->unserialize('[]');
        $this->assertEquals(array(), $this->jar->all());

        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->add($cookie);
        }

        // Remove discard and expired cookies
        $serialized = $this->jar->serialize();
        $data = json_decode($serialized, true);
        $this->assertEquals(1, count($data));

        $a = new ArrayCookieJar();
        $a->unserialize($serialized);
        $this->assertEquals(1, count($a));
    }

    public function testRemovesSelectively()
    {
        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->add($cookie);
        }

        // Remove foo.com cookies
        $this->jar->remove('foo.com');
        $this->assertEquals(2, count($this->jar));
        // Try again, removing no further cookies
        $this->jar->remove('foo.com');
        $this->assertEquals(2, count($this->jar));

        // Remove bar.com cookies with path of /boo
        $this->jar->remove('bar.com', '/boo');
        $this->assertEquals(1, count($this->jar));

        // Remove cookie by name
        $this->jar->remove(null, null, 'test');
        $this->assertEquals(0, count($this->jar));
    }

    public function testDoesNotAddIncompleteCookies()
    {
        $this->assertEquals(false, $this->jar->add(new Cookie()));
        $this->assertFalse($this->jar->add(new Cookie(array(
            'name' => 'foo'
        ))));
        $this->assertFalse($this->jar->add(new Cookie(array(
            'name' => false
        ))));
        $this->assertFalse($this->jar->add(new Cookie(array(
            'name' => true
        ))));
        $this->assertFalse($this->jar->add(new Cookie(array(
            'name'   => 'foo',
            'domain' => 'foo.com'
        ))));
    }

    public function testDoesAddValidCookies()
    {
        $this->assertTrue($this->jar->add(new Cookie(array(
            'name'   => 'foo',
            'domain' => 'foo.com',
            'value'  => 0
        ))));
        $this->assertTrue($this->jar->add(new Cookie(array(
            'name'   => 'foo',
            'domain' => 'foo.com',
            'value'  => 0.0
        ))));
        $this->assertTrue($this->jar->add(new Cookie(array(
            'name'   => 'foo',
            'domain' => 'foo.com',
            'value'  => '0'
        ))));
    }

    public function testOverwritesCookiesThatAreOlderOrDiscardable()
    {
        $t = time() + 1000;
        $data = array(
            'name'    => 'foo',
            'value'   => 'bar',
            'domain'  => '.example.com',
            'path'    => '/',
            'max_age' => '86400',
            'port'    => array(80, 8080),
            'version' => '1',
            'secure'  => true,
            'discard' => true,
            'expires' => $t
        );

        // Make sure that the discard cookie is overridden with the non-discard
        $this->assertTrue($this->jar->add(new Cookie($data)));

        unset($data['discard']);
        $this->assertTrue($this->jar->add(new Cookie($data)));
        $this->assertEquals(1, count($this->jar));

        $c = $this->jar->all();
        $this->assertEquals(false, $c[0]->getDiscard());

        // Make sure it doesn't duplicate the cookie
        $this->jar->add(new Cookie($data));
        $this->assertEquals(1, count($this->jar));

        // Make sure the more future-ful expiration date supersede the other
        $data['expires'] = time() + 2000;
        $this->assertTrue($this->jar->add(new Cookie($data)));
        $this->assertEquals(1, count($this->jar));
        $c = $this->jar->all();
        $this->assertNotEquals($t, $c[0]->getExpires());
    }

    public function testOverwritesCookiesThatHaveChanged()
    {
        $t = time() + 1000;
        $data = array(
            'name'    => 'foo',
            'value'   => 'bar',
            'domain'  => '.example.com',
            'path'    => '/',
            'max_age' => '86400',
            'port'    => array(80, 8080),
            'version' => '1',
            'secure'  => true,
            'discard' => true,
            'expires' => $t
        );

        // Make sure that the discard cookie is overridden with the non-discard
        $this->assertTrue($this->jar->add(new Cookie($data)));

        $data['value'] = 'boo';
        $this->assertTrue($this->jar->add(new Cookie($data)));
        $this->assertEquals(1, count($this->jar));

        // Changing the value plus a parameter also must overwrite the existing one
        $data['value'] = 'zoo';
        $data['secure'] = false;
        $this->assertTrue($this->jar->add(new Cookie($data)));
        $this->assertEquals(1, count($this->jar));

        $c = $this->jar->all();
        $this->assertEquals('zoo', $c[0]->getValue());
    }

    public function testAddsCookiesFromResponseWithNoRequest()
    {
        $response = new Response(200, array(
            'Set-Cookie' => array(
                "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT; path=/; domain=127.0.0.1",
                "FPCK3=AgBNbvoQAGpGEABZLRAAbFsQAF1tEABkDhAAeO0=; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1",
                "CH=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1",
                "CH=AgBNbvoQAAEcEAApuhAAMJcQADQvEAAvGxAALe0QAD6uEAATwhAAC1AQAC8t; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1"
            )
        ));

        $this->jar->addCookiesFromResponse($response);
        $this->assertEquals(3, count($this->jar));
        $this->assertEquals(1, count($this->jar->all(null, null, 'fpc')));
        $this->assertEquals(1, count($this->jar->all(null, null, 'FPCK3')));
        $this->assertEquals(1, count($this->jar->all(null, null, 'CH')));
    }

    public function testAddsCookiesFromResponseWithRequest()
    {
        $response = new Response(200, array(
            'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;"
        ));
        $request = new Request('GET', 'http://www.example.com');
        $this->jar->addCookiesFromResponse($response, $request);
        $this->assertEquals(1, count($this->jar));
    }

    public function getMatchingCookiesDataProvider()
    {
        return array(
            array('https://example.com', array(0)),
            array('http://example.com', array()),
            array('https://example.com:8912', array()),
            array('https://foo.example.com', array(0)),
            array('http://foo.example.com/test/acme/', array(4))
        );
    }

    /**
     * @dataProvider getMatchingCookiesDataProvider
     */
    public function testReturnsCookiesMatchingRequests($url, $cookies)
    {
        $bag = array(
            new Cookie(array(
                'name'    => 'foo',
                'value'   => 'bar',
                'domain'  => 'example.com',
                'path'    => '/',
                'max_age' => '86400',
                'port'    => array(443, 8080),
                'version' => '1',
                'secure'  => true
            )),
            new Cookie(array(
                'name'    => 'baz',
                'value'   => 'foobar',
                'domain'  => 'example.com',
                'path'    => '/',
                'max_age' => '86400',
                'port'    => array(80, 8080),
                'version' => '1',
                'secure'  => true
            )),
            new Cookie(array(
                'name'    => 'test',
                'value'   => '123',
                'domain'  => 'www.foobar.com',
                'path'    => '/path/',
                'discard' => true
            )),
            new Cookie(array(
                'name'    => 'muppet',
                'value'   => 'cookie_monster',
                'domain'  => '.y.example.com',
                'path'    => '/acme/',
                'comment' => 'Comment goes here...',
                'expires' => time() + 86400
            )),
            new Cookie(array(
                'name'    => 'googoo',
                'value'   => 'gaga',
                'domain'  => '.example.com',
                'path'    => '/test/acme/',
                'max_age' => 1500,
                'version' => 2
            ))
        );

        foreach ($bag as $cookie) {
            $this->jar->add($cookie);
        }

        $request = new Request('GET', $url);
        $results = $this->jar->getMatchingCookies($request);
        $this->assertEquals(count($cookies), count($results));
        foreach ($cookies as $i) {
            $this->assertContains($bag[$i], $results);
        }
    }

    /**
     * @expectedException \Guzzle\Plugin\Cookie\Exception\InvalidCookieException
     * @expectedExceptionMessage The cookie name must not contain invalid characters: abc:@123
     */
    public function testThrowsExceptionWithStrictMode()
    {
        $a = new ArrayCookieJar();
        $a->setStrictMode(true);
        $a->add(new Cookie(array(
            'name'   => 'abc:@123',
            'value'  => 'foo',
            'domain' => 'bar'
        )));
    }

    public function testRemoveExistingCookieIfEmpty()
    {
        // Add a cookie that should not be affected
        $a = new Cookie(array(
            'name' => 'foo',
            'value' => 'nope',
            'domain' => 'foo.com',
            'path' => '/abc'
        ));
        $this->jar->add($a);

        $data = array(
            'name' => 'foo',
            'value' => 'bar',
            'domain' => 'foo.com',
            'path' => '/'
        );

        $b = new Cookie($data);
        $this->assertTrue($this->jar->add($b));
        $this->assertEquals(2, count($this->jar));

        // Try to re-set the same cookie with no value: assert that cookie is not added
        $data['value'] = null;
        $this->assertFalse($this->jar->add(new Cookie($data)));
        // assert that original cookie has been deleted
        $cookies = $this->jar->all('foo.com');
        $this->assertTrue(in_array($a, $cookies, true));
        $this->assertFalse(in_array($b, $cookies, true));
        $this->assertEquals(1, count($this->jar));
    }
}
<?php

namespace Guzzle\Tests\Plugin\Cookie\CookieJar;

use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Plugin\Cookie\CookieJar\FileCookieJar;

/**
 * @covers Guzzle\Plugin\Cookie\CookieJar\FileCookieJar
 */
class FileCookieJarTest extends \Guzzle\Tests\GuzzleTestCase
{
    private $file;

    public function setUp()
    {
        $this->file = tempnam('/tmp', 'file-cookies');
    }

    public function testLoadsFromFileFile()
    {
        $jar = new FileCookieJar($this->file);
        $this->assertEquals(array(), $jar->all());
        unlink($this->file);
    }

    public function testPersistsToFileFile()
    {
        $jar = new FileCookieJar($this->file);
        $jar->add(new Cookie(array(
            'name'    => 'foo',
            'value'   => 'bar',
            'domain'  => 'foo.com',
            'expires' => time() + 1000
        )));
        $jar->add(new Cookie(array(
            'name'    => 'baz',
            'value'   => 'bar',
            'domain'  => 'foo.com',
            'expires' => time() + 1000
        )));
        $jar->add(new Cookie(array(
            'name'    => 'boo',
            'value'   => 'bar',
            'domain'  => 'foo.com',
        )));

        $this->assertEquals(3, count($jar));
        unset($jar);

        // Make sure it wrote to the file
        $contents = file_get_contents($this->file);
        $this->assertNotEmpty($contents);

        // Load the cookieJar from the file
        $jar = new FileCookieJar($this->file);

        // Weeds out temporary and session cookies
        $this->assertEquals(2, count($jar));
        unset($jar);
        unlink($this->file);
    }
}
<?php

namespace Guzzle\Tests\Inflection;

use Guzzle\Inflection\Inflector;

/**
 * @covers Guzzle\Inflection\Inflector
 */
class InflectorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testReturnsDefaultInstance()
    {
        $this->assertSame(Inflector::getDefault(), Inflector::getDefault());
    }

    public function testSnake()
    {
        $this->assertEquals('camel_case', Inflector::getDefault()->snake('camelCase'));
        $this->assertEquals('camel_case', Inflector::getDefault()->snake('CamelCase'));
        $this->assertEquals('camel_case_words', Inflector::getDefault()->snake('CamelCaseWords'));
        $this->assertEquals('camel_case_words', Inflector::getDefault()->snake('CamelCase_words'));
        $this->assertEquals('test', Inflector::getDefault()->snake('test'));
        $this->assertEquals('test', Inflector::getDefault()->snake('test'));
        $this->assertEquals('expect100_continue', Inflector::getDefault()->snake('Expect100Continue'));
    }

    public function testCamel()
    {
        $this->assertEquals('CamelCase', Inflector::getDefault()->camel('camel_case'));
        $this->assertEquals('CamelCaseWords', Inflector::getDefault()->camel('camel_case_words'));
        $this->assertEquals('Test', Inflector::getDefault()->camel('test'));
        $this->assertEquals('Expect100Continue', ucfirst(Inflector::getDefault()->camel('expect100_continue')));
        // Get from cache
        $this->assertEquals('Test', Inflector::getDefault()->camel('test', false));
    }
}
<?php

namespace Guzzle\Tests\Inflection;

use Guzzle\Inflection\MemoizingInflector;
use Guzzle\Inflection\Inflector;

/**
 * @covers Guzzle\Inflection\MemoizingInflector
 */
class MemoizingInflectorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testUsesCache()
    {
        $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel'));
        $mock->expects($this->once())->method('snake')->will($this->returnValue('foo_bar'));
        $mock->expects($this->once())->method('camel')->will($this->returnValue('FooBar'));

        $inflector = new MemoizingInflector($mock);
        $this->assertEquals('foo_bar', $inflector->snake('FooBar'));
        $this->assertEquals('foo_bar', $inflector->snake('FooBar'));
        $this->assertEquals('FooBar', $inflector->camel('foo_bar'));
        $this->assertEquals('FooBar', $inflector->camel('foo_bar'));
    }

    public function testProtectsAgainstCacheOverflow()
    {
        $inflector = new MemoizingInflector(new Inflector(), 10);
        for ($i = 1; $i < 11; $i++) {
            $inflector->camel('foo_' . $i);
            $inflector->snake('Foo' . $i);
        }

        $cache = $this->readAttribute($inflector, 'cache');
        $this->assertEquals(10, count($cache['snake']));
        $this->assertEquals(10, count($cache['camel']));

        $inflector->camel('baz!');
        $inflector->snake('baz!');

        // Now ensure that 20% of the cache was removed (2), then the item was added
        $cache = $this->readAttribute($inflector, 'cache');
        $this->assertEquals(9, count($cache['snake']));
        $this->assertEquals(9, count($cache['camel']));
    }
}
<?php

namespace Guzzle\Tests\Inflection;

use Guzzle\Inflection\PreComputedInflector;

/**
 * @covers Guzzle\Inflection\PreComputedInflector
 */
class PreComputedInflectorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testUsesPreComputedHash()
    {
        $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel'));
        $mock->expects($this->once())->method('snake')->with('Test')->will($this->returnValue('test'));
        $mock->expects($this->once())->method('camel')->with('Test')->will($this->returnValue('Test'));
        $inflector = new PreComputedInflector($mock, array('FooBar' => 'foo_bar'), array('foo_bar' => 'FooBar'));
        $this->assertEquals('FooBar', $inflector->camel('foo_bar'));
        $this->assertEquals('foo_bar', $inflector->snake('FooBar'));
        $this->assertEquals('Test', $inflector->camel('Test'));
        $this->assertEquals('test', $inflector->snake('Test'));
    }

    public function testMirrorsPrecomputedValues()
    {
        $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel'));
        $mock->expects($this->never())->method('snake');
        $mock->expects($this->never())->method('camel');
        $inflector = new PreComputedInflector($mock, array('Zeep' => 'zeep'), array(), true);
        $this->assertEquals('Zeep', $inflector->camel('zeep'));
        $this->assertEquals('zeep', $inflector->snake('Zeep'));
    }

    public function testMirrorsPrecomputedValuesByMerging()
    {
        $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel'));
        $mock->expects($this->never())->method('snake');
        $mock->expects($this->never())->method('camel');
        $inflector = new PreComputedInflector($mock, array('Zeep' => 'zeep'), array('foo' => 'Foo'), true);
        $this->assertEquals('Zeep', $inflector->camel('zeep'));
        $this->assertEquals('zeep', $inflector->snake('Zeep'));
        $this->assertEquals('Foo', $inflector->camel('foo'));
        $this->assertEquals('foo', $inflector->snake('Foo'));
    }
}
<?php

namespace Guzzle\Tests\Parser;

use Guzzle\Parser\ParserRegistry;

/**
 * @covers Guzzle\Parser\ParserRegistry
 */
class ParserRegistryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testStoresObjects()
    {
        $r = new ParserRegistry();
        $c = new \stdClass();
        $r->registerParser('foo', $c);
        $this->assertSame($c, $r->getParser('foo'));
    }

    public function testReturnsNullWhenNotFound()
    {
        $r = new ParserRegistry();
        $this->assertNull($r->getParser('FOO'));
    }

    public function testReturnsLazyLoadedDefault()
    {
        $r = new ParserRegistry();
        $c = $r->getParser('cookie');
        $this->assertInstanceOf('Guzzle\Parser\Cookie\CookieParser', $c);
        $this->assertSame($c, $r->getParser('cookie'));
    }
}
<?php

namespace Guzzle\Tests\Parser\Message;

use Guzzle\Parser\Message\MessageParser;

/**
 * @covers Guzzle\Parser\Message\AbstractMessageParser
 * @covers Guzzle\Parser\Message\MessageParser
 */
class MessageParserTest extends MessageParserProvider
{
    /**
     * @dataProvider requestProvider
     */
    public function testParsesRequests($message, $parts)
    {
        $parser = new MessageParser();
        $this->compareRequestResults($parts, $parser->parseRequest($message));
    }

    /**
     * @dataProvider responseProvider
     */
    public function testParsesResponses($message, $parts)
    {
        $parser = new MessageParser();
        $this->compareResponseResults($parts, $parser->parseResponse($message));
    }

    public function testParsesRequestsWithMissingProtocol()
    {
        $parser = new MessageParser();
        $parts = $parser->parseRequest("GET /\r\nHost: Foo.com\r\n\r\n");
        $this->assertEquals('GET', $parts['method']);
        $this->assertEquals('HTTP', $parts['protocol']);
        $this->assertEquals('1.1', $parts['version']);
    }

    public function testParsesRequestsWithMissingVersion()
    {
        $parser = new MessageParser();
        $parts = $parser->parseRequest("GET / HTTP\r\nHost: Foo.com\r\n\r\n");
        $this->assertEquals('GET', $parts['method']);
        $this->assertEquals('HTTP', $parts['protocol']);
        $this->assertEquals('1.1', $parts['version']);
    }

    public function testParsesResponsesWithMissingReasonPhrase()
    {
        $parser = new MessageParser();
        $parts = $parser->parseResponse("HTTP/1.1 200\r\n\r\n");
        $this->assertEquals('200', $parts['code']);
        $this->assertEquals('', $parts['reason_phrase']);
        $this->assertEquals('HTTP', $parts['protocol']);
        $this->assertEquals('1.1', $parts['version']);
    }
}
<?php

namespace Guzzle\Tests\Parser\Message;

use Guzzle\Parser\Message\PeclHttpMessageParser;

/**
 * @covers Guzzle\Parser\Message\PeclHttpMessageParser
 */
class PeclHttpMessageParserTest extends MessageParserProvider
{
    protected function setUp()
    {
        if (!function_exists('http_parse_message')) {
            $this->markTestSkipped('pecl_http is not available.');
        }
    }

    /**
     * @dataProvider requestProvider
     */
    public function testParsesRequests($message, $parts)
    {
        $parser = new PeclHttpMessageParser();
        $this->compareRequestResults($parts, $parser->parseRequest($message));
    }

    /**
     * @dataProvider responseProvider
     */
    public function testParsesResponses($message, $parts)
    {
        $parser = new PeclHttpMessageParser();
        $this->compareResponseResults($parts, $parser->parseResponse($message));
    }
}
<?php

namespace Guzzle\Tests\Parser\Message;

class MessageParserProvider extends \Guzzle\Tests\GuzzleTestCase
{
    public function requestProvider()
    {
        $auth = base64_encode('michael:foo');

        return array(

            // Empty request
            array('', false),

            // Converts casing of request. Does not require host header.
            array("GET / HTTP/1.1\r\n\r\n", array(
                'method'   => 'GET',
                'protocol' => 'HTTP',
                'version' => '1.1',
                'request_url' => array(
                    'scheme' => 'http',
                    'host'   => '',
                    'port'   => '',
                    'path'   => '/',
                    'query'  => ''
                ),
                'headers' => array(),
                'body'    => ''
            )),
            // Path and query string, multiple header values per header and case sensitive storage
            array("HEAD /path?query=foo HTTP/1.0\r\nHost: example.com\r\nX-Foo: foo\r\nx-foo: Bar\r\nX-Foo: foo\r\nX-Foo: Baz\r\n\r\n", array(
                'method'   => 'HEAD',
                'protocol' => 'HTTP',
                'version' => '1.0',
                'request_url' => array(
                    'scheme' => 'http',
                    'host'   => 'example.com',
                    'port'   => '',
                    'path'   => '/path',
                    'query'  => 'query=foo'
                ),
                'headers' => array(
                    'Host'  => 'example.com',
                    'X-Foo' => array('foo', 'foo', 'Baz'),
                    'x-foo' => 'Bar'
                ),
                'body'    => ''
            )),
            // Includes a body
            array("PUT / HTTP/1.0\r\nhost: example.com:443\r\nContent-Length: 4\r\n\r\ntest", array(
                'method'   => 'PUT',
                'protocol' => 'HTTP',
                'version' => '1.0',
                'request_url' => array(
                    'scheme' => 'https',
                    'host'   => 'example.com',
                    'port'   => '443',
                    'path'   => '/',
                    'query'  => ''
                ),
                'headers' => array(
                    'host'           => 'example.com:443',
                    'Content-Length' => '4'
                ),
                'body' => 'test'
            )),
            // Includes Authorization headers
            array("GET / HTTP/1.1\r\nHost: example.com:8080\r\nAuthorization: Basic {$auth}\r\n\r\n", array(
                'method'   => 'GET',
                'protocol' => 'HTTP',
                'version' => '1.1',
                'request_url' => array(
                    'scheme' => 'http',
                    'host'   => 'example.com',
                    'port'   => '8080',
                    'path'   => '/',
                    'query'  => ''
                ),
                'headers' => array(
                    'Host'           => 'example.com:8080',
                    'Authorization' => "Basic {$auth}"
                ),
                'body' => ''
            )),
            // Include authorization header
            array("GET / HTTP/1.1\r\nHost: example.com:8080\r\nauthorization: Basic {$auth}\r\n\r\n", array(
                'method'   => 'GET',
                'protocol' => 'HTTP',
                'version' => '1.1',
                'request_url' => array(
                    'scheme' => 'http',
                    'host'   => 'example.com',
                    'port'   => '8080',
                    'path'   => '/',
                    'query'  => ''
                ),
                'headers' => array(
                    'Host'           => 'example.com:8080',
                    'authorization' => "Basic {$auth}"
                ),
                'body' => ''
            )),
        );
    }

    public function responseProvider()
    {
        return array(
            // Empty request
            array('', false),

            array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", array(
                'protocol'      => 'HTTP',
                'version'       => '1.1',
                'code'          => '200',
                'reason_phrase' => 'OK',
                'headers'       => array(
                    'Content-Length' => 0
                ),
                'body'          => ''
            )),
            array("HTTP/1.0 400 Bad Request\r\nContent-Length: 0\r\n\r\n", array(
                'protocol'      => 'HTTP',
                'version'       => '1.0',
                'code'          => '400',
                'reason_phrase' => 'Bad Request',
                'headers'       => array(
                    'Content-Length' => 0
                ),
                'body'          => ''
            )),
            array("HTTP/1.0 100 Continue\r\n\r\n", array(
                'protocol'      => 'HTTP',
                'version'       => '1.0',
                'code'          => '100',
                'reason_phrase' => 'Continue',
                'headers'       => array(),
                'body'          => ''
            )),
            array("HTTP/1.1 204 No Content\r\nX-Foo: foo\r\nx-foo: Bar\r\nX-Foo: foo\r\n\r\n", array(
                'protocol'      => 'HTTP',
                'version'       => '1.1',
                'code'          => '204',
                'reason_phrase' => 'No Content',
                'headers'       => array(
                    'X-Foo' => array('foo', 'foo'),
                    'x-foo' => 'Bar'
                ),
                'body'          => ''
            )),
            array("HTTP/1.1 200 Ok that is great!\r\nContent-Length: 4\r\n\r\nTest", array(
                'protocol'      => 'HTTP',
                'version'       => '1.1',
                'code'          => '200',
                'reason_phrase' => 'Ok that is great!',
                'headers'       => array(
                    'Content-Length' => 4
                ),
                'body'          => 'Test'
            )),
        );
    }

    public function compareRequestResults($result, $expected)
    {
        if (!$result) {
            $this->assertFalse($expected);
            return;
        }

        $this->assertEquals($result['method'], $expected['method']);
        $this->assertEquals($result['protocol'], $expected['protocol']);
        $this->assertEquals($result['version'], $expected['version']);
        $this->assertEquals($result['request_url'], $expected['request_url']);
        $this->assertEquals($result['body'], $expected['body']);
        $this->compareHttpHeaders($result['headers'], $expected['headers']);
    }

    public function compareResponseResults($result, $expected)
    {
        if (!$result) {
            $this->assertFalse($expected);
            return;
        }

        $this->assertEquals($result['protocol'], $expected['protocol']);
        $this->assertEquals($result['version'], $expected['version']);
        $this->assertEquals($result['code'], $expected['code']);
        $this->assertEquals($result['reason_phrase'], $expected['reason_phrase']);
        $this->assertEquals($result['body'], $expected['body']);
        $this->compareHttpHeaders($result['headers'], $expected['headers']);
    }

    protected function normalizeHeaders($headers)
    {
        $normalized = array();
        foreach ($headers as $key => $value) {
            $key = strtolower($key);
            if (!isset($normalized[$key])) {
                $normalized[$key] = $value;
            } elseif (!is_array($normalized[$key])) {
                $normalized[$key] = array($value);
            } else {
                $normalized[$key][] = $value;
            }
        }

        foreach ($normalized as $key => &$value) {
            if (is_array($value)) {
                sort($value);
            }
        }

        return $normalized;
    }

    public function compareHttpHeaders($result, $expected)
    {
        // Aggregate all headers case-insensitively
        $result = $this->normalizeHeaders($result);
        $expected = $this->normalizeHeaders($expected);
        $this->assertEquals($result, $expected);
    }
}
<?php

namespace Guzzle\Tests\Parser\Cookie;

use Guzzle\Http\Url;

/**
 * @covers Guzzle\Parser\Cookie\CookieParser
 */
class CookieParserProvider extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * Provides the parsed information from a cookie
     *
     * @return array
     */
    public function cookieParserDataProvider()
    {
        return array(
            array(
                'ASIHTTPRequestTestCookie=This+is+the+value; expires=Sat, 26-Jul-2008 17:00:42 GMT; path=/tests; domain=allseeing-i.com; PHPSESSID=6c951590e7a9359bcedde25cda73e43c; path=/";',
                array(
                    'domain' => 'allseeing-i.com',
                    'path' => '/',
                    'data' => array(
                        'PHPSESSID' => '6c951590e7a9359bcedde25cda73e43c'
                    ),
                    'max_age' => NULL,
                    'expires' => 'Sat, 26-Jul-2008 17:00:42 GMT',
                    'version' => NULL,
                    'secure' => NULL,
                    'discard' => NULL,
                    'port' => NULL,
                    'cookies' => array(
                        'ASIHTTPRequestTestCookie' => 'This+is+the+value'
                    ),
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array('', false),
            array('foo', false),
            // Test setting a blank value for a cookie
            array(array(
                'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= '),
                array(
                    'cookies' => array(
                        'foo' => ''
                    ),
                    'data' => array(),
                    'discard' => null,
                    'domain' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            // Test setting a value and removing quotes
            array(array(
                'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;', 'foo="1"', 'foo="1";', 'foo= "1";'),
                array(
                    'cookies' => array(
                        'foo' => '1'
                    ),
                    'data' => array(),
                    'discard' => null,
                    'domain' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            // Test setting multiple values
            array(array(
                'foo=1; bar=2;', 'foo =1; bar = "2"', 'foo=1;   bar=2'),
                array(
                    'cookies' => array(
                        'foo' => '1',
                        'bar' => '2',
                    ),
                    'data' => array(),
                    'discard' => null,
                    'domain' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            // Tests getting the domain and path from a reference request
            array(array(
                'foo=1; port="80,8081"; httponly', 'foo=1; port="80,8081"; domain=www.test.com; HttpOnly;', 'foo=1; ; domain=www.test.com; path=/path; port="80,8081"; HttpOnly;'),
                array(
                    'cookies' => array(
                        'foo' => 1
                    ),
                    'data' => array(),
                    'discard' => null,
                    'domain' => 'www.test.com',
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/path',
                    'port' => array('80', '8081'),
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => true
                ),
                'http://www.test.com/path/'
            ),
            // Some of the following tests are based on http://framework.zend.com/svn/framework/standard/trunk/tests/Zend/Http/CookieTest.php
            array(
                'justacookie=foo; domain=example.com',
                array(
                    'cookies' => array(
                        'justacookie' => 'foo'
                    ),
                    'domain' => 'example.com',
                    'data' => array(),
                    'discard' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array(
                'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
                array(
                    'cookies' => array(
                        'expires' => 'tomorrow'
                    ),
                    'domain' => '.example.com',
                    'path' => '/Space Out/',
                    'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
                    'data' => array(),
                    'discard' => null,
                    'port' => null,
                    'secure' => true,
                    'version' => null,
                    'max_age' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array(
                'domain=unittests; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=example.com; path=/some value/',
                array(
                    'cookies' => array(
                        'domain' => 'unittests'
                    ),
                    'domain' => 'example.com',
                    'path' => '/some value/',
                    'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
                    'secure' => false,
                    'data' => array(),
                    'discard' => null,
                    'max_age' => null,
                    'port' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array(
                'path=indexAction; path=/; domain=.foo.com; expires=Tue, 21-Nov-2006 08:33:44 GMT',
                array(
                    'cookies' => array(
                        'path' => 'indexAction'
                    ),
                    'domain' => '.foo.com',
                    'path' => '/',
                    'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
                    'secure' => false,
                    'data' => array(),
                    'discard' => null,
                    'max_age' => null,
                    'port' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array(
                'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com; version=1; Max-Age=86400',
                array(
                    'cookies' => array(
                        'secure' => 'sha1'
                    ),
                    'domain' => 'some.really.deep.domain.com',
                    'path' => '/',
                    'secure' => true,
                    'data' => array(),
                    'discard' => null,
                    'expires' => time() + 86400,
                    'max_age' => 86400,
                    'port' => null,
                    'version' => 1,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            array(
                'PHPSESSID=123456789+abcd%2Cef; secure; discard; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
                array(
                    'cookies' => array(
                        'PHPSESSID' => '123456789+abcd%2Cef'
                    ),
                    'domain' => '.localdomain',
                    'path' => '/foo/baz',
                    'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
                    'secure' => true,
                    'data' => array(),
                    'discard' => true,
                    'max_age' => null,
                    'port' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                )
            ),
            // rfc6265#section-5.1.4
            array(
                'cookie=value',
                array(
                    'cookies' => array(
                        'cookie' => 'value'
                    ),
                    'domain' => 'example.com',
                    'data' => array(),
                    'discard' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/some/path',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                ),
                'http://example.com/some/path/test.html'
            ),
            array(
                'empty=path',
                array(
                    'cookies' => array(
                        'empty' => 'path'
                    ),
                    'domain' => 'example.com',
                    'data' => array(),
                    'discard' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                ),
                'http://example.com/test.html'
            ),
            array(
                'baz=qux',
                array(
                    'cookies' => array(
                        'baz' => 'qux'
                    ),
                    'domain' => 'example.com',
                    'data' => array(),
                    'discard' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                ),
                'http://example.com?query=here'
            ),
            array(
                'test=noSlashPath; path=someString',
                array(
                    'cookies' => array(
                        'test' => 'noSlashPath'
                    ),
                    'domain' => 'example.com',
                    'data' => array(),
                    'discard' => null,
                    'expires' => null,
                    'max_age' => null,
                    'path' => '/real/path',
                    'port' => null,
                    'secure' => null,
                    'version' => null,
                    'comment' => null,
                    'comment_url' => null,
                    'http_only' => false
                ),
                'http://example.com/real/path/'
            ),
        );
    }

    /**
     * @dataProvider cookieParserDataProvider
     */
    public function testParseCookie($cookie, $parsed, $url = null)
    {
        $c = $this->cookieParserClass;
        $parser = new $c();

        $request = null;
        if ($url) {
            $url = Url::factory($url);
            $host = $url->getHost();
            $path = $url->getPath();
        } else {
            $host = '';
            $path = '';
        }

        foreach ((array) $cookie as $c) {
            $p = $parser->parseCookie($c, $host, $path);

            // Remove expires values from the assertion if they are relatively equal by allowing a 5 minute difference
            if ($p['expires'] != $parsed['expires']) {
                if (abs($p['expires'] - $parsed['expires']) < 300) {
                    unset($p['expires']);
                    unset($parsed['expires']);
                }
            }

            if (is_array($parsed)) {
                foreach ($parsed as $key => $value) {
                    $this->assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
                }

                foreach ($p as $key => $value) {
                    $this->assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
                }
            } else {
                $this->assertEquals($parsed, $p);
            }
        }
    }
}
<?php

namespace Guzzle\Tests\Parser\Cookie;

use Guzzle\Parser\Cookie\CookieParser;

/**
 * @covers Guzzle\Parser\Cookie\CookieParser
 */
class CookieParserTest extends CookieParserProvider
{
    protected $cookieParserClass = 'Guzzle\Parser\Cookie\CookieParser';

    public function testUrlDecodesCookies()
    {
        $parser = new CookieParser();
        $result = $parser->parseCookie('foo=baz+bar', null, null, true);
        $this->assertEquals(array(
            'foo' => 'baz bar'
        ), $result['cookies']);
    }
}
<?php

namespace Guzzle\Tests\Parsers\UriTemplate;

use Guzzle\Parser\UriTemplate\UriTemplate;

/**
 * @covers Guzzle\Parser\UriTemplate\UriTemplate
 */
class UriTemplateTest extends AbstractUriTemplateTest
{
    /**
     * @dataProvider templateProvider
     */
    public function testExpandsUriTemplates($template, $expansion, $params)
    {
        $uri = new UriTemplate($template);
        $this->assertEquals($expansion, $uri->expand($template, $params));
    }

    public function expressionProvider()
    {
        return array(
            array(
                '{+var*}', array(
                    'operator' => '+',
                    'values'   => array(
                        array('value' => 'var', 'modifier' => '*')
                    )
                ),
            ),
            array(
                '{?keys,var,val}', array(
                    'operator' => '?',
                    'values'   => array(
                        array('value' => 'keys', 'modifier' => ''),
                        array('value' => 'var', 'modifier' => ''),
                        array('value' => 'val', 'modifier' => '')
                    )
                ),
            ),
            array(
                '{+x,hello,y}', array(
                    'operator' => '+',
                    'values'   => array(
                        array('value' => 'x', 'modifier' => ''),
                        array('value' => 'hello', 'modifier' => ''),
                        array('value' => 'y', 'modifier' => '')
                    )
                )
            )
        );
    }

    /**
     * @dataProvider expressionProvider
     */
    public function testParsesExpressions($exp, $data)
    {
        $template = new UriTemplate($exp);

        // Access the config object
        $class = new \ReflectionClass($template);
        $method = $class->getMethod('parseExpression');
        $method->setAccessible(true);

        $exp = substr($exp, 1, -1);
        $this->assertEquals($data, $method->invokeArgs($template, array($exp)));
    }

    /**
     * @ticket https://github.com/guzzle/guzzle/issues/90
     */
    public function testAllowsNestedArrayExpansion()
    {
        $template = new UriTemplate();

        $result = $template->expand('http://example.com{+path}{/segments}{?query,data*,foo*}', array(
            'path'     => '/foo/bar',
            'segments' => array('one', 'two'),
            'query'    => 'test',
            'data'     => array(
                'more' => array('fun', 'ice cream')
            ),
            'foo' => array(
                'baz' => array(
                    'bar'  => 'fizz',
                    'test' => 'buzz'
                ),
                'bam' => 'boo'
            )
        ));

        $this->assertEquals('http://example.com/foo/bar/one,two?query=test&more%5B0%5D=fun&more%5B1%5D=ice%20cream&baz%5Bbar%5D=fizz&baz%5Btest%5D=buzz&bam=boo', $result);
    }

    /**
     * @ticket https://github.com/guzzle/guzzle/issues/426
     */
    public function testSetRegex()
    {
        $template = new UriTemplate();
        $template->setRegex('/\<\$(.+)\>/');
        $this->assertSame('/foo', $template->expand('/<$a>', array('a' => 'foo')));
    }
}
<?php

namespace Guzzle\Tests\Parsers\UriTemplate;

use Guzzle\Parser\UriTemplate\PeclUriTemplate;

/**
 * @covers Guzzle\Parser\UriTemplate\PeclUriTemplate
 */
class PeclUriTemplateTest extends AbstractUriTemplateTest
{
    protected function setUp()
    {
        if (!extension_loaded('uri_template')) {
            $this->markTestSkipped('uri_template PECL extension must be installed to test PeclUriTemplate');
        }
    }

    /**
     * @dataProvider templateProvider
     */
    public function testExpandsUriTemplates($template, $expansion, $params)
    {
        $uri = new PeclUriTemplate($template);
        $this->assertEquals($expansion, $uri->expand($template, $params));
    }
}
<?php

namespace Guzzle\Tests\Parsers\UriTemplate;

abstract class AbstractUriTemplateTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @return array
     */
    public function templateProvider()
    {
        $t = array();
        $params = array(
            'var'   => 'value',
            'hello' => 'Hello World!',
            'empty' => '',
            'path'  => '/foo/bar',
            'x'     => '1024',
            'y'     => '768',
            'null'  => null,
            'list'  => array('red', 'green', 'blue'),
            'keys'  => array(
                "semi"  => ';',
                "dot"   => '.',
                "comma" => ','
            ),
            'empty_keys' => array(),
        );

        return array_map(function($t) use ($params) {
            $t[] = $params;
            return $t;
        }, array(
            array('foo',                 'foo'),
            array('{var}',               'value'),
            array('{hello}',             'Hello%20World%21'),
            array('{+var}',              'value'),
            array('{+hello}',            'Hello%20World!'),
            array('{+path}/here',        '/foo/bar/here'),
            array('here?ref={+path}',    'here?ref=/foo/bar'),
            array('X{#var}',             'X#value'),
            array('X{#hello}',           'X#Hello%20World!'),
            array('map?{x,y}',           'map?1024,768'),
            array('{x,hello,y}',         '1024,Hello%20World%21,768'),
            array('{+x,hello,y}',        '1024,Hello%20World!,768'),
            array('{+path,x}/here',      '/foo/bar,1024/here'),
            array('{#x,hello,y}',        '#1024,Hello%20World!,768'),
            array('{#path,x}/here',      '#/foo/bar,1024/here'),
            array('X{.var}',             'X.value'),
            array('X{.x,y}',             'X.1024.768'),
            array('{/var}',              '/value'),
            array('{/var,x}/here',       '/value/1024/here'),
            array('{;x,y}',              ';x=1024;y=768'),
            array('{;x,y,empty}',        ';x=1024;y=768;empty'),
            array('{?x,y}',              '?x=1024&y=768'),
            array('{?x,y,empty}',        '?x=1024&y=768&empty='),
            array('?fixed=yes{&x}',      '?fixed=yes&x=1024'),
            array('{&x,y,empty}',        '&x=1024&y=768&empty='),
            array('{var:3}',             'val'),
            array('{var:30}',            'value'),
            array('{list}',              'red,green,blue'),
            array('{list*}',             'red,green,blue'),
            array('{keys}',              'semi,%3B,dot,.,comma,%2C'),
            array('{keys*}',             'semi=%3B,dot=.,comma=%2C'),
            array('{+path:6}/here',      '/foo/b/here'),
            array('{+list}',             'red,green,blue'),
            array('{+list*}',            'red,green,blue'),
            array('{+keys}',             'semi,;,dot,.,comma,,'),
            array('{+keys*}',            'semi=;,dot=.,comma=,'),
            array('{#path:6}/here',      '#/foo/b/here'),
            array('{#list}',             '#red,green,blue'),
            array('{#list*}',            '#red,green,blue'),
            array('{#keys}',             '#semi,;,dot,.,comma,,'),
            array('{#keys*}',            '#semi=;,dot=.,comma=,'),
            array('X{.var:3}',           'X.val'),
            array('X{.list}',            'X.red,green,blue'),
            array('X{.list*}',           'X.red.green.blue'),
            array('X{.keys}',            'X.semi,%3B,dot,.,comma,%2C'),
            array('X{.keys*}',           'X.semi=%3B.dot=..comma=%2C'),
            array('{/var:1,var}',        '/v/value'),
            array('{/list}',             '/red,green,blue'),
            array('{/list*}',            '/red/green/blue'),
            array('{/list*,path:4}',     '/red/green/blue/%2Ffoo'),
            array('{/keys}',             '/semi,%3B,dot,.,comma,%2C'),
            array('{/keys*}',            '/semi=%3B/dot=./comma=%2C'),
            array('{;hello:5}',          ';hello=Hello'),
            array('{;list}',             ';list=red,green,blue'),
            array('{;list*}',            ';list=red;list=green;list=blue'),
            array('{;keys}',             ';keys=semi,%3B,dot,.,comma,%2C'),
            array('{;keys*}',            ';semi=%3B;dot=.;comma=%2C'),
            array('{?var:3}',            '?var=val'),
            array('{?list}',             '?list=red,green,blue'),
            array('{?list*}',            '?list=red&list=green&list=blue'),
            array('{?keys}',             '?keys=semi,%3B,dot,.,comma,%2C'),
            array('{?keys*}',            '?semi=%3B&dot=.&comma=%2C'),
            array('{&var:3}',            '&var=val'),
            array('{&list}',             '&list=red,green,blue'),
            array('{&list*}',            '&list=red&list=green&list=blue'),
            array('{&keys}',             '&keys=semi,%3B,dot,.,comma,%2C'),
            array('{&keys*}',            '&semi=%3B&dot=.&comma=%2C'),
            array('{.null}',            ''),
            array('{.null,var}',        '.value'),
            array('X{.empty_keys*}',     'X'),
            array('X{.empty_keys}',      'X'),
            // Test that missing expansions are skipped
            array('test{&missing*}',     'test'),
            // Test that multiple expansions can be set
            array('http://{var}/{var:2}{?keys*}', 'http://value/va?semi=%3B&dot=.&comma=%2C'),
            // Test more complex query string stuff
            array('http://www.test.com{+path}{?var,keys*}', 'http://www.test.com/foo/bar?var=value&semi=%3B&dot=.&comma=%2C')
        ));
    }
}
<?php

namespace Guzzle\Tests\Common;

use Guzzle\Common\Event;

/**
 * @covers Guzzle\Common\Event
 */
class EventTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @return Event
     */
    private function getEvent()
    {
        return new Event(array(
            'test'  => '123',
            'other' => '456',
            'event' => 'test.notify'
        ));
    }

    public function testAllowsParameterInjection()
    {
        $event = new Event(array(
            'test' => '123'
        ));
        $this->assertEquals('123', $event['test']);
    }

    public function testImplementsArrayAccess()
    {
        $event = $this->getEvent();
        $this->assertEquals('123', $event['test']);
        $this->assertNull($event['foobar']);

        $this->assertTrue($event->offsetExists('test'));
        $this->assertFalse($event->offsetExists('foobar'));

        unset($event['test']);
        $this->assertFalse($event->offsetExists('test'));

        $event['test'] = 'new';
        $this->assertEquals('new', $event['test']);
    }

    public function testImplementsIteratorAggregate()
    {
        $event = $this->getEvent();
        $this->assertInstanceOf('ArrayIterator', $event->getIterator());
    }

    public function testConvertsToArray()
    {
        $this->assertEquals(array(
            'test'  => '123',
            'other' => '456',
            'event' => 'test.notify'
        ), $this->getEvent()->toArray());
    }
}
<?php

namespace Guzzle\Tests\Common;

use Guzzle\Common\Version;

/**
 * @covers Guzzle\Common\Version
 */
class VersionTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \PHPUnit_Framework_Error_Deprecated
     */
    public function testEmitsWarnings()
    {
        Version::$emitWarnings = true;
        Version::warn('testing!');
    }

    public function testCanSilenceWarnings()
    {
        Version::$emitWarnings = false;
        Version::warn('testing!');
        Version::$emitWarnings = true;
    }
}
<?php

namespace Guzzle\Tests\Common;

use Guzzle\Common\Event;
use Guzzle\Common\AbstractHasDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * @covers Guzzle\Common\AbstractHasDispatcher
 */
class AbstractHasAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDoesNotRequireRegisteredEvents()
    {
        $this->assertEquals(array(), AbstractHasDispatcher::getAllEvents());
    }

    public function testAllowsDispatcherToBeInjected()
    {
        $d = new EventDispatcher();
        $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher');
        $this->assertSame($mock, $mock->setEventDispatcher($d));
        $this->assertSame($d, $mock->getEventDispatcher());
    }

    public function testCreatesDefaultEventDispatcherIfNeeded()
    {
        $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher');
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\EventDispatcher', $mock->getEventDispatcher());
    }

    public function testHelperDispatchesEvents()
    {
        $data = array();
        $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher');
        $mock->getEventDispatcher()->addListener('test', function(Event $e) use (&$data) {
            $data = $e->getIterator()->getArrayCopy();
        });
        $mock->dispatch('test', array(
            'param' => 'abc'
        ));
        $this->assertEquals(array(
            'param' => 'abc',
        ), $data);
    }

    public function testHelperAttachesSubscribers()
    {
        $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher');
        $subscriber = $this->getMockForAbstractClass('Symfony\Component\EventDispatcher\EventSubscriberInterface');

        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->setMethods(array('addSubscriber'))
            ->getMock();

        $dispatcher->expects($this->once())
            ->method('addSubscriber');

        $mock->setEventDispatcher($dispatcher);
        $mock->addSubscriber($subscriber);
    }
}
<?php

namespace Guzzle\Tests\Common;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\QueryString;

/**
 * @covers Guzzle\Common\Collection
 */
class CollectionTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Collection */
    protected $coll;

    protected function setUp()
    {
        $this->coll = new Collection();
    }

    public function testConstructorCanBeCalledWithNoParams()
    {
        $this->coll = new Collection();
        $p = $this->coll->getAll();
        $this->assertEmpty($p, '-> Collection must be empty when no data is passed');
    }

    public function testConstructorCanBeCalledWithParams()
    {
        $testData = array(
            'test' => 'value',
            'test_2' => 'value2'
        );
        $this->coll = new Collection($testData);
        $this->assertEquals($this->coll->getAll(), $testData, '-> getAll() must return the data passed in the constructor');
        $this->assertEquals($this->coll->getAll(), $this->coll->toArray());
    }

    public function testImplementsIteratorAggregate()
    {
        $this->coll->set('key', 'value');
        $this->assertInstanceOf('ArrayIterator', $this->coll->getIterator());
        $this->assertEquals(1, count($this->coll));
        $total = 0;
        foreach ($this->coll as $key => $value) {
            $this->assertEquals('key', $key);
            $this->assertEquals('value', $value);
            $total++;
        }
        $this->assertEquals(1, $total);
    }

    public function testCanAddValuesToExistingKeysByUsingArray()
    {
        $this->coll->add('test', 'value1');
        $this->assertEquals($this->coll->getAll(), array('test' => 'value1'));
        $this->coll->add('test', 'value2');
        $this->assertEquals($this->coll->getAll(), array('test' => array('value1', 'value2')));
        $this->coll->add('test', 'value3');
        $this->assertEquals($this->coll->getAll(), array('test' => array('value1', 'value2', 'value3')));
    }

    public function testHandlesMergingInDisparateDataSources()
    {
        $params = array(
            'test' => 'value1',
            'test2' => 'value2',
            'test3' => array('value3', 'value4')
        );
        $this->coll->merge($params);
        $this->assertEquals($this->coll->getAll(), $params);

        // Pass the same object to itself
        $this->assertEquals($this->coll->merge($this->coll), $this->coll);
    }

    public function testCanClearAllDataOrSpecificKeys()
    {
        $this->coll->merge(array(
            'test' => 'value1',
            'test2' => 'value2'
        ));

        // Clear a specific parameter by name
        $this->coll->remove('test');

        $this->assertEquals($this->coll->getAll(), array(
            'test2' => 'value2'
        ));

        // Clear all parameters
        $this->coll->clear();

        $this->assertEquals($this->coll->getAll(), array());
    }

    public function testGetsValuesByKey()
    {
        $this->assertNull($this->coll->get('test'));
        $this->coll->add('test', 'value');
        $this->assertEquals('value', $this->coll->get('test'));
        $this->coll->set('test2', 'v2');
        $this->coll->set('test3', 'v3');
        $this->assertEquals(array(
            'test' => 'value',
            'test2' => 'v2'
        ), $this->coll->getAll(array('test', 'test2')));
    }

    public function testProvidesKeys()
    {
        $this->assertEquals(array(), $this->coll->getKeys());
        $this->coll->merge(array(
            'test1' => 'value1',
            'test2' => 'value2'
        ));
        $this->assertEquals(array('test1', 'test2'), $this->coll->getKeys());
        // Returns the cached array previously returned
        $this->assertEquals(array('test1', 'test2'), $this->coll->getKeys());
        $this->coll->remove('test1');
        $this->assertEquals(array('test2'), $this->coll->getKeys());
        $this->coll->add('test3', 'value3');
        $this->assertEquals(array('test2', 'test3'), $this->coll->getKeys());
    }

    public function testChecksIfHasKey()
    {
        $this->assertFalse($this->coll->hasKey('test'));
        $this->coll->add('test', 'value');
        $this->assertEquals(true, $this->coll->hasKey('test'));
        $this->coll->add('test2', 'value2');
        $this->assertEquals(true, $this->coll->hasKey('test'));
        $this->assertEquals(true, $this->coll->hasKey('test2'));
        $this->assertFalse($this->coll->hasKey('testing'));
        $this->assertEquals(false, $this->coll->hasKey('AB-C', 'junk'));
    }

    public function testChecksIfHasValue()
    {
        $this->assertFalse($this->coll->hasValue('value'));
        $this->coll->add('test', 'value');
        $this->assertEquals('test', $this->coll->hasValue('value'));
        $this->coll->add('test2', 'value2');
        $this->assertEquals('test', $this->coll->hasValue('value'));
        $this->assertEquals('test2', $this->coll->hasValue('value2'));
        $this->assertFalse($this->coll->hasValue('val'));
    }

    public function testCanGetAllValuesByArray()
    {
        $this->coll->add('foo', 'bar');
        $this->coll->add('tEsT', 'value');
        $this->coll->add('tesTing', 'v2');
        $this->coll->add('key', 'v3');
        $this->assertNull($this->coll->get('test'));
        $this->assertEquals(array(
            'foo'     => 'bar',
            'tEsT'    => 'value',
            'tesTing' => 'v2'
        ), $this->coll->getAll(array(
            'foo', 'tesTing', 'tEsT'
        )));
    }

    public function testImplementsCount()
    {
        $data = new Collection();
        $this->assertEquals(0, $data->count());
        $data->add('key', 'value');
        $this->assertEquals(1, count($data));
        $data->add('key', 'value2');
        $this->assertEquals(1, count($data));
        $data->add('key_2', 'value3');
        $this->assertEquals(2, count($data));
    }

    public function testAddParamsByMerging()
    {
        $params = array(
            'test' => 'value1',
            'test2' => 'value2',
            'test3' => array('value3', 'value4')
        );

        // Add some parameters
        $this->coll->merge($params);

        // Add more parameters by merging them in
        $this->coll->merge(array(
            'test' => 'another',
            'different_key' => 'new value'
        ));

        $this->assertEquals(array(
            'test' => array('value1', 'another'),
            'test2' => 'value2',
            'test3' => array('value3', 'value4'),
            'different_key' => 'new value'
        ), $this->coll->getAll());
    }

    public function testAllowsFunctionalFilter()
    {
        $this->coll->merge(array(
            'fruit' => 'apple',
            'number' => 'ten',
            'prepositions' => array('about', 'above', 'across', 'after'),
            'same_number' => 'ten'
        ));

        $filtered = $this->coll->filter(function($key, $value) {
            return $value == 'ten';
        });

        $this->assertNotEquals($filtered, $this->coll);

        $this->assertEquals(array(
            'number' => 'ten',
            'same_number' => 'ten'
        ), $filtered->getAll());
    }

    public function testAllowsFunctionalMapping()
    {
        $this->coll->merge(array(
            'number_1' => 1,
            'number_2' => 2,
            'number_3' => 3
        ));

        $mapped = $this->coll->map(function($key, $value) {
            return $value * $value;
        });

        $this->assertNotEquals($mapped, $this->coll);

        $this->assertEquals(array(
            'number_1' => 1,
            'number_2' => 4,
            'number_3' => 9
        ), $mapped->getAll());
    }

    public function testImplementsArrayAccess()
    {
        $this->coll->merge(array(
            'k1' => 'v1',
            'k2' => 'v2'
        ));

        $this->assertTrue($this->coll->offsetExists('k1'));
        $this->assertFalse($this->coll->offsetExists('Krull'));

        $this->coll->offsetSet('k3', 'v3');
        $this->assertEquals('v3', $this->coll->offsetGet('k3'));
        $this->assertEquals('v3', $this->coll->get('k3'));

        $this->coll->offsetUnset('k1');
        $this->assertFalse($this->coll->offsetExists('k1'));
    }

    public function testUsesStaticWhenCreatingNew()
    {
        $qs = new QueryString(array(
            'a' => 'b',
            'c' => 'd'
        ));

        $this->assertInstanceOf('Guzzle\\Http\\QueryString', $qs->map(function($a, $b) {}));
        $this->assertInstanceOf('Guzzle\\Common\\Collection', $qs->map(function($a, $b) {}, array(), false));

        $this->assertInstanceOf('Guzzle\\Http\\QueryString', $qs->filter(function($a, $b) {}));
        $this->assertInstanceOf('Guzzle\\Common\\Collection', $qs->filter(function($a, $b) {}, false));
    }

    public function testCanReplaceAllData()
    {
        $this->assertSame($this->coll, $this->coll->replace(array(
            'a' => '123'
        )));

        $this->assertEquals(array(
            'a' => '123'
        ), $this->coll->getAll());
    }

    public function dataProvider()
    {
        return array(
            array('this_is_a_test', '{a}_is_a_{b}', array(
                'a' => 'this',
                'b' => 'test'
            )),
            array('this_is_a_test', '{abc}_is_a_{0}', array(
                'abc' => 'this',
                0 => 'test'
            )),
            array('this_is_a_test', '{abc}_is_a_{0}', array(
                'abc' => 'this',
                0 => 'test'
            )),
            array('this_is_a_test', 'this_is_a_test', array(
                'abc' => 'this'
            )),
            array('{abc}_is_{not_found}a_{0}', '{abc}_is_{not_found}a_{0}', array())
        );
    }

    /**
     * @dataProvider dataProvider
     */
    public function testInjectsConfigData($output, $input, $config)
    {
        $collection = new Collection($config);
        $this->assertEquals($output, $collection->inject($input));
    }

    public function testCanSearchByKey()
    {
        $collection = new Collection(array(
            'foo' => 'bar',
            'BaZ' => 'pho'
        ));

        $this->assertEquals('foo', $collection->keySearch('FOO'));
        $this->assertEquals('BaZ', $collection->keySearch('baz'));
        $this->assertEquals(false, $collection->keySearch('Bar'));
    }

    public function testPreparesFromConfig()
    {
        $c = Collection::fromConfig(array(
            'a' => '123',
            'base_url' => 'http://www.test.com/'
        ), array(
            'a' => 'xyz',
            'b' => 'lol'
        ), array('a'));

        $this->assertInstanceOf('Guzzle\Common\Collection', $c);
        $this->assertEquals(array(
            'a' => '123',
            'b' => 'lol',
            'base_url' => 'http://www.test.com/'
        ), $c->getAll());

        try {
            $c = Collection::fromConfig(array(), array(), array('a'));
            $this->fail('Exception not throw when missing config');
        } catch (InvalidArgumentException $e) {
        }
    }

    function falseyDataProvider()
    {
        return array(
            array(false, false),
            array(null, null),
            array('', ''),
            array(array(), array()),
            array(0, 0),
        );
    }

    /**
     * @dataProvider falseyDataProvider
     */
    public function testReturnsCorrectData($a, $b)
    {
        $c = new Collection(array('value' => $a));
        $this->assertSame($b, $c->get('value'));
    }

    public function testRetrievesNestedKeysUsingPath()
    {
        $data = array(
            'foo' => 'bar',
            'baz' => array(
                'mesa' => array(
                    'jar' => 'jar'
                )
            )
        );
        $collection = new Collection($data);
        $this->assertEquals('bar', $collection->getPath('foo'));
        $this->assertEquals('jar', $collection->getPath('baz/mesa/jar'));
        $this->assertNull($collection->getPath('wewewf'));
        $this->assertNull($collection->getPath('baz/mesa/jar/jar'));
    }

    public function testFalseyKeysStillDescend()
    {
        $collection = new Collection(array(
            '0' => array(
                'a' => 'jar'
            ),
            1 => 'other'
        ));
        $this->assertEquals('jar', $collection->getPath('0/a'));
        $this->assertEquals('other', $collection->getPath('1'));
    }

    public function getPathProvider()
    {
        $data = array(
            'foo' => 'bar',
            'baz' => array(
                'mesa' => array(
                    'jar' => 'jar',
                    'array' => array('a', 'b', 'c')
                ),
                'bar' => array(
                    'baz' => 'bam',
                    'array' => array('d', 'e', 'f')
                )
            ),
            'bam' => array(
                array('foo' => 1),
                array('foo' => 2),
                array('array' => array('h', 'i'))
            )
        );
        $c = new Collection($data);

        return array(
            // Simple path selectors
            array($c, 'foo', 'bar'),
            array($c, 'baz', $data['baz']),
            array($c, 'bam', $data['bam']),
            array($c, 'baz/mesa', $data['baz']['mesa']),
            array($c, 'baz/mesa/jar', 'jar'),
            // Merge everything two levels under baz
            array($c, 'baz/*', array(
                'jar' => 'jar',
                'array' => array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array']),
                'baz' => 'bam'
            )),
            // Does not barf on missing keys
            array($c, 'fefwfw', null),
            // Does not barf when a wildcard does not resolve correctly
            array($c, '*/*/*/*/*/wefwfe', array()),
            // Allows custom separator
            array($c, '*|mesa', $data['baz']['mesa'], '|'),
            // Merge all 'array' keys two levels under baz (the trailing * does not hurt the results)
            array($c, 'baz/*/array/*', array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array'])),
            // Merge all 'array' keys two levels under baz
            array($c, 'baz/*/array', array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array'])),
            array($c, 'baz/mesa/array', $data['baz']['mesa']['array']),
            // Having a trailing * does not hurt the results
            array($c, 'baz/mesa/array/*', $data['baz']['mesa']['array']),
            // Merge of anything one level deep
            array($c, '*', array_merge(array('bar'), $data['baz'], $data['bam'])),
            // Funky merge of anything two levels deep
            array($c, '*/*', array(
                'jar' => 'jar',
                'array' => array('a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'),
                'baz' => 'bam',
                'foo' => array(1, 2)
            )),
            // Funky merge of all 'array' keys that are two levels deep
            array($c, '*/*/array', array('a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'))
        );
    }

    /**
     * @dataProvider getPathProvider
     */
    public function testGetPath(Collection $c, $path, $expected, $separator = '/')
    {
        $this->assertEquals($expected, $c->getPath($path, $separator));
    }

    public function testOverridesSettings()
    {
        $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3));
        $c->overwriteWith(array('foo' => 10, 'bar' => 300));
        $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll());
    }

    public function testOverwriteWithCollection()
    {
        $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3));
        $b = new Collection(array('foo' => 10, 'bar' => 300));
        $c->overwriteWith($b);
        $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll());
    }

    public function testOverwriteWithTraversable()
    {
        $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3));
        $b = new Collection(array('foo' => 10, 'bar' => 300));
        $c->overwriteWith($b->getIterator());
        $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll());
    }

    public function testCanSetNestedPathValueThatDoesNotExist()
    {
        $c = new Collection(array());
        $c->setPath('foo/bar/baz/123', 'hi');
        $this->assertEquals('hi', $c['foo']['bar']['baz']['123']);
    }

    public function testCanSetNestedPathValueThatExists()
    {
        $c = new Collection(array('foo' => array('bar' => 'test')));
        $c->setPath('foo/bar', 'hi');
        $this->assertEquals('hi', $c['foo']['bar']);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     */
    public function testVerifiesNestedPathIsValidAtExactLevel()
    {
        $c = new Collection(array('foo' => 'bar'));
        $c->setPath('foo/bar', 'hi');
        $this->assertEquals('hi', $c['foo']['bar']);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     */
    public function testVerifiesThatNestedPathIsValidAtAnyLevel()
    {
        $c = new Collection(array('foo' => 'bar'));
        $c->setPath('foo/bar/baz', 'test');
    }
}
<?php

namespace Guzzle\Tests\Common\Exception;

use Guzzle\Batch\Exception\BatchTransferException;

class BatchTransferExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testContainsBatch()
    {
        $e = new \Exception('Baz!');
        $t = $this->getMock('Guzzle\Batch\BatchTransferInterface');
        $d = $this->getMock('Guzzle\Batch\BatchDivisorInterface');
        $transferException = new BatchTransferException(array('foo'), array(1, 2), $e, $t, $d);
        $this->assertEquals(array('foo'), $transferException->getBatch());
        $this->assertSame($t, $transferException->getTransferStrategy());
        $this->assertSame($d, $transferException->getDivisorStrategy());
        $this->assertSame($e, $transferException->getPrevious());
        $this->assertEquals(array(1, 2), $transferException->getTransferredItems());
    }
}
<?php

namespace Guzzle\Tests\Common\Exception;

use Guzzle\Common\Exception\ExceptionCollection;

class ExceptionCollectionTest extends \Guzzle\Tests\GuzzleTestCase
{
    private function getExceptions()
    {
        return array(
            new \Exception('Test'),
            new \Exception('Testing')
        );
    }

    public function testAggregatesExceptions()
    {
        $e = new ExceptionCollection();
        $exceptions = $this->getExceptions();
        $e->add($exceptions[0]);
        $e->add($exceptions[1]);
        $this->assertContains("(Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $e->getMessage());
        $this->assertContains("    Test\n\n    #0 ./", $e->getMessage());
        $this->assertSame($exceptions[0], $e->getFirst());
    }

    public function testCanSetExceptions()
    {
        $ex = new \Exception('foo');
        $e = new ExceptionCollection();
        $e->setExceptions(array($ex));
        $this->assertSame($ex, $e->getFirst());
    }

    public function testActsAsArray()
    {
        $e = new ExceptionCollection();
        $exceptions = $this->getExceptions();
        $e->add($exceptions[0]);
        $e->add($exceptions[1]);
        $this->assertEquals(2, count($e));
        $this->assertEquals($exceptions, $e->getIterator()->getArrayCopy());
    }

    public function testCanAddSelf()
    {
        $e1 = new ExceptionCollection();
        $e1->add(new \Exception("Test"));
        $e2 = new ExceptionCollection('Meta description!');
        $e2->add(new \Exception("Test 2"));
        $e3 = new ExceptionCollection();
        $e3->add(new \Exception('Baz'));
        $e2->add($e3);
        $e1->add($e2);
        $message = $e1->getMessage();
        $this->assertContains("(Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message);
        $this->assertContains("\n    Test\n\n    #0 ", $message);
        $this->assertContains("\n\n(Guzzle\\Common\\Exception\\ExceptionCollection) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message);
        $this->assertContains("\n\n    Meta description!\n\n", $message);
        $this->assertContains("    (Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message);
        $this->assertContains("\n        Test 2\n\n        #0 ", $message);
        $this->assertContains("        (Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message);
        $this->assertContains("            Baz\n\n            #0", $message);
    }
}
<?php

namespace Guzzle\Tests\Iterator;

use Guzzle\Iterator\ChunkedIterator;

/**
 * @covers Guzzle\Iterator\ChunkedIterator
 */
class ChunkedIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testChunksIterator()
    {
        $chunked = new ChunkedIterator(new \ArrayIterator(range(0, 100)), 10);
        $chunks = iterator_to_array($chunked, false);
        $this->assertEquals(11, count($chunks));
        foreach ($chunks as $j => $chunk) {
            $this->assertEquals(range($j * 10, min(100, $j * 10 + 9)), $chunk);
        }
    }

    public function testChunksIteratorWithOddValues()
    {
        $chunked = new ChunkedIterator(new \ArrayIterator(array(1, 2, 3, 4, 5)), 2);
        $chunks = iterator_to_array($chunked, false);
        $this->assertEquals(3, count($chunks));
        $this->assertEquals(array(1, 2), $chunks[0]);
        $this->assertEquals(array(3, 4), $chunks[1]);
        $this->assertEquals(array(5), $chunks[2]);
    }

    public function testMustNotTerminateWithTraversable()
    {
        $traversable = simplexml_load_string('<root><foo/><foo/><foo/></root>')->foo;
        $chunked = new ChunkedIterator($traversable, 2);
        $actual = iterator_to_array($chunked, false);
        $this->assertCount(2, $actual);
    }

    public function testSizeOfZeroMakesIteratorInvalid() {
        $chunked = new ChunkedIterator(new \ArrayIterator(range(1, 5)), 0);
        $chunked->rewind();
        $this->assertFalse($chunked->valid());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSizeLowerZeroThrowsException() {
        new ChunkedIterator(new \ArrayIterator(range(1, 5)), -1);
    }
}
<?php

namespace Guzzle\Tests\Iterator;

use Guzzle\Iterator\AppendIterator;

/**
 * @covers Guzzle\Iterator\AppendIterator
 */
class AppendIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testTraversesIteratorsInOrder()
    {
        $a = new \ArrayIterator(array(
            'a' => 1,
            'b' => 2
        ));
        $b = new \ArrayIterator(array());
        $c = new \ArrayIterator(array(
            'c' => 3,
            'd' => 4
        ));
        $i = new AppendIterator();
        $i->append($a);
        $i->append($b);
        $i->append($c);
        $this->assertEquals(array(1, 2, 3, 4), iterator_to_array($i, false));
    }
}
<?php

namespace Guzzle\Tests\Iterator;

use Guzzle\Iterator\MapIterator;

/**
 * @covers Guzzle\Iterator\MapIterator
 */
class MapIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testFiltersValues()
    {
        $i = new MapIterator(new \ArrayIterator(range(0, 100)), function ($value) {
            return $value * 10;
        });

        $this->assertEquals(range(0, 1000, 10), iterator_to_array($i, false));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesCallable()
    {
        $i = new MapIterator(new \ArrayIterator(), new \stdClass());
    }
}
<?php

namespace Guzzle\Tests\Iterator;

use Guzzle\Iterator\FilterIterator;

/**
 * @covers Guzzle\Iterator\FilterIterator
 */
class FilterIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testFiltersValues()
    {
        $i = new FilterIterator(new \ArrayIterator(range(0, 100)), function ($value) {
            return $value % 2;
        });

        $this->assertEquals(range(1, 99, 2), iterator_to_array($i, false));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesCallable()
    {
        $i = new FilterIterator(new \ArrayIterator(), new \stdClass());
    }
}
<?php

namespace Guzzle\Tests\Iterator;

use Guzzle\Iterator\MethodProxyIterator;
use Guzzle\Iterator\ChunkedIterator;

/**
 * @covers Guzzle\Iterator\MethodProxyIterator
 */
class MethodProxyIteratorTest extends \PHPUnit_Framework_TestCase
{
    public function testProxiesMagicCallsToInnermostIterator()
    {
        $i = new \ArrayIterator();
        $proxy = new MethodProxyIterator(new MethodProxyIterator(new MethodProxyIterator($i)));
        $proxy->append('a');
        $proxy->append('b');
        $this->assertEquals(array('a', 'b'), $i->getArrayCopy());
        $this->assertEquals(array('a', 'b'), $proxy->getArrayCopy());
    }

    public function testUsesInnerIterator()
    {
        $i = new MethodProxyIterator(new ChunkedIterator(new \ArrayIterator(array(1, 2, 3, 4, 5)), 2));
        $this->assertEquals(3, count(iterator_to_array($i, false)));
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\EntityBody;
use Guzzle\Http\IoEmittingEntityBody;

/**
 * @covers Guzzle\Http\IoEmittingEntityBody
 */
class IoEmittingEntityBodyTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $body;
    protected $decorated;

    public function setUp()
    {
        $this->decorated = EntityBody::factory('hello');
        $this->body = new IoEmittingEntityBody($this->decorated);
    }

    public function testEmitsReadEvents()
    {
        $e = null;
        $this->body->getEventDispatcher()->addListener('body.read', function ($event) use (&$e) {
            $e = $event;
        });
        $this->assertEquals('hel', $this->body->read(3));
        $this->assertEquals('hel', $e['read']);
        $this->assertEquals(3, $e['length']);
        $this->assertSame($this->body, $e['body']);
    }

    public function testEmitsWriteEvents()
    {
        $e = null;
        $this->body->getEventDispatcher()->addListener('body.write', function ($event) use (&$e) {
            $e = $event;
        });
        $this->body->seek(0, SEEK_END);
        $this->assertEquals(5, $this->body->write('there'));
        $this->assertEquals('there', $e['write']);
        $this->assertEquals(5, $e['result']);
        $this->assertSame($this->body, $e['body']);
        $this->assertEquals('hellothere', (string) $this->body);
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\QueryString;
use Guzzle\Http\QueryAggregator\CommaAggregator as Ag;

class CommaAggregatorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testAggregates()
    {
        $query = new QueryString();
        $a = new Ag();
        $key = 'test 123';
        $value = array('foo 123', 'baz', 'bar');
        $result = $a->aggregate($key, $value, $query);
        $this->assertEquals(array('test%20123' => 'foo%20123,baz,bar'), $result);
    }

    public function testEncodes()
    {
        $query = new QueryString();
        $query->useUrlEncoding(false);
        $a = new Ag();
        $key = 'test 123';
        $value = array('foo 123', 'baz', 'bar');
        $result = $a->aggregate($key, $value, $query);
        $this->assertEquals(array('test 123' => 'foo 123,baz,bar'), $result);
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\QueryString;
use Guzzle\Http\QueryAggregator\PhpAggregator as Ag;

class PhpAggregatorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testEncodes()
    {
        $query = new QueryString();
        $query->useUrlEncoding(false);
        $a = new Ag();
        $key = 't';
        $value = array(
            'v1' => 'a',
            'v2' => 'b',
            'v3' => array(
                'v4' => 'c',
                'v5' => 'd',
            )
        );
        $result = $a->aggregate($key, $value, $query);
        $this->assertEquals(array(
            't[v1]' => 'a',
            't[v2]' => 'b',
            't[v3][v4]' => 'c',
            't[v3][v5]' => 'd',
        ), $result);
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\QueryString;
use Guzzle\Http\QueryAggregator\DuplicateAggregator as Ag;

class DuplicateAggregatorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testAggregates()
    {
        $query = new QueryString();
        $a = new Ag();
        $key = 'facet 1';
        $value = array('size a', 'width b');
        $result = $a->aggregate($key, $value, $query);
        $this->assertEquals(array('facet%201' => array('size%20a', 'width%20b')), $result);
    }

    public function testEncodes()
    {
        $query = new QueryString();
        $query->useUrlEncoding(false);
        $a = new Ag();
        $key = 'facet 1';
        $value = array('size a', 'width b');
        $result = $a->aggregate($key, $value, $query);
        $this->assertEquals(array('facet 1' => array('size a', 'width b')), $result);
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Client;

/**
 * The Server class is used to control a scripted webserver using node.js that
 * will respond to HTTP requests with queued responses.
 *
 * Queued responses will be served to requests using a FIFO order.  All requests
 * received by the server are stored on the node.js server and can be retrieved
 * by calling {@see Server::getReceivedRequests()}.
 *
 * Mock responses that don't require data to be transmitted over HTTP a great
 * for testing.  Mock response, however, cannot test the actual sending of an
 * HTTP request using cURL.  This test server allows the simulation of any
 * number of HTTP request response transactions to test the actual sending of
 * requests over the wire without having to leave an internal network.
 */
class Server
{
    const DEFAULT_PORT = 8124;
    const REQUEST_DELIMITER = "\n----[request]\n";

    /** @var int Port that the server will listen on */
    private $port;

    /** @var bool Is the server running */
    private $running = false;

    /** @var Client */
    private $client;

    /**
     * Create a new scripted server
     *
     * @param int $port Port to listen on (defaults to 8124)
     */
    public function __construct($port = null)
    {
        $this->port = $port ?: self::DEFAULT_PORT;
        $this->client = new Client($this->getUrl());
        register_shutdown_function(array($this, 'stop'));
    }

    /**
     * Flush the received requests from the server
     * @throws RuntimeException
     */
    public function flush()
    {
        $this->client->delete('guzzle-server/requests')->send();
    }

    /**
     * Queue an array of responses or a single response on the server.
     *
     * Any currently queued responses will be overwritten.  Subsequent requests
     * on the server will return queued responses in FIFO order.
     *
     * @param array|Response $responses A single or array of Responses to queue
     * @throws BadResponseException
     */
    public function enqueue($responses)
    {
        $data = array();
        foreach ((array) $responses as $response) {

            // Create the response object from a string
            if (is_string($response)) {
                $response = Response::fromMessage($response);
            } elseif (!($response instanceof Response)) {
                throw new BadResponseException('Responses must be strings or implement Response');
            }

            $data[] = array(
                'statusCode'   => $response->getStatusCode(),
                'reasonPhrase' => $response->getReasonPhrase(),
                'headers'      => $response->getHeaders()->toArray(),
                'body'         => $response->getBody(true)
            );
        }

        $request = $this->client->put('guzzle-server/responses', null, json_encode($data));
        $request->send();
    }

    /**
     * Check if the server is running
     *
     * @return bool
     */
    public function isRunning()
    {
        if ($this->running) {
            return true;
        }

        try {
            $this->client->get('guzzle-server/perf', array(), array('timeout' => 5))->send();
            $this->running = true;
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Get the URL to the server
     *
     * @return string
     */
    public function getUrl()
    {
        return 'http://127.0.0.1:' . $this->getPort() . '/';
    }

    /**
     * Get the port that the server is listening on
     *
     * @return int
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * Get all of the received requests
     *
     * @param bool $hydrate Set to TRUE to turn the messages into
     *      actual {@see RequestInterface} objects.  If $hydrate is FALSE,
     *      requests will be returned as strings.
     *
     * @return array
     * @throws RuntimeException
     */
    public function getReceivedRequests($hydrate = false)
    {
        $response = $this->client->get('guzzle-server/requests')->send();
        $data = array_filter(explode(self::REQUEST_DELIMITER, $response->getBody(true)));
        if ($hydrate) {
            $data = array_map(function($message) {
                return RequestFactory::getInstance()->fromMessage($message);
            }, $data);
        }

        return $data;
    }

    /**
     * Start running the node.js server in the background
     */
    public function start()
    {
        if (!$this->isRunning()) {
            exec('node ' . __DIR__ . \DIRECTORY_SEPARATOR
                . 'server.js ' . $this->port
                . ' >> /tmp/server.log 2>&1 &');
            // Wait at most 5 seconds for the server the setup before
            // proceeding.
            $start = time();
            while (!$this->isRunning() && time() - $start < 5);
            if (!$this->running) {
                throw new RuntimeException(
                    'Unable to contact server.js. Have you installed node.js v0.5.0+? node must be in your path.'
                );
            }
        }
    }

    /**
     * Stop running the node.js server
     */
    public function stop()
    {
        if (!$this->isRunning()) {
            return false;
        }

        $this->running = false;
        $this->client->delete('guzzle-server')->send();
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\Mimetypes;

/**
 * @covers Guzzle\Http\Mimetypes
 */
class MimetypesTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testGetsFromExtension()
    {
        $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromExtension('php'));
    }

    public function testGetsFromFilename()
    {
        $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(__FILE__));
    }

    public function testGetsFromCaseInsensitiveFilename()
    {
        $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(strtoupper(__FILE__)));
    }

    public function testReturnsNullWhenNoMatchFound()
    {
        $this->assertNull(Mimetypes::getInstance()->fromExtension('foobar'));
    }
}
/**
 * Guzzle node.js test server to return queued responses to HTTP requests and
 * expose a RESTful API for enqueueing responses and retrieving the requests
 * that have been received.
 *
 * - Delete all requests that have been received:
 *      DELETE /guzzle-server/requests
 *      Host: 127.0.0.1:8124
 *
 *  - Enqueue responses
 *      PUT /guzzle-server/responses
 *      Host: 127.0.0.1:8124
 *
 *      [{ "statusCode": 200, "reasonPhrase": "OK", "headers": {}, "body": "" }]
 *
 *  - Get the received requests
 *      GET /guzzle-server/requests
 *      Host: 127.0.0.1:8124
 *
 *  - Shutdown the server
 *      DELETE /guzzle-server
 *      Host: 127.0.0.1:8124
 *
 * @package Guzzle PHP <http://www.guzzlephp.org>
 * @license See the LICENSE file that was distributed with this source code.
 */

var http = require("http");

/**
 * Guzzle node.js server
 * @class
 */
var GuzzleServer = function(port, log) {

    this.port = port;
    this.log = log;
    this.responses = [];
    this.requests = [];
    var that = this;

    var controlRequest = function(request, req, res) {
        if (req.url == '/guzzle-server/perf') {
            res.writeHead(200, "OK", {"Content-Length": 16});
            res.end("Body of response");
        } else if (req.method == "DELETE") {
            if (req.url == "/guzzle-server/requests") {
                // Clear the received requests
                that.requests = [];
                res.writeHead(200, "OK", { "Content-Length": 0 });
                res.end();
                if (this.log) {
                    console.log("Flushing requests");
                }
            } else if (req.url == "/guzzle-server") {
                // Shutdown the server
                res.writeHead(200, "OK", { "Content-Length": 0, "Connection": "close" });
                res.end();
                if (this.log) {
                    console.log("Shutting down");
                }
                that.server.close();
            }
        } else if (req.method == "GET") {
            if (req.url === "/guzzle-server/requests") {
                // Get received requests
                var data = that.requests.join("\n----[request]\n");
                res.writeHead(200, "OK", { "Content-Length": data.length });
                res.end(data);
                if (that.log) {
                    console.log("Sending receiving requests");
                }
            }
        } else if (req.method == "PUT") {
            if (req.url == "/guzzle-server/responses") {
                if (that.log) {
                    console.log("Adding responses...");
                }
                // Received response to queue
                var data = request.split("\r\n\r\n")[1];
                if (!data) {
                    if (that.log) {
                        console.log("No response data was provided");
                    }
                    res.writeHead(400, "NO RESPONSES IN REQUEST", { "Content-Length": 0 });
                } else {
                    that.responses = eval("(" + data + ")");
                    if (that.log) {
                        console.log(that.responses);
                    }
                    res.writeHead(200, "OK", { "Content-Length": 0 });
                }
                res.end();
            }
        }
    };

    var receivedRequest = function(request, req, res) {
        if (req.url.indexOf("/guzzle-server") === 0) {
            controlRequest(request, req, res);
        } else if (req.url.indexOf("/guzzle-server") == -1 && !that.responses.length) {
            res.writeHead(500);
            res.end("No responses in queue");
        } else {
            var response = that.responses.shift();
            res.writeHead(response.statusCode, response.reasonPhrase, response.headers);
            res.end(response.body);
            that.requests.push(request);
        }
    };

    this.start = function() {

        that.server = http.createServer(function(req, res) {

            var request = req.method + " " + req.url + " HTTP/" + req.httpVersion + "\r\n";
            for (var i in req.headers) {
                request += i + ": " + req.headers[i] + "\r\n";
            }
            request += "\r\n";

            // Receive each chunk of the request body
            req.addListener("data", function(chunk) {
                request += chunk;
            });

            // Called when the request completes
            req.addListener("end", function() {
                receivedRequest(request, req, res);
            });
        });
        that.server.listen(port, "127.0.0.1");

        if (this.log) {
            console.log("Server running at http://127.0.0.1:8124/");
        }
    };
};

// Get the port from the arguments
port = process.argv.length >= 3 ? process.argv[2] : 8124;
log = process.argv.length >= 4 ? process.argv[3] : false;

// Start the server
server = new GuzzleServer(port, log);
server.start();
<?php

namespace Guzzle\Tests\Plugin\Redirect;

use Guzzle\Http\Client;
use Guzzle\Http\EntityBody;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Exception\TooManyRedirectsException;
use Guzzle\Plugin\History\HistoryPlugin;

/**
 * @covers Guzzle\Http\RedirectPlugin
 */
class RedirectPluginTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testRedirectsRequests()
    {
        // Flush the server and queue up a redirect followed by a successful response
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        // Create a client that uses the default redirect behavior
        $client = new Client($this->getServer()->getUrl());
        $history = new HistoryPlugin();
        $client->addSubscriber($history);

        $request = $client->get('/foo');
        $response = $request->send();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertContains('/redirect2', $response->getEffectiveUrl());

        // Ensure that two requests were sent
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('/foo', $requests[0]->getResource());
        $this->assertEquals('GET', $requests[0]->getMethod());
        $this->assertEquals('/redirect1', $requests[1]->getResource());
        $this->assertEquals('GET', $requests[1]->getMethod());
        $this->assertEquals('/redirect2', $requests[2]->getResource());
        $this->assertEquals('GET', $requests[2]->getMethod());

        // Ensure that the redirect count was incremented
        $this->assertEquals(2, $request->getParams()->get(RedirectPlugin::REDIRECT_COUNT));
        $this->assertCount(3, $history);
        $requestHistory = $history->getAll();

        $this->assertEquals(301, $requestHistory[0]['response']->getStatusCode());
        $this->assertEquals('/redirect1', (string) $requestHistory[0]['response']->getHeader('Location'));
        $this->assertEquals(301, $requestHistory[1]['response']->getStatusCode());
        $this->assertEquals('/redirect2', (string) $requestHistory[1]['response']->getHeader('Location'));
        $this->assertEquals(200, $requestHistory[2]['response']->getStatusCode());
    }

    public function testCanLimitNumberOfRedirects()
    {
        // Flush the server and queue up a redirect followed by a successful response
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect3\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect4\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect5\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect6\r\nContent-Length: 0\r\n\r\n"
        ));

        try {
            $client = new Client($this->getServer()->getUrl());
            $client->get('/foo')->send();
            $this->fail('Did not throw expected exception');
        } catch (TooManyRedirectsException $e) {
            $this->assertContains(
                "5 redirects were issued for this request:\nGET /foo HTTP/1.1\r\n",
                $e->getMessage()
            );
        }
    }

    public function testDefaultBehaviorIsToRedirectWithGetForEntityEnclosingRequests()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        $client = new Client($this->getServer()->getUrl());
        $client->post('/foo', array('X-Baz' => 'bar'), 'testing')->send();

        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('POST', $requests[0]->getMethod());
        $this->assertEquals('GET', $requests[1]->getMethod());
        $this->assertEquals('bar', (string) $requests[1]->getHeader('X-Baz'));
        $this->assertEquals('GET', $requests[2]->getMethod());
    }

    public function testCanRedirectWithStrictRfcCompliance()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->post('/foo', array('X-Baz' => 'bar'), 'testing');
        $request->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, true);
        $request->send();

        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('POST', $requests[0]->getMethod());
        $this->assertEquals('POST', $requests[1]->getMethod());
        $this->assertEquals('bar', (string) $requests[1]->getHeader('X-Baz'));
        $this->assertEquals('POST', $requests[2]->getMethod());
    }

    public function testRedirect303WithGet()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
             "HTTP/1.1 303 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
             "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->post('/foo');
        $request->send();

        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('POST', $requests[0]->getMethod());
        $this->assertEquals('GET', $requests[1]->getMethod());
    }

    public function testRedirect303WithGetWithStrictRfcCompliance()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
             "HTTP/1.1 303 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
             "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->post('/foo');
        $request->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, true);
        $request->send();

        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('POST', $requests[0]->getMethod());
        $this->assertEquals('GET', $requests[1]->getMethod());
    }

    public function testRewindsStreamWhenRedirectingIfNeeded()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->put();
        $request->configureRedirects(true);
        $body = EntityBody::factory('foo');
        $body->read(1);
        $request->setBody($body);
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('foo', (string) $requests[0]->getBody());
    }

    /**
     * @expectedException \Guzzle\Http\Exception\CouldNotRewindStreamException
     */
    public function testThrowsExceptionWhenStreamCannotBeRewound()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n"
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->put();
        $request->configureRedirects(true);
        $body = EntityBody::factory(fopen($this->getServer()->getUrl(), 'r'));
        $body->read(1);
        $request->setBody($body)->send();
    }

    public function testRedirectsCanBeDisabledPerRequest()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array("HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n"));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->put();
        $request->configureRedirects(false, 0);
        $this->assertEquals(301, $request->send()->getStatusCode());
    }

    public function testCanRedirectWithNoLeadingSlashAndQuery()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: redirect?foo=bar\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
        ));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('?foo=bar');
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals($this->getServer()->getUrl() . '?foo=bar', $requests[0]->getUrl());
        $this->assertEquals($this->getServer()->getUrl() . 'redirect?foo=bar', $requests[1]->getUrl());
        // Ensure that the history on the actual request is correct
        $this->assertEquals($this->getServer()->getUrl() . '?foo=bar', $request->getUrl());
    }

    public function testRedirectWithStrictRfc386Compliance()
    {
        // Flush the server and queue up a redirect followed by a successful response
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: redirect\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('/foo');
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('/redirect', $requests[1]->getResource());
    }

    public function testResetsHistoryEachSend()
    {
        // Flush the server and queue up a redirect followed by a successful response
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));

        // Create a client that uses the default redirect behavior
        $client = new Client($this->getServer()->getUrl());
        $history = new HistoryPlugin();
        $client->addSubscriber($history);

        $request = $client->get('/foo');
        $response = $request->send();
        $this->assertEquals(3, count($history));
        $this->assertTrue($request->getParams()->hasKey('redirect.count'));
        $this->assertContains('/redirect2', $response->getEffectiveUrl());

        $request->send();
        $this->assertFalse($request->getParams()->hasKey('redirect.count'));
    }

    public function testHandlesRedirectsWithSpacesProperly()
    {
        // Flush the server and queue up a redirect followed by a successful response
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect 1\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('/foo');
        $request->send();
        $reqs = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('/redirect%201', $reqs[1]->getResource());
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Http\Client;
use Guzzle\Http\Message\PostFile;

/**
 * @covers Guzzle\Http\Message\PostFile
 * @group server
 */
class PostFileTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testConstructorConfiguresPostFile()
    {
        $file = new PostFile('foo', __FILE__, 'x-foo', 'boo');
        $this->assertEquals('foo', $file->getFieldName());
        $this->assertEquals(__FILE__, $file->getFilename());
        $this->assertEquals('boo', $file->getPostName());
        $this->assertEquals('x-foo', $file->getContentType());
    }

    public function testRemovesLeadingAtSymbolFromPath()
    {
        $file = new PostFile('foo', '@' . __FILE__);
        $this->assertEquals(__FILE__, $file->getFilename());
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresFileIsReadable()
    {
        $file = new PostFile('foo', '/foo/baz/bar');
    }

    public function testCanChangeContentType()
    {
        $file = new PostFile('foo', '@' . __FILE__);
        $file->setContentType('Boo');
        $this->assertEquals('Boo', $file->getContentType());
    }

    public function testCanChangeFieldName()
    {
        $file = new PostFile('foo', '@' . __FILE__);
        $file->setFieldName('Boo');
        $this->assertEquals('Boo', $file->getFieldName());
    }

    public function testReturnsCurlValueString()
    {
        $file = new PostFile('foo', __FILE__);
        if (version_compare(phpversion(), '5.5.0', '<')) {
            $this->assertContains('@' . __FILE__ . ';filename=PostFileTest.php;type=text/x-', $file->getCurlValue());
        } else {
            $c = $file->getCurlValue();
            $this->assertEquals(__FILE__, $c->getFilename());
            $this->assertEquals('PostFileTest.php', $c->getPostFilename());
            $this->assertContains('text/x-', $c->getMimeType());
        }
    }

    public function testReturnsCurlValueStringAndPostname()
    {
        $file = new PostFile('foo', __FILE__, null, 'NewPostFileTest.php');
        if (version_compare(phpversion(), '5.5.0', '<')) {
            $this->assertContains('@' . __FILE__ . ';filename=NewPostFileTest.php;type=text/x-', $file->getCurlValue());
        } else {
            $c = $file->getCurlValue();
            $this->assertEquals(__FILE__, $c->getFilename());
            $this->assertEquals('NewPostFileTest.php', $c->getPostFilename());
            $this->assertContains('text/x-', $c->getMimeType());
        }
    }

    public function testContentDispositionFilePathIsStripped()
    {
        $this->getServer()->flush();
        $client = new Client($this->getServer()->getUrl());
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request = $client->post()->addPostFile('file', __FILE__);
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(false);
        $this->assertContains('POST / HTTP/1.1', $requests[0]);
        $this->assertContains('Content-Disposition: form-data; name="file"; filename="PostFileTest.php"', $requests[0]);
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Url;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\Request;
use Guzzle\Http\QueryString;
use Guzzle\Parser\Message\MessageParser;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Plugin\Mock\MockPlugin;

/**
 * @group server
 * @covers Guzzle\Http\Message\RequestFactory
 */
class HttpRequestFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCachesSingletonInstance()
    {
        $factory = RequestFactory::getInstance();
        $this->assertSame($factory, RequestFactory::getInstance());
    }

    public function testCreatesNewGetRequests()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://www.google.com/');
        $this->assertInstanceOf('Guzzle\\Http\\Message\\MessageInterface', $request);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\RequestInterface', $request);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Request', $request);
        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals('http', $request->getScheme());
        $this->assertEquals('http://www.google.com/', $request->getUrl());
        $this->assertEquals('www.google.com', $request->getHost());
        $this->assertEquals('/', $request->getPath());
        $this->assertEquals('/', $request->getResource());

        // Create a GET request with a custom receiving body
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $b = EntityBody::factory();
        $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl(), null, $b);
        $request->setClient(new Client());
        $response = $request->send();
        $this->assertSame($b, $response->getBody());
    }

    public function testCreatesPutRequests()
    {
        // Test using a string
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, 'Data');
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('http', $request->getScheme());
        $this->assertEquals('http://www.google.com/path?q=1&v=2', $request->getUrl());
        $this->assertEquals('www.google.com', $request->getHost());
        $this->assertEquals('/path', $request->getPath());
        $this->assertEquals('/path?q=1&v=2', $request->getResource());
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody());
        $this->assertEquals('Data', (string) $request->getBody());
        unset($request);

        // Test using an EntityBody
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, EntityBody::factory('Data'));
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('Data', (string) $request->getBody());

        // Test using a resource
        $resource = fopen('php://temp', 'w+');
        fwrite($resource, 'Data');
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, $resource);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('Data', (string) $request->getBody());

        // Test using an object that can be cast as a string
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, Url::factory('http://www.example.com/'));
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('http://www.example.com/', (string) $request->getBody());
    }

    public function testCreatesHeadAndDeleteRequests()
    {
        $request = RequestFactory::getInstance()->create('DELETE', 'http://www.test.com/');
        $this->assertEquals('DELETE', $request->getMethod());
        $request = RequestFactory::getInstance()->create('HEAD', 'http://www.test.com/');
        $this->assertEquals('HEAD', $request->getMethod());
    }

    public function testCreatesOptionsRequests()
    {
        $request = RequestFactory::getInstance()->create('OPTIONS', 'http://www.example.com/');
        $this->assertEquals('OPTIONS', $request->getMethod());
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
    }

    public function testCreatesNewPutRequestWithBody()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, 'Data');
        $this->assertEquals('Data', (string) $request->getBody());
    }

    public function testCreatesNewPostRequestWithFields()
    {
        // Use an array
        $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, array(
            'a' => 'b'
        ));
        $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll());
        unset($request);

        // Use a collection
        $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, new Collection(array(
            'a' => 'b'
        )));
        $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll());

        // Use a QueryString
        $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, new QueryString(array(
            'a' => 'b'
        )));
        $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll());

        $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/', null, array(
            'a' => 'b',
            'file' => '@' . __FILE__
        ));

        $this->assertEquals(array(
            'a' => 'b'
        ), $request->getPostFields()->getAll());

        $files = $request->getPostFiles();
        $this->assertInstanceOf('Guzzle\Http\Message\PostFile', $files['file'][0]);
    }

    public function testCreatesFromParts()
    {
        $parts = parse_url('http://michael:123@www.google.com:8080/path?q=1&v=2');

        $request = RequestFactory::getInstance()->fromParts('PUT', $parts, null, 'Data');
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('http', $request->getScheme());
        $this->assertEquals('http://www.google.com:8080/path?q=1&v=2', $request->getUrl());
        $this->assertEquals('www.google.com', $request->getHost());
        $this->assertEquals('www.google.com:8080', $request->getHeader('Host'));
        $this->assertEquals('/path', $request->getPath());
        $this->assertEquals('/path?q=1&v=2', $request->getResource());
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody());
        $this->assertEquals('Data', (string) $request->getBody());
        $this->assertEquals('michael', $request->getUsername());
        $this->assertEquals('123', $request->getPassword());
        $this->assertEquals('8080', $request->getPort());
        $this->assertEquals(array(
            'scheme' => 'http',
            'host' => 'www.google.com',
            'port' => 8080,
            'path' => '/path',
            'query' => 'q=1&v=2',
        ), parse_url($request->getUrl()));
    }

    public function testCreatesFromMessage()
    {
        $auth = base64_encode('michael:123');
        $message = "PUT /path?q=1&v=2 HTTP/1.1\r\nHost: www.google.com:8080\r\nContent-Length: 4\r\nAuthorization: Basic {$auth}\r\n\r\nData";
        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('http', $request->getScheme());
        $this->assertEquals('http://www.google.com:8080/path?q=1&v=2', $request->getUrl());
        $this->assertEquals('www.google.com', $request->getHost());
        $this->assertEquals('www.google.com:8080', $request->getHeader('Host'));
        $this->assertEquals('/path', $request->getPath());
        $this->assertEquals('/path?q=1&v=2', $request->getResource());
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody());
        $this->assertEquals('Data', (string) $request->getBody());
        $this->assertEquals("Basic {$auth}", (string) $request->getHeader('Authorization'));
        $this->assertEquals('8080', $request->getPort());

        // Test passing a blank message returns false
        $this->assertFalse($request = RequestFactory::getInstance()->fromMessage(''));

        // Test passing a url with no port
        $message = "PUT /path?q=1&v=2 HTTP/1.1\r\nHost: www.google.com\r\nContent-Length: 4\r\nAuthorization: Basic {$auth}\r\n\r\nData";
        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('http', $request->getScheme());
        $this->assertEquals('http://www.google.com/path?q=1&v=2', $request->getUrl());
        $this->assertEquals('www.google.com', $request->getHost());
        $this->assertEquals('/path', $request->getPath());
        $this->assertEquals('/path?q=1&v=2', $request->getResource());
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody());
        $this->assertEquals('Data', (string) $request->getBody());
        $this->assertEquals("Basic {$auth}", (string) $request->getHeader('Authorization'));
        $this->assertEquals(80, $request->getPort());
    }

    public function testCreatesNewTraceRequest()
    {
        $request = RequestFactory::getInstance()->create('TRACE', 'http://www.google.com/');
        $this->assertFalse($request instanceof \Guzzle\Http\Message\EntityEnclosingRequest);
        $this->assertEquals('TRACE', $request->getMethod());
    }

    public function testCreatesProperTransferEncodingRequests()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/', array(
            'Transfer-Encoding' => 'chunked'
        ), 'hello');
        $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding'));
        $this->assertFalse($request->hasHeader('Content-Length'));
    }

    public function testProperlyDealsWithDuplicateHeaders()
    {
        $parser = new MessageParser();

        $message = "POST / http/1.1\r\n"
            . "DATE:Mon, 09 Sep 2011 23:36:00 GMT\r\n"
            . "host:host.foo.com\r\n"
            . "ZOO:abc\r\n"
            . "ZOO:123\r\n"
            . "ZOO:HI\r\n"
            . "zoo:456\r\n\r\n";

        $parts = $parser->parseRequest($message);
        $this->assertEquals(array (
            'DATE' => 'Mon, 09 Sep 2011 23:36:00 GMT',
            'host' => 'host.foo.com',
            'ZOO'  => array('abc', '123', 'HI'),
            'zoo'  => '456',
        ), $parts['headers']);

        $request = RequestFactory::getInstance()->fromMessage($message);

        $this->assertEquals(array(
            'abc', '123', 'HI', '456'
        ), $request->getHeader('zoo')->toArray());
    }

    public function testCreatesHttpMessagesWithBodiesAndNormalizesLineEndings()
    {
        $message = "POST / http/1.1\r\n"
                 . "Content-Type:application/x-www-form-urlencoded; charset=utf8\r\n"
                 . "Date:Mon, 09 Sep 2011 23:36:00 GMT\r\n"
                 . "Host:host.foo.com\r\n\r\n"
                 . "foo=bar";

        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertEquals('application/x-www-form-urlencoded; charset=utf8', (string) $request->getHeader('Content-Type'));
        $this->assertEquals('foo=bar', (string) $request->getBody());

        $message = "POST / http/1.1\n"
                 . "Content-Type:application/x-www-form-urlencoded; charset=utf8\n"
                 . "Date:Mon, 09 Sep 2011 23:36:00 GMT\n"
                 . "Host:host.foo.com\n\n"
                 . "foo=bar";
        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertEquals('foo=bar', (string) $request->getBody());

        $message = "PUT / HTTP/1.1\r\nContent-Length: 0\r\n\r\n";
        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertTrue($request->hasHeader('Content-Length'));
        $this->assertEquals(0, (string) $request->getHeader('Content-Length'));
    }

    public function testBugPathIncorrectlyHandled()
    {
        $message = "POST /foo\r\n\r\nBODY";
        $request = RequestFactory::getInstance()->fromMessage($message);
        $this->assertSame('POST', $request->getMethod());
        $this->assertSame('/foo', $request->getPath());
        $this->assertSame('BODY', (string) $request->getBody());
    }

    public function testHandlesChunkedTransferEncoding()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.foo.com/', array(
            'Transfer-Encoding' => 'chunked'
        ), 'Test');
        $this->assertFalse($request->hasHeader('Content-Length'));
        $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding'));

        $request = RequestFactory::getInstance()->create('POST', 'http://www.foo.com/', array(
            'transfer-encoding' => 'chunked'
        ), array(
            'foo' => 'bar'
        ));

        $this->assertFalse($request->hasHeader('Content-Length'));
        $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding'));
    }

    public function testClonesRequestsWithMethodWithoutClient()
    {
        $f = RequestFactory::getInstance();
        $request = $f->create('GET', 'http://www.test.com', array('X-Foo' => 'Bar'));
        $request->getParams()->replace(array('test' => '123'));
        $request->getCurlOptions()->set('foo', 'bar');
        $cloned = $f->cloneRequestWithMethod($request, 'PUT');
        $this->assertEquals('PUT', $cloned->getMethod());
        $this->assertEquals('Bar', (string) $cloned->getHeader('X-Foo'));
        $this->assertEquals('http://www.test.com', $cloned->getUrl());
        // Ensure params are cloned and cleaned up
        $this->assertEquals(1, count($cloned->getParams()->getAll()));
        $this->assertEquals('123', $cloned->getParams()->get('test'));
        // Ensure curl options are cloned
        $this->assertEquals('bar', $cloned->getCurlOptions()->get('foo'));
        // Ensure event dispatcher is cloned
        $this->assertNotSame($request->getEventDispatcher(), $cloned->getEventDispatcher());
    }

    public function testClonesRequestsWithMethodWithClient()
    {
        $f = RequestFactory::getInstance();
        $client = new Client();
        $request = $client->put('http://www.test.com', array('Content-Length' => 4), 'test');
        $cloned = $f->cloneRequestWithMethod($request, 'GET');
        $this->assertEquals('GET', $cloned->getMethod());
        $this->assertNull($cloned->getHeader('Content-Length'));
        $this->assertEquals('http://www.test.com', $cloned->getUrl());
        $this->assertSame($request->getClient(), $cloned->getClient());
    }

    public function testClonesRequestsWithMethodWithClientWithEntityEnclosingChange()
    {
        $f = RequestFactory::getInstance();
        $client = new Client();
        $request = $client->put('http://www.test.com', array('Content-Length' => 4), 'test');
        $cloned = $f->cloneRequestWithMethod($request, 'POST');
        $this->assertEquals('POST', $cloned->getMethod());
        $this->assertEquals('test', (string) $cloned->getBody());
    }

    public function testCanDisableRedirects()
    {
        $this->getServer()->enqueue(array(
            "HTTP/1.1 307\r\nLocation: " . $this->getServer()->getUrl() . "\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $response = $client->get('/', array(), array('allow_redirects' => false))->send();
        $this->assertEquals(307, $response->getStatusCode());
    }

    public function testCanAddCookies()
    {
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('/', array(), array('cookies' => array('Foo' => 'Bar')));
        $this->assertEquals('Bar', $request->getCookie('Foo'));
    }

    public function testCanAddQueryString()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
            'query' => array('Foo' => 'Bar')
        ));
        $this->assertEquals('Bar', $request->getQuery()->get('Foo'));
    }

    public function testCanSetDefaultQueryString()
    {
        $request = new Request('GET', 'http://www.foo.com?test=abc');
        RequestFactory::getInstance()->applyOptions($request, array(
            'query' => array('test' => '123', 'other' => 't123')
        ), RequestFactory::OPTIONS_AS_DEFAULTS);
        $this->assertEquals('abc', $request->getQuery()->get('test'));
        $this->assertEquals('t123', $request->getQuery()->get('other'));
    }

    public function testCanAddBasicAuth()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
            'auth' => array('michael', 'test')
        ));
        $this->assertEquals('michael', $request->getUsername());
        $this->assertEquals('test', $request->getPassword());
    }

    public function testCanAddDigestAuth()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
            'auth' => array('michael', 'test', 'digest')
        ));
        $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH));
        $this->assertEquals('michael', $request->getUsername());
        $this->assertEquals('test', $request->getPassword());
    }

    public function testCanAddEvents()
    {
        $foo = null;
        $client = new Client();
        $client->addSubscriber(new MockPlugin(array(new Response(200))));
        $request = $client->get($this->getServer()->getUrl(), array(), array(
            'events' => array(
                'request.before_send' => function () use (&$foo) { $foo = true; }
            )
        ));
        $request->send();
        $this->assertTrue($foo);
    }

    public function testCanAddEventsWithPriority()
    {
        $foo = null;
        $client = new Client();
        $client->addSubscriber(new MockPlugin(array(new Response(200))));
        $request = $client->get($this->getServer()->getUrl(), array(), array(
            'events' => array(
                'request.before_send' => array(function () use (&$foo) { $foo = true; }, 100)
            )
        ));
        $request->send();
        $this->assertTrue($foo);
    }

    public function testCanAddPlugins()
    {
        $mock = new MockPlugin(array(
            new Response(200),
            new Response(200)
        ));
        $client = new Client();
        $client->addSubscriber($mock);
        $request = $client->get('/', array(), array(
            'plugins' => array($mock)
        ));
        $request->send();
    }

    public function testCanDisableExceptions()
    {
        $client = new Client();
        $request = $client->get('/', array(), array(
            'plugins' => array(new MockPlugin(array(new Response(500)))),
            'exceptions' => false
        ));
        $this->assertEquals(500, $request->send()->getStatusCode());
    }

    public function testCanDisableExceptionsWithErrorListener()
    {
        $client = new Client();
        $client->getEventDispatcher()->addListener('request.error', function () {});
        $request = $client->get('/', array(), array(
                'plugins' => array(new MockPlugin(array(new Response(500)))),
                'exceptions' => false
            ));
        $this->assertEquals(500, $request->send()->getStatusCode());
    }

    public function testCanChangeSaveToLocation()
    {
        $r = EntityBody::factory();
        $client = new Client();
        $request = $client->get('/', array(), array(
            'plugins' => array(new MockPlugin(array(new Response(200, array(), 'testing')))),
            'save_to' => $r
        ));
        $request->send();
        $this->assertEquals('testing', (string) $r);
    }

    public function testCanSetProxy()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('proxy' => '192.168.16.121'));
        $this->assertEquals('192.168.16.121', $request->getCurlOptions()->get(CURLOPT_PROXY));
    }

    public function testCanSetHeadersOption()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('headers' => array('Foo' => 'Bar')));
        $this->assertEquals('Bar', (string) $request->getHeader('Foo'));
    }

    public function testCanSetDefaultHeadersOptions()
    {
        $request = new Request('GET', 'http://www.foo.com', array('Foo' => 'Bar'));
        RequestFactory::getInstance()->applyOptions($request, array(
            'headers' => array('Foo' => 'Baz', 'Bam' => 't123')
        ), RequestFactory::OPTIONS_AS_DEFAULTS);
        $this->assertEquals('Bar', (string) $request->getHeader('Foo'));
        $this->assertEquals('t123', (string) $request->getHeader('Bam'));
    }

    public function testCanSetBodyOption()
    {
        $client = new Client();
        $request = $client->put('/', array(), null, array('body' => 'test'));
        $this->assertEquals('test', (string) $request->getBody());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesBodyOption()
    {
        $client = new Client();
        $client->get('/', array(), array('body' => 'test'));
    }

    public function testCanSetTimeoutOption()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('timeout' => 1.5));
        $this->assertEquals(1500, $request->getCurlOptions()->get(CURLOPT_TIMEOUT_MS));
    }

    public function testCanSetConnectTimeoutOption()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('connect_timeout' => 1.5));
        $this->assertEquals(1500, $request->getCurlOptions()->get(CURLOPT_CONNECTTIMEOUT_MS));
    }

    public function testCanSetDebug()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('debug' => true));
        $this->assertTrue($request->getCurlOptions()->get(CURLOPT_VERBOSE));
    }

    public function testCanSetVerifyToOff()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('verify' => false));
        $this->assertNull($request->getCurlOptions()->get(CURLOPT_CAINFO));
        $this->assertSame(0, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST));
        $this->assertFalse($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER));
    }

    public function testCanSetVerifyToOn()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('verify' => true));
        $this->assertNotNull($request->getCurlOptions()->get(CURLOPT_CAINFO));
        $this->assertSame(2, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST));
        $this->assertTrue($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER));
    }

    public function testCanSetVerifyToPath()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('verify' => '/foo.pem'));
        $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_CAINFO));
        $this->assertSame(2, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST));
        $this->assertTrue($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER));
    }

    public function inputValidation()
    {
        return array_map(function ($option) { return array($option); }, array(
            'headers', 'query', 'cookies', 'auth', 'events', 'plugins', 'params'
        ));
    }

    /**
     * @dataProvider inputValidation
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesInput($option)
    {
        $client = new Client();
        $client->get('/', array(), array($option => 'foo'));
    }

    public function testCanAddRequestParams()
    {
        $client = new Client();
        $request = $client->put('/', array(), null, array('params' => array('foo' => 'test')));
        $this->assertEquals('test', $request->getParams()->get('foo'));
    }

    public function testCanAddSslKey()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('ssl_key' => '/foo.pem'));
        $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLKEY));
    }

    public function testCanAddSslKeyPassword()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('ssl_key' => array('/foo.pem', 'bar')));
        $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLKEY));
        $this->assertEquals('bar', $request->getCurlOptions()->get(CURLOPT_SSLKEYPASSWD));
    }

    public function testCanAddSslCert()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('cert' => '/foo.pem'));
        $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLCERT));
    }

    public function testCanAddSslCertPassword()
    {
        $client = new Client();
        $request = $client->get('/', array(), array('cert' => array('/foo.pem', 'bar')));
        $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLCERT));
        $this->assertEquals('bar', $request->getCurlOptions()->get(CURLOPT_SSLCERTPASSWD));
    }

    public function testCreatesBodyWithoutZeroString()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://test.com', array(), '0');
        $this->assertSame('0', (string) $request->getBody());
    }
}
<?php

namespace Guzzle\Tests\Message;

use Guzzle\Common\Collection;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\EntityBody;
use Guzzle\Http\HttpException;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\Message\Response;

/**
 * @group server
 * @covers Guzzle\Http\Message\Response
 */
class ResponseTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Response The response object to test */
    protected $response;

    public function setup()
    {
        $this->response = new Response(200, new Collection(array(
            'Accept-Ranges' => 'bytes',
            'Age' => '12',
            'Allow' => 'GET, HEAD',
            'Cache-Control' => 'no-cache',
            'Content-Encoding' => 'gzip',
            'Content-Language' => 'da',
            'Content-Length' => '348',
            'Content-Location' => '/index.htm',
            'Content-Disposition' => 'attachment; filename=fname.ext',
            'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==',
            'Content-Range' => 'bytes 21010-47021/47022',
            'Content-Type' => 'text/html; charset=utf-8',
            'Date' => 'Tue, 15 Nov 1994 08:12:31 GMT',
            'ETag' => '737060cd8c284d8af7ad3082f209582d',
            'Expires' => 'Thu, 01 Dec 1994 16:00:00 GMT',
            'Last-Modified' => 'Tue, 15 Nov 1994 12:45:26 GMT',
            'Location' => 'http://www.w3.org/pub/WWW/People.html',
            'Pragma' => 'no-cache',
            'Proxy-Authenticate' => 'Basic',
            'Retry-After' => '120',
            'Server' => 'Apache/1.3.27 (Unix) (Red-Hat/Linux)',
            'Set-Cookie' => 'UserID=JohnDoe; Max-Age=3600; Version=1',
            'Trailer' => 'Max-Forwards',
            'Transfer-Encoding' => 'chunked',
            'Vary' => '*',
            'Via' => '1.0 fred, 1.1 nowhere.com (Apache/1.1)',
            'Warning' => '199 Miscellaneous warning',
            'WWW-Authenticate' => 'Basic'
        )), 'body');
    }

    public function tearDown()
    {
        unset($this->response);
    }

    public function testConstructor()
    {
        $params = new Collection();
        $body = EntityBody::factory('');
        $response = new Response(200, $params, $body);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals($body, $response->getBody());
        $this->assertEquals('OK', $response->getReasonPhrase());
        $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", $response->getRawHeaders());

        // Make sure Content-Length is set automatically
        $response = new Response(200, $params);
        $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", $response->getRawHeaders());

        // Pass bodies to the response
        $response = new Response(200, null, 'data');
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody());
        $response = new Response(200, null, EntityBody::factory('data'));
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody());
        $this->assertEquals('data', $response->getBody(true));
        $response = new Response(200, null, '0');
        $this->assertSame('0', $response->getBody(true), 'getBody(true) should return "0" if response body is "0".');

        // Make sure the proper exception is thrown
        try {
            //$response = new Response(200, null, array('foo' => 'bar'));
            //$this->fail('Response did not throw exception when passing invalid body');
        } catch (HttpException $e) {
        }

        // Ensure custom codes can be set
        $response = new Response(2);
        $this->assertEquals(2, $response->getStatusCode());
        $this->assertEquals('', $response->getReasonPhrase());

        // Make sure the proper exception is thrown when sending invalid headers
        try {
            $response = new Response(200, 'adidas');
            $this->fail('Response did not throw exception when passing invalid $headers');
        } catch (BadResponseException $e) {
        }
    }

    public function test__toString()
    {
        $response = new Response(200);
        $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", (string) $response);

        // Add another header
        $response = new Response(200, array(
            'X-Test' => 'Guzzle'
        ));
        $this->assertEquals("HTTP/1.1 200 OK\r\nX-Test: Guzzle\r\n\r\n", (string) $response);

        $response = new Response(200, array(
            'Content-Length' => 4
        ), 'test');
        $this->assertEquals("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest", (string) $response);
    }

    public function testFactory()
    {
        $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('OK', $response->getReasonPhrase());
        $this->assertEquals(4, (string) $response->getContentLength());
        $this->assertEquals('test', $response->getBody(true));

        // Make sure that automatic Content-Length works
        $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
        $this->assertEquals(4, (string) $response->getContentLength());
        $this->assertEquals('test', $response->getBody(true));
    }

    public function testFactoryCanCreateHeadResponses()
    {
        $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n");
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('OK', $response->getReasonPhrase());
        $this->assertEquals(4, (string) $response->getContentLength());
        $this->assertEquals('', $response->getBody(true));
    }

    public function testFactoryRequiresMessage()
    {
        $this->assertFalse(Response::fromMessage(''));
    }

    public function testGetBody()
    {
        $body = EntityBody::factory('');
        $response = new Response(403, new Collection(), $body);
        $this->assertEquals($body, $response->getBody());
        $response->setBody('foo');
        $this->assertEquals('foo', $response->getBody(true));
    }

    public function testManagesStatusCode()
    {
        $response = new Response(403);
        $this->assertEquals(403, $response->getStatusCode());
    }

    public function testGetMessage()
    {
        $response = new Response(200, new Collection(array(
            'Content-Length' => 4
        )), 'body');

        $this->assertEquals("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nbody", $response->getMessage());
    }

    public function testGetRawHeaders()
    {
        $response = new Response(200, new Collection(array(
            'Keep-Alive' => 155,
            'User-Agent' => 'Guzzle',
            'Content-Length' => 4
        )), 'body');

        $this->assertEquals("HTTP/1.1 200 OK\r\nKeep-Alive: 155\r\nUser-Agent: Guzzle\r\nContent-Length: 4\r\n\r\n", $response->getRawHeaders());
    }

    public function testHandlesStatusAndStatusCodes()
    {
        $response = new Response(200, new Collection(), 'body');
        $this->assertEquals('OK', $response->getReasonPhrase());

        $this->assertSame($response, $response->setStatus(204));
        $this->assertEquals('No Content', $response->getReasonPhrase());
        $this->assertEquals(204, $response->getStatusCode());

        $this->assertSame($response, $response->setStatus(204, 'Testing!'));
        $this->assertEquals('Testing!', $response->getReasonPhrase());
        $this->assertEquals(204, $response->getStatusCode());

        $response->setStatus(2000);
        $this->assertEquals(2000, $response->getStatusCode());
        $this->assertEquals('', $response->getReasonPhrase());

        $response->setStatus(200, 'Foo');
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('Foo', $response->getReasonPhrase());
    }

    public function testIsClientError()
    {
        $response = new Response(403);
        $this->assertTrue($response->isClientError());
        $response = new Response(200);
        $this->assertFalse($response->isClientError());
    }

    public function testIsError()
    {
        $response = new Response(403);
        $this->assertTrue($response->isError());
        $response = new Response(200);
        $this->assertFalse($response->isError());
        $response = new Response(500);
        $this->assertTrue($response->isError());
    }

    public function testIsInformational()
    {
        $response = new Response(100);
        $this->assertTrue($response->isInformational());
        $response = new Response(200);
        $this->assertFalse($response->isInformational());
    }

    public function testIsRedirect()
    {
        $response = new Response(301);
        $this->assertTrue($response->isRedirect());
        $response = new Response(200);
        $this->assertFalse($response->isRedirect());
    }

    public function testIsServerError()
    {
        $response = new Response(500);
        $this->assertTrue($response->isServerError());
        $response = new Response(400);
        $this->assertFalse($response->isServerError());
    }

    public function testIsSuccessful()
    {
        $response = new Response(200);
        $this->assertTrue($response->isSuccessful());
        $response = new Response(403);
        $this->assertFalse($response->isSuccessful());
    }

    public function testGetAcceptRanges()
    {
        $this->assertEquals('bytes', $this->response->getAcceptRanges());
    }

    public function testCalculatesAge()
    {
        $this->assertEquals(12, $this->response->calculateAge());

        $this->response->removeHeader('Age');
        $this->response->removeHeader('Date');
        $this->assertNull($this->response->calculateAge());

        $this->response->setHeader('Date', gmdate(ClientInterface::HTTP_DATE, strtotime('-1 minute')));
        // If the test runs slowly, still pass with a +5 second allowance
        $this->assertTrue($this->response->getAge() - 60 <= 5);
    }

    public function testGetAllow()
    {
        $this->assertEquals('GET, HEAD', $this->response->getAllow());
    }

    public function testGetCacheControl()
    {
        $this->assertEquals('no-cache', $this->response->getCacheControl());
    }

    public function testGetContentEncoding()
    {
        $this->assertEquals('gzip', $this->response->getContentEncoding());
    }

    public function testGetContentLanguage()
    {
        $this->assertEquals('da', $this->response->getContentLanguage());
    }

    public function testGetContentLength()
    {
        $this->assertEquals('348', $this->response->getContentLength());
    }

    public function testGetContentLocation()
    {
        $this->assertEquals('/index.htm', $this->response->getContentLocation());
    }

    public function testGetContentDisposition()
    {
        $this->assertEquals('attachment; filename=fname.ext', $this->response->getContentDisposition());
    }

    public function testGetContentMd5()
    {
        $this->assertEquals('Q2hlY2sgSW50ZWdyaXR5IQ==', $this->response->getContentMd5());
    }

    public function testGetContentRange()
    {
        $this->assertEquals('bytes 21010-47021/47022', $this->response->getContentRange());
    }

    public function testGetContentType()
    {
        $this->assertEquals('text/html; charset=utf-8', $this->response->getContentType());
    }

    public function testGetDate()
    {
        $this->assertEquals('Tue, 15 Nov 1994 08:12:31 GMT', $this->response->getDate());
    }

    public function testGetEtag()
    {
        $this->assertEquals('737060cd8c284d8af7ad3082f209582d', $this->response->getEtag());
    }

    public function testGetExpires()
    {
        $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $this->response->getExpires());
    }

    public function testGetLastModified()
    {
        $this->assertEquals('Tue, 15 Nov 1994 12:45:26 GMT', $this->response->getLastModified());
    }

    public function testGetLocation()
    {
        $this->assertEquals('http://www.w3.org/pub/WWW/People.html', $this->response->getLocation());
    }

    public function testGetPragma()
    {
        $this->assertEquals('no-cache', $this->response->getPragma());
    }

    public function testGetProxyAuthenticate()
    {
        $this->assertEquals('Basic', $this->response->getProxyAuthenticate());
    }

    public function testGetServer()
    {
        $this->assertEquals('Apache/1.3.27 (Unix) (Red-Hat/Linux)', $this->response->getServer());
    }

    public function testGetSetCookie()
    {
        $this->assertEquals('UserID=JohnDoe; Max-Age=3600; Version=1', $this->response->getSetCookie());
    }

    public function testGetMultipleSetCookie()
    {
        $this->response->addHeader('Set-Cookie', 'UserID=Mike; Max-Age=200');
        $this->assertEquals(array(
            'UserID=JohnDoe; Max-Age=3600; Version=1',
            'UserID=Mike; Max-Age=200',
        ), $this->response->getHeader('Set-Cookie')->toArray());
    }

    public function testGetSetCookieNormalizesHeaders()
    {
        $this->response->addHeaders(array(
            'Set-Cooke'  => 'boo',
            'set-cookie' => 'foo'
        ));

        $this->assertEquals(array(
            'UserID=JohnDoe; Max-Age=3600; Version=1',
            'foo'
        ), $this->response->getHeader('Set-Cookie')->toArray());

        $this->response->addHeaders(array(
            'set-cookie' => 'fubu'
        ));
        $this->assertEquals(
            array('UserID=JohnDoe; Max-Age=3600; Version=1', 'foo', 'fubu'),
            $this->response->getHeader('Set-Cookie')->toArray()
        );
    }

    public function testGetTrailer()
    {
        $this->assertEquals('Max-Forwards', $this->response->getTrailer());
    }

    public function testGetTransferEncoding()
    {
        $this->assertEquals('chunked', $this->response->getTransferEncoding());
    }

    public function testGetVary()
    {
        $this->assertEquals('*', $this->response->getVary());
    }

    public function testReturnsViaHeader()
    {
        $this->assertEquals('1.0 fred, 1.1 nowhere.com (Apache/1.1)', $this->response->getVia());
    }
    public function testGetWarning()
    {
        $this->assertEquals('199 Miscellaneous warning', $this->response->getWarning());
    }

    public function testReturnsWwwAuthenticateHeader()
    {
        $this->assertEquals('Basic', $this->response->getWwwAuthenticate());
    }

    public function testReturnsConnectionHeader()
    {
        $this->assertEquals(null, $this->response->getConnection());
        $this->response->setHeader('Connection', 'close');
        $this->assertEquals('close', $this->response->getConnection());
    }

    public function testReturnsHeaders()
    {
        $this->assertEquals('Basic', $this->response->getHeader('WWW-Authenticate', null, true));
        $this->assertEquals('chunked', $this->response->getHeader('Transfer-Encoding', null, false));
    }

    public function testHasTransferInfo()
    {
        $stats = array (
            'url' => 'http://www.google.com/',
            'content_type' => 'text/html; charset=ISO-8859-1',
            'http_code' => 200,
            'header_size' => 606,
            'request_size' => 53,
            'filetime' => -1,
            'ssl_verify_result' => 0,
            'redirect_count' => 0,
            'total_time' => 0.093284,
            'namelookup_time' => 0.001349,
            'connect_time' => 0.01635,
            'pretransfer_time' => 0.016358,
            'size_upload' => 0,
            'size_download' => 10330,
            'speed_download' => 110737,
            'speed_upload' => 0,
            'download_content_length' => -1,
            'upload_content_length' => 0,
            'starttransfer_time' => 0.07066,
            'redirect_time' => 0,
        );

        // Uninitialized state
        $this->assertNull($this->response->getInfo('url'));
        $this->assertEquals(array(), $this->response->getInfo());

        // Set the stats
        $this->response->setInfo($stats);
        $this->assertEquals($stats, $this->response->getInfo());
        $this->assertEquals(606, $this->response->getInfo('header_size'));
        $this->assertNull($this->response->getInfo('does_not_exist'));
    }

    /**
     * @return Response
     */
    private function getResponse($code, array $headers = null, EntityBody $body = null)
    {
        return new Response($code, $headers, $body);
    }

    public function testDeterminesIfItCanBeCached()
    {
        $this->assertTrue($this->getResponse(200)->canCache());
        $this->assertTrue($this->getResponse(410)->canCache());
        $this->assertFalse($this->getResponse(404)->canCache());
        $this->assertTrue($this->getResponse(200, array(
            'Cache-Control' => 'public'
        ))->canCache());

        // This has the no-store directive
        $this->assertFalse($this->getResponse(200, array(
            'Cache-Control' => 'private, no-store'
        ))->canCache());

        // The body cannot be read, so it cannot be cached
        $tmp = tempnam('/tmp', 'not-readable');
        $resource = fopen($tmp, 'w');
        $this->assertFalse($this->getResponse(200, array(
            'Transfer-Encoding' => 'chunked'
        ), EntityBody::factory($resource, 10))->canCache());
        unlink($tmp);

        // The body is 0 length, cannot be read, so it can be cached
        $tmp = tempnam('/tmp', 'not-readable');
        $resource = fopen($tmp, 'w');
        $this->assertTrue($this->getResponse(200, array(array(
            'Content-Length' => 0
        )), EntityBody::factory($resource, 0))->canCache());
        unlink($tmp);
    }

    public function testDeterminesResponseMaxAge()
    {
        $this->assertEquals(null, $this->getResponse(200)->getMaxAge());

        // Uses the response's s-maxage
        $this->assertEquals(140, $this->getResponse(200, array(
            'Cache-Control' => 's-maxage=140'
        ))->getMaxAge());

        // Uses the response's max-age
        $this->assertEquals(120, $this->getResponse(200, array(
            'Cache-Control' => 'max-age=120'
        ))->getMaxAge());

        // Uses the response's max-age
        $this->assertEquals(120, $this->getResponse(200, array(
            'Cache-Control' => 'max-age=120',
            'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day'))
        ))->getMaxAge());

        // Uses the Expires date
        $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array(
            'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day'))
        ))->getMaxAge());

        // Uses the Expires date
        $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array(
            'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day'))
        ))->getMaxAge());
    }

    public function testDeterminesIfItCanValidate()
    {
        $response = new Response(200);
        $this->assertFalse($response->canValidate());
        $response->setHeader('ETag', '123');
        $this->assertTrue($response->canValidate());
        $response->removeHeader('ETag');
        $this->assertFalse($response->canValidate());
        $response->setHeader('Last-Modified', '123');
        $this->assertTrue($response->canValidate());
    }

    public function testCalculatesFreshness()
    {
        $response = new Response(200);
        $this->assertNull($response->isFresh());
        $this->assertNull($response->getFreshness());

        $response->setHeader('Cache-Control', 'max-age=120');
        $response->setHeader('Age', 100);
        $this->assertEquals(20, $response->getFreshness());
        $this->assertTrue($response->isFresh());

        $response->setHeader('Age', 120);
        $this->assertEquals(0, $response->getFreshness());
        $this->assertTrue($response->isFresh());

        $response->setHeader('Age', 150);
        $this->assertEquals(-30, $response->getFreshness());
        $this->assertFalse($response->isFresh());
    }

    public function testHandlesProtocols()
    {
        $this->assertSame($this->response, $this->response->setProtocol('HTTP', '1.0'));
        $this->assertEquals('HTTP', $this->response->getProtocol());
        $this->assertEquals('1.0', $this->response->getProtocolVersion());
    }

    public function testComparesContentType()
    {
        $response = new Response(200, array(
            'Content-Type' => 'text/html; charset=ISO-8859-4'
        ));

        $this->assertTrue($response->isContentType('text/html'));
        $this->assertTrue($response->isContentType('TExT/html'));
        $this->assertTrue($response->isContentType('charset=ISO-8859-4'));
        $this->assertFalse($response->isContentType('application/xml'));
    }

    public function testResponseDeterminesIfMethodIsAllowedBaseOnAllowHeader()
    {
        $response = new Response(200, array(
            'Allow' => 'OPTIONS, POST, deletE,GET'
        ));

        $this->assertTrue($response->isMethodAllowed('get'));
        $this->assertTrue($response->isMethodAllowed('GET'));
        $this->assertTrue($response->isMethodAllowed('options'));
        $this->assertTrue($response->isMethodAllowed('post'));
        $this->assertTrue($response->isMethodAllowed('Delete'));
        $this->assertFalse($response->isMethodAllowed('put'));
        $this->assertFalse($response->isMethodAllowed('PUT'));

        $response = new Response(200);
        $this->assertFalse($response->isMethodAllowed('get'));
    }

    public function testParsesJsonResponses()
    {
        $response = new Response(200, array(), '{"foo": "bar"}');
        $this->assertEquals(array('foo' => 'bar'), $response->json());
        // Return array when null is a service response
        $response = new Response(200);
        $this->assertEquals(array(), $response->json());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage Unable to parse response body into JSON: 4
     */
    public function testThrowsExceptionWhenFailsToParseJsonResponse()
    {
        $response = new Response(200, array(), '{"foo": "');
        $response->json();
    }

    public function testParsesXmlResponses()
    {
        $response = new Response(200, array(), '<abc><foo>bar</foo></abc>');
        $this->assertEquals('bar', (string) $response->xml()->foo);
        // Always return a SimpleXMLElement from the xml method
        $response = new Response(200);
        $this->assertEmpty((string) $response->xml()->foo);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage Unable to parse response body into XML: String could not be parsed as XML
     */
    public function testThrowsExceptionWhenFailsToParseXmlResponse()
    {
        $response = new Response(200, array(), '<abc');
        $response->xml();
    }

    public function testResponseIsSerializable()
    {
        $response = new Response(200, array('Foo' => 'bar'), 'test');
        $r = unserialize(serialize($response));
        $this->assertEquals(200, $r->getStatusCode());
        $this->assertEquals('bar', (string) $r->getHeader('Foo'));
        $this->assertEquals('test', (string) $r->getBody());
    }

    public function testPreventsComplexExternalEntities()
    {
        $xml = '<?xml version="1.0"?><!DOCTYPE scan[<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=ResponseTest.php">]><scan>&test;</scan>';
        $response = new Response(200, array(), $xml);

        $oldCwd = getcwd();
        chdir(__DIR__);
        try {
            $xml = $response->xml();
            chdir($oldCwd);
            $this->markTestIncomplete('Did not throw the expected exception! XML resolved as: ' . $xml->asXML());
        } catch (\Exception $e) {
            chdir($oldCwd);
        }
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Http\Message\Header;
use Guzzle\Http\Message\Response;

/**
 * @covers Guzzle\Http\Message\Header
 */
class HeaderTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $test = array(
        'zoo'   => array('foo', 'Foo'),
        'Zoo'   => 'bar',
    );

    public function testStoresHeaderName()
    {
        $i = new Header('Zoo', $this->test);
        $this->assertEquals('Zoo', $i->getName());
    }

    public function testConvertsToString()
    {
        $i = new Header('Zoo', $this->test);
        $this->assertEquals('foo, Foo, bar', (string) $i);
        $i->setGlue(';');
        $this->assertEquals('foo; Foo; bar', (string) $i);
    }

    public function testNormalizesGluedHeaders()
    {
        $h = new Header('Zoo', array('foo, Faz', 'bar'));
        $result = $h->normalize(true)->toArray();
        natsort($result);
        $this->assertEquals(array('bar', 'foo', 'Faz'), $result);
    }

    public function testCanSearchForValues()
    {
        $h = new Header('Zoo', $this->test);
        $this->assertTrue($h->hasValue('foo'));
        $this->assertTrue($h->hasValue('Foo'));
        $this->assertTrue($h->hasValue('bar'));
        $this->assertFalse($h->hasValue('moo'));
        $this->assertFalse($h->hasValue('FoO'));
    }

    public function testIsCountable()
    {
        $h = new Header('Zoo', $this->test);
        $this->assertEquals(3, count($h));
    }

    public function testCanBeIterated()
    {
        $h = new Header('Zoo', $this->test);
        $results = array();
        foreach ($h as $key => $value) {
            $results[$key] = $value;
        }
        $this->assertEquals(array(
            'foo', 'Foo', 'bar'
        ), $results);
    }

    public function testAllowsFalseyValues()
    {
        // Allows 0
        $h = new Header('Foo', 0, ';');
        $this->assertEquals('0', (string) $h);
        $this->assertEquals(1, count($h));
        $this->assertEquals(';', $h->getGlue());

        // Does not add a null header by default
        $h = new Header('Foo');
        $this->assertEquals('', (string) $h);
        $this->assertEquals(0, count($h));

        // Allows null array for a single null header
        $h = new Header('Foo', array(null));
        $this->assertEquals('', (string) $h);

        // Allows empty string
        $h = new Header('Foo', '');
        $this->assertEquals('', (string) $h);
        $this->assertEquals(1, count($h));
        $this->assertEquals(1, count($h->normalize()->toArray()));
    }

    public function testCanRemoveValues()
    {
        $h = new Header('Foo', array('Foo', 'baz', 'bar'));
        $h->removeValue('bar');
        $this->assertTrue($h->hasValue('Foo'));
        $this->assertFalse($h->hasValue('bar'));
        $this->assertTrue($h->hasValue('baz'));
    }

    public function testAllowsArrayInConstructor()
    {
        $h = new Header('Foo', array('Testing', '123', 'Foo=baz'));
        $this->assertEquals(array('Testing', '123', 'Foo=baz'), $h->toArray());
    }

    public function parseParamsProvider()
    {
        $res1 = array(
            array(
                '<http:/.../front.jpeg>' => '',
                'rel' => 'front',
                'type' => 'image/jpeg',
            ),
            array(
                '<http://.../back.jpeg>' => '',
                'rel' => 'back',
                'type' => 'image/jpeg',
            ),
        );

        return array(
            array(
                '<http:/.../front.jpeg>; rel="front"; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg"',
                $res1
            ),
            array(
                '<http:/.../front.jpeg>; rel="front"; type="image/jpeg",<http://.../back.jpeg>; rel=back; type="image/jpeg"',
                $res1
            ),
            array(
                'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"',
                array(
                    array('foo' => 'baz', 'bar' => '123'),
                    array('boo' => ''),
                    array('test' => '123'),
                    array('foobar' => 'foo;bar')
                )
            ),
            array(
                '<http://.../side.jpeg?test=1>; rel="side"; type="image/jpeg",<http://.../side.jpeg?test=2>; rel=side; type="image/jpeg"',
                array(
                    array('<http://.../side.jpeg?test=1>' => '', 'rel' => 'side', 'type' => 'image/jpeg'),
                    array('<http://.../side.jpeg?test=2>' => '', 'rel' => 'side', 'type' => 'image/jpeg')
                )
            ),
            array(
                '',
                array()
            )
        );
    }

    /**
     * @dataProvider parseParamsProvider
     */
    public function testParseParams($header, $result)
    {
        $response = new Response(200, array('Link' => $header));
        $this->assertEquals($result, $response->getHeader('Link')->parseParams());
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Url;
use Guzzle\Http\Client;
use Guzzle\Plugin\Async\AsyncPlugin;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Exception\BadResponseException;

/**
 * @group server
 * @covers Guzzle\Http\Message\Request
 * @covers Guzzle\Http\Message\AbstractMessage
 */
class RequestTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Request */
    protected $request;

    /** @var Client */
    protected $client;

    protected function setUp()
    {
        $this->client = new Client($this->getServer()->getUrl());
        $this->request = $this->client->get();
    }

    public function tearDown()
    {
        unset($this->request);
        unset($this->client);
    }

    public function testConstructorBuildsRequestWithArrayHeaders()
    {
        // Test passing an array of headers
        $request = new Request('GET', 'http://www.guzzle-project.com/', array(
            'foo' => 'bar'
        ));

        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals('http://www.guzzle-project.com/', $request->getUrl());
        $this->assertEquals('bar', $request->getHeader('foo'));
    }

    public function testDescribesEvents()
    {
        $this->assertInternalType('array', Request::getAllEvents());
    }

    public function testConstructorBuildsRequestWithCollectionHeaders()
    {
        $request = new Request('GET', 'http://www.guzzle-project.com/', new Collection(array(
            'foo' => 'bar'
        )));
        $this->assertEquals('bar', $request->getHeader('foo'));
    }

    public function testConstructorBuildsRequestWithNoHeaders()
    {
        $request = new Request('GET', 'http://www.guzzle-project.com/', null);
        $this->assertFalse($request->hasHeader('foo'));
    }

    public function testConstructorHandlesNonBasicAuth()
    {
        $request = new Request('GET', 'http://www.guzzle-project.com/', array(
            'Authorization' => 'Foo bar'
        ));
        $this->assertNull($request->getUserName());
        $this->assertNull($request->getPassword());
        $this->assertEquals('Foo bar', (string) $request->getHeader('Authorization'));
    }

    public function testRequestsCanBeConvertedToRawMessageStrings()
    {
        $auth = base64_encode('michael:123');
        $message = "PUT /path?q=1&v=2 HTTP/1.1\r\n"
            . "Host: www.google.com\r\n"
            . "Authorization: Basic {$auth}\r\n"
            . "Content-Length: 4\r\n\r\nData";

        $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', array(
            'Authorization' => 'Basic ' . $auth
        ), 'Data');

        $this->assertEquals($message, $request->__toString());
    }

    /**
     * Add authorization after the fact and see that it was put in the message
     */
    public function testRequestStringsIncludeAuth()
    {
        $auth = base64_encode('michael:123');
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl(), null, 'Data')
            ->setClient($this->client)
            ->setAuth('michael', '123', CURLAUTH_BASIC);
        $request->send();

        $this->assertContains('Authorization: Basic ' . $auth, (string) $request);
    }

    public function testGetEventDispatcher()
    {
        $d = $this->request->getEventDispatcher();
        $this->assertInstanceOf('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface', $d);
        $this->assertEquals($d, $this->request->getEventDispatcher());
    }

    public function testRequestsManageClients()
    {
        $request = new Request('GET', 'http://test.com');
        $this->assertNull($request->getClient());
        $request->setClient($this->client);
        $this->assertSame($this->client, $request->getClient());
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage A client must be set on the request
     */
    public function testRequestsRequireClients()
    {
        $request = new Request('GET', 'http://test.com');
        $request->send();
    }

    public function testSend()
    {
        $response = new Response(200, array(
            'Content-Length' => 3
        ), 'abc');
        $this->request->setResponse($response, true);
        $r = $this->request->send();

        $this->assertSame($response, $r);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $this->request->getResponse());
        $this->assertSame($r, $this->request->getResponse());
        $this->assertEquals('complete', $this->request->getState());
    }

    public function testGetResponse()
    {
        $this->assertNull($this->request->getResponse());
        $response = new Response(200, array('Content-Length' => 3), 'abc');

        $this->request->setResponse($response);
        $this->assertEquals($response, $this->request->getResponse());

        $client = new Client('http://www.google.com');
        $request = $client->get('http://www.google.com/');
        $request->setResponse($response, true);
        $request->send();
        $requestResponse = $request->getResponse();
        $this->assertSame($response, $requestResponse);

        // Try again, making sure it's still the same response
        $this->assertSame($requestResponse, $request->getResponse());

        $response = new Response(204);
        $request = $client->get();
        $request->setResponse($response, true);
        $request->send();
        $requestResponse = $request->getResponse();
        $this->assertSame($response, $requestResponse);
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody());
    }

    public function testRequestThrowsExceptionOnBadResponse()
    {
        try {
            $this->request->setResponse(new Response(404, array('Content-Length' => 3), 'abc'), true);
            $this->request->send();
            $this->fail('Expected exception not thrown');
        } catch (BadResponseException $e) {
            $this->assertInstanceOf('Guzzle\\Http\\Message\\RequestInterface', $e->getRequest());
            $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $e->getResponse());
            $this->assertContains('Client error response', $e->getMessage());
        }
    }

    public function testManagesQuery()
    {
        $this->assertInstanceOf('Guzzle\\Http\\QueryString', $this->request->getQuery());
        $this->request->getQuery()->set('test', '123');
        $this->assertEquals('test=123', $this->request->getQuery(true));
    }

    public function testRequestHasMethod()
    {
        $this->assertEquals('GET', $this->request->getMethod());
    }

    public function testRequestHasScheme()
    {
        $this->assertEquals('http', $this->request->getScheme());
        $this->assertEquals($this->request, $this->request->setScheme('https'));
        $this->assertEquals('https', $this->request->getScheme());
    }

    public function testRequestHasHost()
    {
        $this->assertEquals('127.0.0.1', $this->request->getHost());
        $this->assertEquals('127.0.0.1:8124', (string) $this->request->getHeader('Host'));

        $this->assertSame($this->request, $this->request->setHost('www2.google.com'));
        $this->assertEquals('www2.google.com', $this->request->getHost());
        $this->assertEquals('www2.google.com:8124', (string) $this->request->getHeader('Host'));

        $this->assertSame($this->request, $this->request->setHost('www.test.com:8081'));
        $this->assertEquals('www.test.com', $this->request->getHost());
        $this->assertEquals(8081, $this->request->getPort());
    }

    public function testRequestHasProtocol()
    {
        $this->assertEquals('1.1', $this->request->getProtocolVersion());
        $this->assertEquals($this->request, $this->request->setProtocolVersion('1.1'));
        $this->assertEquals('1.1', $this->request->getProtocolVersion());
        $this->assertEquals($this->request, $this->request->setProtocolVersion('1.0'));
        $this->assertEquals('1.0', $this->request->getProtocolVersion());
    }

    public function testRequestHasPath()
    {
        $this->assertEquals('/', $this->request->getPath());
        $this->assertEquals($this->request, $this->request->setPath('/index.html'));
        $this->assertEquals('/index.html', $this->request->getPath());
        $this->assertEquals($this->request, $this->request->setPath('index.html'));
        $this->assertEquals('/index.html', $this->request->getPath());
    }

    public function testPermitsFalsyComponents()
    {
        $request = new Request('GET', 'http://0/0?0');
        $this->assertSame('0', $request->getHost());
        $this->assertSame('/0', $request->getPath());
        $this->assertSame('0', $request->getQuery(true));

        $request = new Request('GET', '0');
        $this->assertEquals('/0', $request->getPath());
    }

    public function testRequestHasPort()
    {
        $this->assertEquals(8124, $this->request->getPort());
        $this->assertEquals('127.0.0.1:8124', $this->request->getHeader('Host'));

        $this->assertEquals($this->request, $this->request->setPort('8080'));
        $this->assertEquals('8080', $this->request->getPort());
        $this->assertEquals('127.0.0.1:8080', $this->request->getHeader('Host'));

        $this->request->setPort(80);
        $this->assertEquals('127.0.0.1', $this->request->getHeader('Host'));
    }

    public function testRequestHandlesAuthorization()
    {
        // Uninitialized auth
        $this->assertEquals(null, $this->request->getUsername());
        $this->assertEquals(null, $this->request->getPassword());

        // Set an auth
        $this->assertSame($this->request, $this->request->setAuth('michael', '123'));
        $this->assertEquals('michael', $this->request->getUsername());
        $this->assertEquals('123', $this->request->getPassword());

        // Set an auth with blank password
        $this->assertSame($this->request, $this->request->setAuth('michael', ''));
        $this->assertEquals('michael', $this->request->getUsername());
        $this->assertEquals('', $this->request->getPassword());

        // Remove the auth
        $this->request->setAuth(false);
        $this->assertEquals(null, $this->request->getUsername());
        $this->assertEquals(null, $this->request->getPassword());

        // Make sure that the cURL based auth works too
        $request = new Request('GET', $this->getServer()->getUrl());
        $request->setAuth('michael', 'password', CURLAUTH_DIGEST);
        $this->assertEquals('michael:password', $request->getCurlOptions()->get(CURLOPT_USERPWD));
        $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH));
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesAuth()
    {
        $this->request->setAuth('foo', 'bar', 'bam');
    }

    public function testGetResourceUri()
    {
        $this->assertEquals('/', $this->request->getResource());
        $this->request->setPath('/index.html');
        $this->assertEquals('/index.html', $this->request->getResource());
        $this->request->getQuery()->add('v', '1');
        $this->assertEquals('/index.html?v=1', $this->request->getResource());
    }

    public function testRequestHasMutableUrl()
    {
        $url = 'http://www.test.com:8081/path?q=123#fragment';
        $u = Url::factory($url);
        $this->assertSame($this->request, $this->request->setUrl($url));
        $this->assertEquals($url, $this->request->getUrl());

        $this->assertSame($this->request, $this->request->setUrl($u));
        $this->assertEquals($url, $this->request->getUrl());
    }

    public function testRequestHasState()
    {
        $this->assertEquals(RequestInterface::STATE_NEW, $this->request->getState());
        $this->request->setState(RequestInterface::STATE_TRANSFER);
        $this->assertEquals(RequestInterface::STATE_TRANSFER, $this->request->getState());
    }

    public function testSetManualResponse()
    {
        $response = new Response(200, array(
            'Date' => 'Sat, 16 Oct 2010 17:27:14 GMT',
            'Expires' => '-1',
            'Cache-Control' => 'private, max-age=0',
            'Content-Type' => 'text/html; charset=ISO-8859-1',
        ), 'response body');

        $this->assertSame($this->request, $this->request->setResponse($response), '-> setResponse() must use a fluent interface');
        $this->assertEquals('complete', $this->request->getState(), '-> setResponse() must change the state of the request to complete');
        $this->assertSame($response, $this->request->getResponse(), '-> setResponse() must set the exact same response that was passed in to it');
    }

    public function testRequestCanHaveManuallySetResponseBody()
    {
        $file = __DIR__ . '/../../TestData/temp.out';
        if (file_exists($file)) {
            unlink($file);
        }

        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata");
        $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl());
        $request->setClient($this->client);
        $entityBody = EntityBody::factory(fopen($file, 'w+'));
        $request->setResponseBody($entityBody);
        $response = $request->send();
        $this->assertSame($entityBody, $response->getBody());

        $this->assertTrue(file_exists($file));
        $this->assertEquals('data', file_get_contents($file));
        unlink($file);

        $this->assertEquals('data', $response->getBody(true));
    }

    public function testHoldsCookies()
    {
        $this->assertNull($this->request->getCookie('test'));

        // Set a cookie
        $this->assertSame($this->request, $this->request->addCookie('test', 'abc'));
        $this->assertEquals('abc', $this->request->getCookie('test'));

        // Multiple cookies by setting the Cookie header
        $this->request->setHeader('Cookie', '__utma=1.638370270.1344367610.1374365610.1944450276.2; __utmz=1.1346368610.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); hl=de; PHPSESSID=ak93pqashi5uubuoq8fjv60897');
        $this->assertEquals('1.638370270.1344367610.1374365610.1944450276.2', $this->request->getCookie('__utma'));
        $this->assertEquals('1.1346368610.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', $this->request->getCookie('__utmz'));
        $this->assertEquals('de', $this->request->getCookie('hl'));
        $this->assertEquals('ak93pqashi5uubuoq8fjv60897', $this->request->getCookie('PHPSESSID'));

        // Unset the cookies by setting the Cookie header to null
        $this->request->setHeader('Cookie', null);
        $this->assertNull($this->request->getCookie('test'));
        $this->request->removeHeader('Cookie');

        // Set and remove a cookie
        $this->assertSame($this->request, $this->request->addCookie('test', 'abc'));
        $this->assertEquals('abc', $this->request->getCookie('test'));
        $this->assertSame($this->request, $this->request->removeCookie('test'));
        $this->assertNull($this->request->getCookie('test'));

        // Remove the cookie header
        $this->assertSame($this->request, $this->request->addCookie('test', 'abc'));
        $this->request->removeHeader('Cookie');
        $this->assertEquals('', (string) $this->request->getHeader('Cookie'));

        // Remove a cookie value
        $this->request->addCookie('foo', 'bar')->addCookie('baz', 'boo');
        $this->request->removeCookie('foo');
        $this->assertEquals(array(
            'baz' => 'boo'
        ), $this->request->getCookies());

        $this->request->addCookie('foo', 'bar');
        $this->assertEquals('baz=boo; foo=bar', (string) $this->request->getHeader('Cookie'));
    }

    /**
     * @expectedException \Guzzle\Http\Exception\RequestException
     * @expectedExceptionMessage Error completing request
     */
    public function testRequestThrowsExceptionWhenSetToCompleteWithNoResponse()
    {
        $this->request->setState(RequestInterface::STATE_COMPLETE);
    }

    public function testClonedRequestsUseNewInternalState()
    {
        $p = new AsyncPlugin();
        $this->request->getEventDispatcher()->addSubscriber($p);
        $h = $this->request->getHeader('Host');

        $r = clone $this->request;
        $this->assertEquals(RequestInterface::STATE_NEW, $r->getState());
        $this->assertNotSame($r->getQuery(), $this->request->getQuery());
        $this->assertNotSame($r->getCurlOptions(), $this->request->getCurlOptions());
        $this->assertNotSame($r->getEventDispatcher(), $this->request->getEventDispatcher());
        $this->assertEquals($r->getHeaders(), $this->request->getHeaders());
        $this->assertNotSame($h, $r->getHeader('Host'));
        $this->assertNotSame($r->getParams(), $this->request->getParams());
        $this->assertTrue($this->request->getEventDispatcher()->hasListeners('request.sent'));
    }

    public function testRecognizesBasicAuthCredentialsInUrls()
    {
        $this->request->setUrl('http://michael:test@test.com/');
        $this->assertEquals('michael', $this->request->getUsername());
        $this->assertEquals('test', $this->request->getPassword());
    }

    public function testRequestCanBeSentUsingCurl()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata",
            "HTTP/1.1 404 Not Found\r\nContent-Encoding: application/xml\r\nContent-Length: 48\r\n\r\n<error><mesage>File not found</message></error>"
        ));

        $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl());
        $request->setClient($this->client);
        $response = $request->send();

        $this->assertEquals('data', $response->getBody(true));
        $this->assertEquals(200, (int) $response->getStatusCode());
        $this->assertEquals('OK', $response->getReasonPhrase());
        $this->assertEquals(4, $response->getContentLength());
        $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $response->getExpires());

        // Test that the same handle can be sent twice without setting state to new
        $response2 = $request->send();
        $this->assertNotSame($response, $response2);

        try {
            $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl() . 'index.html');
            $request->setClient($this->client);
            $response = $request->send();
            $this->fail('Request did not receive a 404 response');
        } catch (BadResponseException $e) {
        }

        $requests = $this->getServer()->getReceivedRequests(true);
        $messages = $this->getServer()->getReceivedRequests(false);
        $port = $this->getServer()->getPort();

        $userAgent = $this->client->getDefaultUserAgent();

        $this->assertEquals('127.0.0.1:' . $port, $requests[0]->getHeader('Host'));
        $this->assertEquals('127.0.0.1:' . $port, $requests[1]->getHeader('Host'));
        $this->assertEquals('127.0.0.1:' . $port, $requests[2]->getHeader('Host'));

        $this->assertEquals('/', $requests[0]->getPath());
        $this->assertEquals('/', $requests[1]->getPath());
        $this->assertEquals('/index.html', $requests[2]->getPath());

        $parts = explode("\r\n", $messages[0]);
        $this->assertEquals('GET / HTTP/1.1', $parts[0]);

        $parts = explode("\r\n", $messages[1]);
        $this->assertEquals('GET / HTTP/1.1', $parts[0]);

        $parts = explode("\r\n", $messages[2]);
        $this->assertEquals('GET /index.html HTTP/1.1', $parts[0]);
    }

    public function testThrowsExceptionsWhenUnsuccessfulResponseIsReceivedByDefault()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 404 Not found\r\nContent-Length: 0\r\n\r\n");

        try {
            $request = $this->client->get('/index.html');
            $response = $request->send();
            $this->fail('Request did not receive a 404 response');
        } catch (BadResponseException $e) {
            $this->assertContains('Client error response', $e->getMessage());
            $this->assertContains('[status code] 404', $e->getMessage());
            $this->assertContains('[reason phrase] Not found', $e->getMessage());
        }
    }

    public function testCanShortCircuitErrorHandling()
    {
        $request = $this->request;
        $response = new Response(404);
        $request->setResponse($response, true);
        $out = '';
        $that = $this;
        $request->getEventDispatcher()->addListener('request.error', function($event) use (&$out, $that) {
            $out .= $event['request'] . "\n" . $event['response'] . "\n";
            $event->stopPropagation();
        });
        $request->send();
        $this->assertContains((string) $request, $out);
        $this->assertContains((string) $request->getResponse(), $out);
        $this->assertSame($response, $request->getResponse());
    }

    public function testCanOverrideUnsuccessfulResponses()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 404 NOT FOUND\r\n" .
            "Content-Length: 0\r\n" .
            "\r\n",
            "HTTP/1.1 200 OK\r\n" .
            "Content-Length: 0\r\n" .
            "\r\n"
        ));

        $newResponse = null;

        $request = $this->request;
        $request->getEventDispatcher()->addListener('request.error', function($event) use (&$newResponse) {
            if ($event['response']->getStatusCode() == 404) {
                $newRequest = clone $event['request'];
                $newResponse = $newRequest->send();
                // Override the original response and bypass additional response processing
                $event['response'] = $newResponse;
                // Call $event['request']->setResponse($newResponse); to re-apply events
                $event->stopPropagation();
            }
        });

        $request->send();

        $this->assertEquals(200, $request->getResponse()->getStatusCode());
        $this->assertSame($newResponse, $request->getResponse());
        $this->assertEquals(2, count($this->getServer()->getReceivedRequests()));
    }

    public function testCanRetrieveUrlObject()
    {
        $request = new Request('GET', 'http://www.example.com/foo?abc=d');
        $this->assertInstanceOf('Guzzle\Http\Url', $request->getUrl(true));
        $this->assertEquals('http://www.example.com/foo?abc=d', $request->getUrl());
        $this->assertEquals('http://www.example.com/foo?abc=d', (string) $request->getUrl(true));
    }

    public function testUnresolvedRedirectsReturnResponse()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 303 SEE OTHER\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n"
        ));
        $request = $this->request;
        $this->assertEquals(303, $request->send()->getStatusCode());
        $request->getParams()->set(RedirectPlugin::DISABLE, true);
        $this->assertEquals(301, $request->send()->getStatusCode());
    }

    public function testCanSendCustomRequests()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request = $this->client->createRequest('PROPFIND', $this->getServer()->getUrl(), array(
            'Content-Type' => 'text/plain'
        ), 'foo');
        $response = $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('PROPFIND', $requests[0]->getMethod());
        $this->assertEquals(3, (string) $requests[0]->getHeader('Content-Length'));
        $this->assertEquals('foo', (string) $requests[0]->getBody());
    }

    /**
     * @expectedException \PHPUnit_Framework_Error_Warning
     */
    public function testEnsuresFileCanBeCreated()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
        $this->client->get('/')->setResponseBody('/wefwefefefefwewefwe/wefwefwefefwe/wefwefewfw.txt')->send();
    }

    public function testAllowsFilenameForDownloadingContent()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest");
        $name = sys_get_temp_dir() . '/foo.txt';
        $this->client->get('/')->setResponseBody($name)->send();
        $this->assertEquals('test', file_get_contents($name));
        unlink($name);
    }

    public function testUsesCustomResponseBodyWhenItIsCustom()
    {
        $en = EntityBody::factory();
        $request = $this->client->get();
        $request->setResponseBody($en);
        $request->setResponse(new Response(200, array(), 'foo'));
        $this->assertEquals('foo', (string) $en);
    }

    public function testCanChangePortThroughScheme()
    {
        $request = new Request('GET', 'http://foo.com');
        $request->setScheme('https');
        $this->assertEquals('https://foo.com', (string) $request->getUrl());
        $this->assertEquals('foo.com', $request->getHost());
        $request->setScheme('http');
        $this->assertEquals('http://foo.com', (string) $request->getUrl());
        $this->assertEquals('foo.com', $request->getHost());
        $request->setPort(null);
        $this->assertEquals('http://foo.com', (string) $request->getUrl());
        $this->assertEquals('foo.com', $request->getHost());
    }
}
<?php

namespace Guzzle\Tests\Message;

use Guzzle\Common\Collection;
use Guzzle\Tests\Http\Message\HeaderComparison;

class HeaderComparisonTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function filterProvider()
    {
        return array(

            // Headers match
            array(array(
                'Content-Length' => 'Foo'
            ), array(
                'Content-Length' => 'Foo'
            ), false),

            // Missing header
            array(array(
                'X-Foo' => 'Bar'
            ), array(), array(
                '- X-Foo' => 'Bar'
            )),

            // Extra headers is present
            array(array(
                'X-Foo' => 'Bar'
            ), array(
                'X-Foo' => 'Bar',
                'X-Baz' => 'Jar'
            ), array(
                '+ X-Baz' => 'Jar'
            )),

            // Header is present but must be absent
            array(array(
                '!X-Foo' => '*'
            ), array(
                'X-Foo' => 'Bar'
            ), array(
                '++ X-Foo' => 'Bar'
            )),

            // Different values
            array(array(
                'X-Foo' => 'Bar'
            ), array(
                'X-Foo' => 'Baz'
            ), array(
                'X-Foo' => 'Baz != Bar'
            )),

            // Wildcard search passes
            array(array(
                'X-Foo' => '*'
            ), array(
                'X-Foo' => 'Bar'
            ), false),

            // Wildcard search fails
            array(array(
                'X-Foo' => '*'
            ), array(), array(
                '- X-Foo' => '*'
            )),

            // Ignore extra header if present
            array(array(
                'X-Foo' => '*',
                '_X-Bar' => '*',
            ), array(
                'X-Foo' => 'Baz',
                'X-Bar' => 'Jar'
            ), false),

            // Ignore extra header if present and is not
            array(array(
                'X-Foo' => '*',
                '_X-Bar' => '*',
            ), array(
                'X-Foo' => 'Baz'
            ), false),

            // Case insensitive
            array(array(
                'X-Foo' => '*',
                '_X-Bar' => '*',
            ), array(
                'x-foo' => 'Baz',
                'x-BAR' => 'baz'
            ), false),

            // Case insensitive with collection
            array(array(
                'X-Foo' => '*',
                '_X-Bar' => '*',
            ), new Collection(array(
                'x-foo' => 'Baz',
                'x-BAR' => 'baz'
            )), false),
        );
    }

    /**
     * @dataProvider filterProvider
     */
    public function testComparesHeaders($filters, $headers, $result)
    {
        $compare = new HeaderComparison();
        $this->assertEquals($result, $compare->compare($filters, $headers));
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Http\Client;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\PostFile;
use Guzzle\Http\QueryString;

/**
 * @group server
 * @covers Guzzle\Http\Message\EntityEnclosingRequest
 */
class EntityEnclosingRequestTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $client;

    public function setUp()
    {
        $this->client = new Client();
    }

    public function tearDown()
    {
        $this->client = null;
    }

    public function testConstructorConfiguresRequest()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com', array(
            'X-Test' => '123'
        ));
        $request->setBody('Test');
        $this->assertEquals('123', $request->getHeader('X-Test'));
        $this->assertNull($request->getHeader('Expect'));
    }

    public function testCanSetBodyWithoutOverridingContentType()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com', array('Content-Type' => 'foooooo'));
        $request->setBody('{"a":"b"}');
        $this->assertEquals('foooooo', $request->getHeader('Content-Type'));
    }

    public function testRequestIncludesBodyInMessage()
    {

        $request = RequestFactory::getInstance()->create('PUT', 'http://www.guzzle-project.com/', null, 'data');
        $this->assertEquals("PUT / HTTP/1.1\r\n"
            . "Host: www.guzzle-project.com\r\n"
            . "Content-Length: 4\r\n\r\n"
            . "data", (string) $request);
    }

    public function testRequestIncludesPostBodyInMessageOnlyWhenNoPostFiles()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array(
            'foo' => 'bar'
        ));
        $this->assertEquals("POST / HTTP/1.1\r\n"
            . "Host: www.guzzle-project.com\r\n"
            . "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n\r\n"
            . "foo=bar", (string) $request);

        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array(
            'foo' => '@' . __FILE__
        ));
        $this->assertEquals("POST / HTTP/1.1\r\n"
            . "Host: www.guzzle-project.com\r\n"
            . "Content-Type: multipart/form-data\r\n"
            . "Expect: 100-Continue\r\n\r\n", (string) $request);
    }

    public function testAddsPostFieldsAndSetsContentLength()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array(
            'data' => '123'
        ));
        $this->assertEquals("POST / HTTP/1.1\r\n"
            . "Host: www.guzzle-project.com\r\n"
            . "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n\r\n"
            . "data=123", (string) $request);
    }

    public function testAddsPostFilesAndSetsContentType()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/')
            ->addPostFiles(array(
                'file' => __FILE__
            ))->addPostFields(array(
                'a' => 'b'
            ));
        $message = (string) $request;
        $this->assertEquals('multipart/form-data', $request->getHeader('Content-Type'));
        $this->assertEquals('100-Continue', $request->getHeader('Expect'));
    }

    public function testRequestBodyContainsPostFiles()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/');
        $request->addPostFields(array(
            'test' => '123'
        ));
        $this->assertContains("\r\n\r\ntest=123", (string) $request);
    }

    public function testRequestBodyAddsContentLength()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.test.com/');
        $request->setBody(EntityBody::factory('test'));
        $this->assertEquals(4, (string) $request->getHeader('Content-Length'));
        $this->assertFalse($request->hasHeader('Transfer-Encoding'));
    }

    public function testRequestBodyDoesNotUseContentLengthWhenChunked()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.test.com/', array(
            'Transfer-Encoding' => 'chunked'
        ), 'test');
        $this->assertNull($request->getHeader('Content-Length'));
        $this->assertTrue($request->hasHeader('Transfer-Encoding'));
    }

    public function testRequestHasMutableBody()
    {
        $request = RequestFactory::getInstance()->create('PUT', 'http://www.guzzle-project.com/', null, 'data');
        $body = $request->getBody();
        $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $body);
        $this->assertSame($body, $request->getBody());

        $newBody = EntityBody::factory('foobar');
        $request->setBody($newBody);
        $this->assertEquals('foobar', (string) $request->getBody());
        $this->assertSame($newBody, $request->getBody());
    }

    public function testSetPostFields()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/');
        $this->assertInstanceOf('Guzzle\\Http\\QueryString', $request->getPostFields());

        $fields = new QueryString(array(
            'a' => 'b'
        ));
        $request->addPostFields($fields);
        $this->assertEquals($fields->getAll(), $request->getPostFields()->getAll());
        $this->assertEquals(array(), $request->getPostFiles());
    }

    public function testSetPostFiles()
    {
        $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl())
            ->setClient(new Client())
            ->addPostFiles(array(__FILE__))
            ->addPostFields(array(
                'test' => 'abc'
            ));

        $request->getCurlOptions()->set('debug', true);

        $this->assertEquals(array(
            'test' => 'abc'
        ), $request->getPostFields()->getAll());

        $files = $request->getPostFiles();
        $post = $files['file'][0];
        $this->assertEquals('file', $post->getFieldName());
        $this->assertContains('text/x-', $post->getContentType());
        $this->assertEquals(__FILE__, $post->getFilename());

        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request->send();

        $this->assertNotNull($request->getHeader('Content-Length'));
        $this->assertContains('multipart/form-data; boundary=', (string) $request->getHeader('Content-Type'), '-> cURL must add the boundary');
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testSetPostFilesThrowsExceptionWhenFileIsNotFound()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/')
            ->addPostFiles(array(
                'file' => 'filenotfound.ini'
            ));
    }

    /**
     * @expectedException Guzzle\Http\Exception\RequestException
     */
    public function testThrowsExceptionWhenNonStringsAreAddedToPost()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/')
            ->addPostFile('foo', new \stdClass());
    }

    public function testAllowsContentTypeInPostUploads()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/')
            ->addPostFile('foo', __FILE__, 'text/plain');

        $this->assertEquals(array(
            new PostFile('foo', __FILE__, 'text/plain')
        ), $request->getPostFile('foo'));
    }

    public function testGuessesContentTypeOfPostUpload()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/')
            ->addPostFile('foo', __FILE__);
        $file = $request->getPostFile('foo');
        $this->assertContains('text/x-', $file[0]->getContentType());
    }

    public function testAllowsContentDispositionFieldsInPostUploadsWhenSettingInBulk()
    {
        $postFile = new PostFile('foo', __FILE__, 'text/x-php');
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/')
            ->addPostFiles(array('foo' => $postFile));

        $this->assertEquals(array($postFile), $request->getPostFile('foo'));
    }

    public function testPostRequestsUseApplicationXwwwForUrlEncodedForArrays()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/');
        $request->setPostField('a', 'b');
        $this->assertContains("\r\n\r\na=b", (string) $request);
        $this->assertEquals('application/x-www-form-urlencoded; charset=utf-8', $request->getHeader('Content-Type'));
    }

    public function testProcessMethodAddsContentType()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/');
        $request->setPostField('a', 'b');
        $this->assertEquals('application/x-www-form-urlencoded; charset=utf-8', $request->getHeader('Content-Type'));
    }

    public function testPostRequestsUseMultipartFormDataWithFiles()
    {
        $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/');
        $request->addPostFiles(array('file' => __FILE__));
        $this->assertEquals('multipart/form-data', $request->getHeader('Content-Type'));
    }

    public function testCanSendMultipleRequestsUsingASingleRequestObject()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n",
        ));

        // Send the first request
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl())
            ->setBody('test')
            ->setClient(new Client());
        $request->send();
        $this->assertEquals(200, $request->getResponse()->getStatusCode());

        // Send the second request
        $request->setBody('abcdefg', 'application/json', false);
        $request->send();
        $this->assertEquals(201, $request->getResponse()->getStatusCode());

        // Ensure that the same request was sent twice with different bodies
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals(2, count($requests));
        $this->assertEquals(4, (string) $requests[0]->getHeader('Content-Length'));
        $this->assertEquals(7, (string) $requests[1]->getHeader('Content-Length'));
    }

    public function testRemovingPostFieldRebuildsPostFields()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com');
        $request->setPostField('test', 'value');
        $request->removePostField('test');
        $this->assertNull($request->getPostField('test'));
    }

    public function testUsesChunkedTransferWhenBodyLengthCannotBeDetermined()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
        $request->setBody(fopen($this->getServer()->getUrl(), 'r'));
        $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding'));
        $this->assertFalse($request->hasHeader('Content-Length'));
    }

    /**
     * @expectedException \Guzzle\Http\Exception\RequestException
     */
    public function testThrowsExceptionWhenContentLengthCannotBeDeterminedAndUsingHttp1()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request->setProtocolVersion('1.0');
        $request->setBody(fopen($this->getServer()->getUrl(), 'r'));
    }

    public function testAllowsNestedPostData()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFields(array(
            'a' => array('b', 'c')
        ));
        $this->assertEquals(array(
            'a' => array('b', 'c')
        ), $request->getPostFields()->getAll());
    }

    public function testAllowsEmptyFields()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFields(array(
            'a' => ''
        ));
        $this->assertEquals(array(
            'a' => ''
        ), $request->getPostFields()->getAll());
    }

    /**
     * @expectedException \Guzzle\Http\Exception\RequestException
     */
    public function testFailsOnInvalidFiles()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFiles(array(
            'a' => new \stdClass()
        ));
    }

    public function testHandlesEmptyStrings()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFields(array(
            'a' => '',
            'b' => null,
            'c' => 'Foo'
        ));
        $this->assertEquals(array(
            'a' => '',
            'b' => null,
            'c' => 'Foo'
        ), $request->getPostFields()->getAll());
    }

    public function testHoldsPostFiles()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFile('foo', __FILE__);
        $request->addPostFile(new PostFile('foo', __FILE__));

        $this->assertArrayHasKey('foo', $request->getPostFiles());
        $foo = $request->getPostFile('foo');
        $this->assertEquals(2, count($foo));
        $this->assertEquals(__FILE__, $foo[0]->getFilename());
        $this->assertEquals(__FILE__, $foo[1]->getFilename());

        $request->removePostFile('foo');
        $this->assertEquals(array(), $request->getPostFiles());
    }

    public function testAllowsAtPrefixWhenAddingPostFiles()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->addPostFiles(array(
            'foo' => '@' . __FILE__
        ));
        $foo = $request->getPostFile('foo');
        $this->assertEquals(__FILE__, $foo[0]->getFilename());
    }

    public function testSetStateToTransferWithEmptyBodySetsContentLengthToZero()
    {
        $request = new EntityEnclosingRequest('POST', 'http://test.com/');
        $request->setState($request::STATE_TRANSFER);
        $this->assertEquals('0', (string) $request->getHeader('Content-Length'));
    }

    public function testSettingExpectHeaderCutoffChangesRequest()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
        $request->setHeader('Expect', '100-Continue');
        $request->setExpectHeaderCutoff(false);
        $this->assertNull($request->getHeader('Expect'));
        // There is not body, so remove the expect header
        $request->setHeader('Expect', '100-Continue');
        $request->setExpectHeaderCutoff(10);
        $this->assertNull($request->getHeader('Expect'));
        // The size is less than the cutoff
        $request->setBody('foo');
        $this->assertNull($request->getHeader('Expect'));
        // The size is greater than the cutoff
        $request->setBody('foobazbarbamboo');
        $this->assertNotNull($request->getHeader('Expect'));
    }

    public function testStrictRedirectsCanBeSpecifiedOnEntityEnclosingRequests()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
        $request->configureRedirects(true);
        $this->assertTrue($request->getParams()->get(RedirectPlugin::STRICT_REDIRECTS));
    }

    public function testCanDisableRedirects()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/');
        $request->configureRedirects(false, false);
        $this->assertTrue($request->getParams()->get(RedirectPlugin::DISABLE));
    }

    public function testSetsContentTypeWhenSettingBodyByGuessingFromEntityBody()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo');
        $request->setBody(EntityBody::factory(fopen(__FILE__, 'r')));
        $this->assertEquals('text/x-php', (string) $request->getHeader('Content-Type'));
    }

    public function testDoesNotCloneBody()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo');
        $request->setBody('test');
        $newRequest = clone $request;
        $newRequest->setBody('foo');
        $this->assertInternalType('string', (string) $request->getBody());
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Http\Message\Header\HeaderCollection;

/**
 * Class used to compare HTTP headers using a custom DSL
 */
class HeaderComparison
{
    /**
     * Compare HTTP headers and use special markup to filter values
     * A header prefixed with '!' means it must not exist
     * A header prefixed with '_' means it must be ignored
     * A header value of '*' means anything after the * will be ignored
     *
     * @param array $filteredHeaders Array of special headers
     * @param array $actualHeaders   Array of headers to check against
     *
     * @return array|bool Returns an array of the differences or FALSE if none
     */
    public function compare($filteredHeaders, $actualHeaders)
    {
        $expected = array();
        $ignore = array();
        $absent = array();

        if ($actualHeaders instanceof HeaderCollection) {
            $actualHeaders = $actualHeaders->toArray();
        }

        foreach ($filteredHeaders as $k => $v) {
            if ($k[0] == '_') {
                // This header should be ignored
                $ignore[] = str_replace('_', '', $k);
            } elseif ($k[0] == '!') {
                // This header must not be present
                $absent[] = str_replace('!', '', $k);
            } else {
                $expected[$k] = $v;
            }
        }

        return $this->compareArray($expected, $actualHeaders, $ignore, $absent);
    }

    /**
     * Check if an array of HTTP headers matches another array of HTTP headers while taking * into account as a wildcard
     *
     * @param array            $expected Expected HTTP headers (allows wildcard values)
     * @param array|Collection $actual   Actual HTTP header array
     * @param array            $ignore   Headers to ignore from the comparison
     * @param array            $absent   Array of headers that must not be present
     *
     * @return array|bool Returns an array of the differences or FALSE if none
     */
    public function compareArray(array $expected, $actual, array $ignore = array(), array $absent = array())
    {
        $differences = array();

        // Add information about headers that were present but weren't supposed to be
        foreach ($absent as $header) {
            if ($this->hasKey($header, $actual)) {
                $differences["++ {$header}"] = $actual[$header];
                unset($actual[$header]);
            }
        }

        // Check if expected headers are missing
        foreach ($expected as $header => $value) {
            if (!$this->hasKey($header, $actual)) {
                $differences["- {$header}"] = $value;
            }
        }

        // Flip the ignore array so it works with the case insensitive helper
        $ignore = array_flip($ignore);
        // Allow case-insensitive comparisons in wildcards
        $expected = array_change_key_case($expected);

        // Compare the expected and actual HTTP headers in no particular order
        foreach ($actual as $key => $value) {

            // If this is to be ignored, the skip it
            if ($this->hasKey($key, $ignore)) {
                continue;
            }

            // If the header was not expected
            if (!$this->hasKey($key, $expected)) {
                $differences["+ {$key}"] = $value;
                continue;
            }

            // Check values and take wildcards into account
            $lkey = strtolower($key);
            $pos = is_string($expected[$lkey]) ? strpos($expected[$lkey], '*') : false;

            foreach ((array) $actual[$key] as $v) {
                if (($pos === false && $v != $expected[$lkey]) || $pos > 0 && substr($v, 0, $pos) != substr($expected[$lkey], 0, $pos)) {
                    $differences[$key] = "{$value} != {$expected[$lkey]}";
                }
            }
        }

        return empty($differences) ? false : $differences;
    }

    /**
     * Case insensitive check if an array have a key
     *
     * @param string $key   Key to check
     * @param array  $array Array to check
     *
     * @return bool
     */
    protected function hasKey($key, $array)
    {
        if ($array instanceof Collection) {
            $keys = $array->getKeys();
        } else {
            $keys = array_keys($array);
        }

        foreach ($keys as $k) {
            if (!strcasecmp($k, $key)) {
                return true;
            }
        }

        return false;
    }
}
<?php

namespace Guzzle\Tests\Http\Message\Header;

use Guzzle\Http\Message\Header\Link;
use Guzzle\Tests\GuzzleTestCase;

class LinkTest extends GuzzleTestCase
{
    public function testParsesLinks()
    {
        $link = new Link('Link', '<http:/.../front.jpeg>; rel=front; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg", <http://.../side.jpeg?test=1>; rel=side; type="image/jpeg"');
        $links = $link->getLinks();
        $this->assertEquals(array(
            array(
                'rel' => 'front',
                'type' => 'image/jpeg',
                'url' => 'http:/.../front.jpeg',
            ),
            array(
                'rel' => 'back',
                'type' => 'image/jpeg',
                'url' => 'http://.../back.jpeg',
            ),
            array(
                'rel' => 'side',
                'type' => 'image/jpeg',
                'url' => 'http://.../side.jpeg?test=1'
            )
        ), $links);

        $this->assertEquals(array(
            'rel' => 'back',
            'type' => 'image/jpeg',
            'url' => 'http://.../back.jpeg',
        ), $link->getLink('back'));

        $this->assertTrue($link->hasLink('front'));
        $this->assertFalse($link->hasLink('foo'));
    }

    public function testCanAddLink()
    {
        $link = new Link('Link', '<http://foo>; rel=a; type="image/jpeg"');
        $link->addLink('http://test.com', 'test', array('foo' => 'bar'));
        $this->assertEquals(
            '<http://foo>; rel=a; type="image/jpeg", <http://test.com>; rel="test"; foo="bar"',
            (string) $link
        );
    }

    public function testCanParseLinksWithCommas()
    {
        $link = new Link('Link', '<http://example.com/TheBook/chapter1>; rel="previous"; title="start, index"');
        $this->assertEquals(array(
            array(
                'rel' => 'previous',
                'title' => 'start, index',
                'url' => 'http://example.com/TheBook/chapter1',
            )
        ), $link->getLinks());
    }
}
<?php

namespace Guzzle\Tests\Http\Message\Header;

use Guzzle\Http\Message\Header\HeaderFactory;

/**
 * @covers Guzzle\Http\Message\Header\HeaderFactory
 */
class HeaderFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCreatesBasicHeaders()
    {
        $f = new HeaderFactory();
        $h = $f->createHeader('Foo', 'Bar');
        $this->assertInstanceOf('Guzzle\Http\Message\Header', $h);
        $this->assertEquals('Foo', $h->getName());
        $this->assertEquals('Bar', (string) $h);
    }

    public function testCreatesSpecificHeaders()
    {
        $f = new HeaderFactory();
        $h = $f->createHeader('Link', '<http>; rel="test"');
        $this->assertInstanceOf('Guzzle\Http\Message\Header\Link', $h);
        $this->assertEquals('Link', $h->getName());
        $this->assertEquals('<http>; rel="test"', (string) $h);
    }
}
<?php

namespace Guzzle\Tests\Http\Message;

use Guzzle\Http\Message\Header;
use Guzzle\Http\Message\Request;
use Guzzle\Common\Collection;

/**
 * @covers Guzzle\Http\Message\AbstractMessage
 */
class AbstractMessageTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Request Request object */
    private $request;

    /** @var AbstractMessage */
    private $mock;

    public function setUp()
    {
        parent::setUp();
        $this->mock = $this->getMockForAbstractClass('Guzzle\Http\Message\AbstractMessage');
    }

    public function tearDown()
    {
        $this->mock = $this->request = null;
    }

    public function testGetParams()
    {
        $request = new Request('GET', 'http://example.com');
        $this->assertInstanceOf('Guzzle\\Common\\Collection', $request->getParams());
    }

    public function testAddHeaders()
    {
        $this->mock->setHeader('A', 'B');

        $this->assertEquals($this->mock, $this->mock->addHeaders(array(
            'X-Data' => '123'
        )));

        $this->assertTrue($this->mock->hasHeader('X-Data') !== false);
        $this->assertTrue($this->mock->hasHeader('A') !== false);
    }

    public function testAllowsHeaderToSetAsHeader()
    {
        $h = new Header('A', 'B');
        $this->mock->setHeader('A', $h);
        $this->assertSame($h, $this->mock->getHeader('A'));
    }

    public function testGetHeader()
    {
        $this->mock->setHeader('Test', '123');
        $this->assertEquals('123', $this->mock->getHeader('Test'));
    }

    public function testGetHeaders()
    {
        $this->assertSame($this->mock, $this->mock->setHeaders(array('a' => 'b', 'c' => 'd')));
        $h = $this->mock->getHeaders();
        $this->assertArrayHasKey('a', $h->toArray());
        $this->assertArrayHasKey('c', $h->toArray());
        $this->assertInstanceOf('Guzzle\Http\Message\Header\HeaderInterface', $h->get('a'));
        $this->assertInstanceOf('Guzzle\Http\Message\Header\HeaderInterface', $h->get('c'));
    }

    public function testGetHeaderLinesUsesGlue()
    {
        $this->mock->setHeaders(array('a' => 'b', 'c' => 'd'));
        $this->mock->addHeader('a', 'e');
        $this->mock->getHeader('a')->setGlue('!');
        $this->assertEquals(array(
            'a: b! e',
            'c: d'
        ), $this->mock->getHeaderLines());
    }

    public function testHasHeader()
    {
        $this->assertFalse($this->mock->hasHeader('Foo'));
        $this->mock->setHeader('Foo', 'Bar');
        $this->assertEquals(true, $this->mock->hasHeader('Foo'));
        $this->mock->setHeader('foo', 'yoo');
        $this->assertEquals(true, $this->mock->hasHeader('Foo'));
        $this->assertEquals(true, $this->mock->hasHeader('foo'));
        $this->assertEquals(false, $this->mock->hasHeader('bar'));
    }

    public function testRemoveHeader()
    {
        $this->mock->setHeader('Foo', 'Bar');
        $this->assertEquals(true, $this->mock->hasHeader('Foo'));
        $this->mock->removeHeader('Foo');
        $this->assertFalse($this->mock->hasHeader('Foo'));
    }

    public function testReturnsNullWhenHeaderIsNotFound()
    {
        $this->assertNull($this->mock->getHeader('foo'));
    }

    public function testAddingHeadersPreservesOriginalHeaderCase()
    {
        $this->mock->addHeaders(array(
            'test' => '123',
            'Test' => 'abc'
        ));
        $this->mock->addHeader('test', '456');
        $this->mock->addHeader('test', '789');

        $header = $this->mock->getHeader('test');
        $this->assertContains('123', $header->toArray());
        $this->assertContains('456', $header->toArray());
        $this->assertContains('789', $header->toArray());
        $this->assertContains('abc', $header->toArray());
    }

    public function testCanStoreEmptyHeaders()
    {
        $this->mock->setHeader('Content-Length', 0);
        $this->assertTrue($this->mock->hasHeader('Content-Length'));
        $this->assertEquals(0, (string) $this->mock->getHeader('Content-Length'));
    }

    public function testCanSetCustomHeaderFactory()
    {
        $f = new Header\HeaderFactory();
        $this->mock->setHeaderFactory($f);
        $this->assertSame($f, $this->readAttribute($this->mock, 'headerFactory'));
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\EntityBody;
use Guzzle\Http\CachingEntityBody;

/**
 * @covers Guzzle\Http\CachingEntityBody
 */
class CachingEntityBodyTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var CachingEntityBody */
    protected $body;

    /** @var EntityBody */
    protected $decorated;

    public function setUp()
    {
        $this->decorated = EntityBody::factory('testing');
        $this->body = new CachingEntityBody($this->decorated);
    }

    public function testUsesRemoteSizeIfPossible()
    {
        $body = EntityBody::factory('test');
        $caching = new CachingEntityBody($body);
        $this->assertEquals(4, $caching->getSize());
        $this->assertEquals(4, $caching->getContentLength());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage does not support custom stream rewind
     */
    public function testDoesNotAllowRewindFunction()
    {
        $this->body->setRewindFunction(true);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage Cannot seek to byte 10
     */
    public function testCannotSeekPastWhatHasBeenRead()
    {
        $this->body->seek(10);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage supports only SEEK_SET and SEEK_CUR
     */
    public function testCannotUseSeekEnd()
    {
        $this->body->seek(2, SEEK_END);
    }

    public function testChangingUnderlyingStreamUpdatesSizeAndStream()
    {
        $size = filesize(__FILE__);
        $s = fopen(__FILE__, 'r');
        $this->body->setStream($s, $size);
        $this->assertEquals($size, $this->body->getSize());
        $this->assertEquals($size, $this->decorated->getSize());
        $this->assertSame($s, $this->body->getStream());
        $this->assertSame($s, $this->decorated->getStream());
    }

    public function testRewindUsesSeek()
    {
        $a = EntityBody::factory('foo');
        $d = $this->getMockBuilder('Guzzle\Http\CachingEntityBody')
            ->setMethods(array('seek'))
            ->setConstructorArgs(array($a))
            ->getMock();
        $d->expects($this->once())
            ->method('seek')
            ->with(0)
            ->will($this->returnValue(true));
        $d->rewind();
    }

    public function testCanSeekToReadBytes()
    {
        $this->assertEquals('te', $this->body->read(2));
        $this->body->seek(0);
        $this->assertEquals('test', $this->body->read(4));
        $this->assertEquals(4, $this->body->ftell());
        $this->body->seek(2);
        $this->assertEquals(2, $this->body->ftell());
        $this->body->seek(2, SEEK_CUR);
        $this->assertEquals(4, $this->body->ftell());
        $this->assertEquals('ing', $this->body->read(3));
    }

    public function testWritesToBufferStream()
    {
        $this->body->read(2);
        $this->body->write('hi');
        $this->body->rewind();
        $this->assertEquals('tehiing', (string) $this->body);
    }

    public function testReadLinesFromBothStreams()
    {
        $this->body->seek($this->body->ftell());
        $this->body->write("test\n123\nhello\n1234567890\n");
        $this->body->rewind();
        $this->assertEquals("test\n", $this->body->readLine(7));
        $this->assertEquals("123\n", $this->body->readLine(7));
        $this->assertEquals("hello\n", $this->body->readLine(7));
        $this->assertEquals("123456", $this->body->readLine(7));
        $this->assertEquals("7890\n", $this->body->readLine(7));
        // We overwrote the decorated stream, so no more data
        $this->assertEquals('', $this->body->readLine(7));
    }

    public function testSkipsOverwrittenBytes()
    {
        $decorated = EntityBody::factory(
            implode("\n", array_map(function ($n) {
                return str_pad($n, 4, '0', STR_PAD_LEFT);
            }, range(0, 25)))
        );

        $body = new CachingEntityBody($decorated);

        $this->assertEquals("0000\n", $body->readLine());
        $this->assertEquals("0001\n", $body->readLine());
        // Write over part of the body yet to be read, so skip some bytes
        $this->assertEquals(5, $body->write("TEST\n"));
        $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes'));
        // Read, which skips bytes, then reads
        $this->assertEquals("0003\n", $body->readLine());
        $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes'));
        $this->assertEquals("0004\n", $body->readLine());
        $this->assertEquals("0005\n", $body->readLine());

        // Overwrite part of the cached body (so don't skip any bytes)
        $body->seek(5);
        $this->assertEquals(5, $body->write("ABCD\n"));
        $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes'));
        $this->assertEquals("TEST\n", $body->readLine());
        $this->assertEquals("0003\n", $body->readLine());
        $this->assertEquals("0004\n", $body->readLine());
        $this->assertEquals("0005\n", $body->readLine());
        $this->assertEquals("0006\n", $body->readLine());
        $this->assertEquals(5, $body->write("1234\n"));
        $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes'));

        // Seek to 0 and ensure the overwritten bit is replaced
        $body->rewind();
        $this->assertEquals("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", $body->read(50));

        // Ensure that casting it to a string does not include the bit that was overwritten
        $this->assertContains("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", (string) $body);
    }

    public function testWrapsContentType()
    {
        $a = $this->getMockBuilder('Guzzle\Http\EntityBody')
            ->setMethods(array('getContentType'))
            ->setConstructorArgs(array(fopen(__FILE__, 'r')))
            ->getMock();
        $a->expects($this->once())
            ->method('getContentType')
            ->will($this->returnValue('foo'));
        $d = new CachingEntityBody($a);
        $this->assertEquals('foo', $d->getContentType());
    }

    public function testWrapsContentEncoding()
    {
        $a = $this->getMockBuilder('Guzzle\Http\EntityBody')
            ->setMethods(array('getContentEncoding'))
            ->setConstructorArgs(array(fopen(__FILE__, 'r')))
            ->getMock();
        $a->expects($this->once())
            ->method('getContentEncoding')
            ->will($this->returnValue('foo'));
        $d = new CachingEntityBody($a);
        $this->assertEquals('foo', $d->getContentEncoding());
    }

    public function testWrapsMetadata()
    {
        $a = $this->getMockBuilder('Guzzle\Http\EntityBody')
            ->setMethods(array('getMetadata', 'getWrapper', 'getWrapperData', 'getStreamType', 'getUri'))
            ->setConstructorArgs(array(fopen(__FILE__, 'r')))
            ->getMock();

        $a->expects($this->once())
            ->method('getMetadata')
            ->will($this->returnValue(array()));
        // Called twice for getWrapper and getWrapperData
        $a->expects($this->exactly(1))
            ->method('getWrapper')
            ->will($this->returnValue('wrapper'));
        $a->expects($this->once())
            ->method('getWrapperData')
            ->will($this->returnValue(array()));
        $a->expects($this->once())
            ->method('getStreamType')
            ->will($this->returnValue('baz'));
        $a->expects($this->once())
            ->method('getUri')
            ->will($this->returnValue('path/to/foo'));

        $d = new CachingEntityBody($a);
        $this->assertEquals(array(), $d->getMetaData());
        $this->assertEquals('wrapper', $d->getWrapper());
        $this->assertEquals(array(), $d->getWrapperData());
        $this->assertEquals('baz', $d->getStreamType());
        $this->assertEquals('path/to/foo', $d->getUri());
    }

    public function testWrapsCustomData()
    {
        $a = $this->getMockBuilder('Guzzle\Http\EntityBody')
            ->setMethods(array('getCustomData', 'setCustomData'))
            ->setConstructorArgs(array(fopen(__FILE__, 'r')))
            ->getMock();

        $a->expects($this->exactly(1))
            ->method('getCustomData')
            ->with('foo')
            ->will($this->returnValue('bar'));

        $a->expects($this->exactly(1))
            ->method('setCustomData')
            ->with('foo', 'bar')
            ->will($this->returnSelf());

        $d = new CachingEntityBody($a);
        $this->assertSame($d, $d->setCustomData('foo', 'bar'));
        $this->assertEquals('bar', $d->getCustomData('foo'));
    }

    public function testClosesBothStreams()
    {
        $s = fopen('php://temp', 'r');
        $a = EntityBody::factory($s);
        $d = new CachingEntityBody($a);
        $d->close();
        $this->assertFalse(is_resource($s));
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\EntityBody;
use Guzzle\Http\QueryString;

/**
 * @group server
 * @covers Guzzle\Http\EntityBody
 */
class EntityBodyTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testFactoryThrowsException()
    {
        $body = EntityBody::factory(false);
    }

    public function testFactory()
    {
        $body = EntityBody::factory('data');
        $this->assertEquals('data', (string) $body);
        $this->assertEquals(4, $body->getContentLength());
        $this->assertEquals('PHP', $body->getWrapper());
        $this->assertEquals('TEMP', $body->getStreamType());

        $handle = fopen(__DIR__ . '/../../../../phpunit.xml.dist', 'r');
        if (!$handle) {
            $this->fail('Could not open test file');
        }
        $body = EntityBody::factory($handle);
        $this->assertEquals(__DIR__ . '/../../../../phpunit.xml.dist', $body->getUri());
        $this->assertTrue($body->isLocal());
        $this->assertEquals(__DIR__ . '/../../../../phpunit.xml.dist', $body->getUri());
        $this->assertEquals(filesize(__DIR__ . '/../../../../phpunit.xml.dist'), $body->getContentLength());

        // make sure that a body will return as the same object
        $this->assertTrue($body === EntityBody::factory($body));
    }

    public function testFactoryCreatesTempStreamByDefault()
    {
        $body = EntityBody::factory('');
        $this->assertEquals('PHP', $body->getWrapper());
        $this->assertEquals('TEMP', $body->getStreamType());
        $body = EntityBody::factory();
        $this->assertEquals('PHP', $body->getWrapper());
        $this->assertEquals('TEMP', $body->getStreamType());
    }

    public function testFactoryCanCreateFromObject()
    {
        $body = EntityBody::factory(new QueryString(array('foo' => 'bar')));
        $this->assertEquals('foo=bar', (string) $body);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testFactoryEnsuresObjectsHaveToStringMethod()
    {
        EntityBody::factory(new \stdClass('a'));
    }

    public function testHandlesCompression()
    {
        $body = EntityBody::factory('testing 123...testing 123');
        $this->assertFalse($body->getContentEncoding(), '-> getContentEncoding() must initially return FALSE');
        $size = $body->getContentLength();
        $body->compress();
        $this->assertEquals('gzip', $body->getContentEncoding(), '-> getContentEncoding() must return the correct encoding after compressing');
        $this->assertEquals(gzdeflate('testing 123...testing 123'), (string) $body);
        $this->assertTrue($body->getContentLength() < $size);
        $this->assertTrue($body->uncompress());
        $this->assertEquals('testing 123...testing 123', (string) $body);
        $this->assertFalse($body->getContentEncoding(), '-> getContentEncoding() must reset to FALSE');

        if (in_array('bzip2.*', stream_get_filters())) {
            $this->assertTrue($body->compress('bzip2.compress'));
            $this->assertEquals('compress', $body->getContentEncoding(), '-> compress() must set \'compress\' as the Content-Encoding');
        }

        $this->assertFalse($body->compress('non-existent'), '-> compress() must return false when a non-existent stream filter is used');

        // Release the body
        unset($body);

        // Use gzip compression on the initial content.  This will include a
        // gzip header which will need to be stripped when deflating the stream
        $body = EntityBody::factory(gzencode('test'));
        $this->assertSame($body, $body->setStreamFilterContentEncoding('zlib.deflate'));
        $this->assertTrue($body->uncompress('zlib.inflate'));
        $this->assertEquals('test', (string) $body);
        unset($body);

        // Test using a very long string
        $largeString = '';
        for ($i = 0; $i < 25000; $i++) {
            $largeString .= chr(rand(33, 126));
        }
        $body = EntityBody::factory($largeString);
        $this->assertEquals($largeString, (string) $body);
        $this->assertTrue($body->compress());
        $this->assertNotEquals($largeString, (string) $body);
        $compressed = (string) $body;
        $this->assertTrue($body->uncompress());
        $this->assertEquals($largeString, (string) $body);
        $this->assertEquals($compressed, gzdeflate($largeString));

        $body = EntityBody::factory(fopen(__DIR__ . '/../TestData/compress_test', 'w'));
        $this->assertFalse($body->compress());
        unset($body);

        unlink(__DIR__ . '/../TestData/compress_test');
    }

    public function testDeterminesContentType()
    {
        // Test using a string/temp stream
        $body = EntityBody::factory('testing 123...testing 123');
        $this->assertNull($body->getContentType());

        // Use a local file
        $body = EntityBody::factory(fopen(__FILE__, 'r'));
        $this->assertContains('text/x-', $body->getContentType());
    }

    public function testCreatesMd5Checksum()
    {
        $body = EntityBody::factory('testing 123...testing 123');
        $this->assertEquals(md5('testing 123...testing 123'), $body->getContentMd5());

        $server = $this->getServer()->enqueue(
            "HTTP/1.1 200 OK" . "\r\n" .
            "Content-Length: 3" . "\r\n\r\n" .
            "abc"
        );

        $body = EntityBody::factory(fopen($this->getServer()->getUrl(), 'r'));
        $this->assertFalse($body->getContentMd5());
    }

    public function testSeeksToOriginalPosAfterMd5()
    {
        $body = EntityBody::factory('testing 123');
        $body->seek(4);
        $this->assertEquals(md5('testing 123'), $body->getContentMd5());
        $this->assertEquals(4, $body->ftell());
        $this->assertEquals('ing 123', $body->read(1000));
    }

    public function testGetTypeFormBodyFactoring()
    {
        $body = EntityBody::factory(array('key1' => 'val1', 'key2' => 'val2'));
        $this->assertEquals('key1=val1&key2=val2', (string) $body);
    }

    public function testAllowsCustomRewind()
    {
        $body = EntityBody::factory('foo');
        $rewound = false;
        $body->setRewindFunction(function ($body) use (&$rewound) {
            $rewound = true;
            return $body->seek(0);
        });
        $body->seek(2);
        $this->assertTrue($body->rewind());
        $this->assertTrue($rewound);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testCustomRewindFunctionMustBeCallable()
    {
        $body = EntityBody::factory();
        $body->setRewindFunction('foo');
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\EntityBody;
use Guzzle\Http\ReadLimitEntityBody;

/**
 * @covers Guzzle\Http\ReadLimitEntityBody
 */
class ReadLimitEntityBodyTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var ReadLimitEntityBody */
    protected $body;

    /** @var EntityBody */
    protected $decorated;

    public function setUp()
    {
        $this->decorated = EntityBody::factory(fopen(__FILE__, 'r'));
        $this->body = new ReadLimitEntityBody($this->decorated, 10, 3);
    }

    public function testReturnsSubsetWhenCastToString()
    {
        $body = EntityBody::factory('foo_baz_bar');
        $limited = new ReadLimitEntityBody($body, 3, 4);
        $this->assertEquals('baz', (string) $limited);
    }

    public function testReturnsSubsetOfEmptyBodyWhenCastToString()
    {
        $body = EntityBody::factory('');
        $limited = new ReadLimitEntityBody($body, 0, 10);
        $this->assertEquals('', (string) $limited);
    }

    public function testSeeksWhenConstructed()
    {
        $this->assertEquals(3, $this->body->ftell());
    }

    public function testAllowsBoundedSeek()
    {
        $this->body->seek(100);
        $this->assertEquals(13, $this->body->ftell());
        $this->body->seek(0);
        $this->assertEquals(3, $this->body->ftell());
        $this->assertEquals(false, $this->body->seek(1000, SEEK_END));
    }

    public function testReadsOnlySubsetOfData()
    {
        $data = $this->body->read(100);
        $this->assertEquals(10, strlen($data));
        $this->assertFalse($this->body->read(1000));

        $this->body->setOffset(10);
        $newData = $this->body->read(100);
        $this->assertEquals(10, strlen($newData));
        $this->assertNotSame($data, $newData);
    }

    public function testClaimsConsumedWhenReadLimitIsReached()
    {
        $this->assertFalse($this->body->isConsumed());
        $this->body->read(1000);
        $this->assertTrue($this->body->isConsumed());
    }

    public function testContentLengthIsBounded()
    {
        $this->assertEquals(10, $this->body->getContentLength());
    }

    public function testContentMd5IsBasedOnSubsection()
    {
        $this->assertNotSame($this->body->getContentMd5(), $this->decorated->getContentMd5());
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\QueryString;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Http\QueryAggregator\CommaAggregator;

class QueryStringTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var \Guzzle\Http\QueryString The query string object to test */
    protected $q;

    public function setup()
    {
        $this->q = new QueryString();
    }

    public function testGetFieldSeparator()
    {
        $this->assertEquals('&', $this->q->getFieldSeparator());
    }

    public function testGetValueSeparator()
    {
        $this->assertEquals('=', $this->q->getValueSeparator());
    }

    public function testIsUrlEncoding()
    {
        $this->assertEquals('RFC 3986', $this->q->getUrlEncoding());
        $this->assertTrue($this->q->isUrlEncoding());
        $this->assertEquals('foo%20bar', $this->q->encodeValue('foo bar'));

        $this->q->useUrlEncoding(QueryString::FORM_URLENCODED);
        $this->assertTrue($this->q->isUrlEncoding());
        $this->assertEquals(QueryString::FORM_URLENCODED, $this->q->getUrlEncoding());
        $this->assertEquals('foo+bar', $this->q->encodeValue('foo bar'));

        $this->assertSame($this->q, $this->q->useUrlEncoding(false));
        $this->assertFalse($this->q->isUrlEncoding());
        $this->assertFalse($this->q->isUrlEncoding());
    }

    public function testSetFieldSeparator()
    {
        $this->assertEquals($this->q, $this->q->setFieldSeparator('/'));
        $this->assertEquals('/', $this->q->getFieldSeparator());
    }

    public function testSetValueSeparator()
    {
        $this->assertEquals($this->q, $this->q->setValueSeparator('/'));
        $this->assertEquals('/', $this->q->getValueSeparator());
    }

    public function testUrlEncode()
    {
        $params = array(
            'test'   => 'value',
            'test 2' => 'this is a test?',
            'test3'  => array('v1', 'v2', 'v3'),
            'ሴ'      => 'bar'
        );
        $encoded = array(
            'test'         => 'value',
            'test%202'     => rawurlencode('this is a test?'),
            'test3%5B0%5D' => 'v1',
            'test3%5B1%5D' => 'v2',
            'test3%5B2%5D' => 'v3',
            '%E1%88%B4'    => 'bar'
        );
        $this->q->replace($params);
        $this->assertEquals($encoded, $this->q->urlEncode());

        // Disable encoding
        $testData = array('test 2' => 'this is a test');
        $this->q->replace($testData);
        $this->q->useUrlEncoding(false);
        $this->assertEquals($testData, $this->q->urlEncode());
    }

    public function testToString()
    {
        // Check with no parameters
        $this->assertEquals('', $this->q->__toString());

        $params = array(
            'test'   => 'value',
            'test 2' => 'this is a test?',
            'test3'  => array('v1', 'v2', 'v3'),
            'test4'  => null,
        );
        $this->q->replace($params);
        $this->assertEquals('test=value&test%202=this%20is%20a%20test%3F&test3%5B0%5D=v1&test3%5B1%5D=v2&test3%5B2%5D=v3&test4', $this->q->__toString());
        $this->q->useUrlEncoding(false);
        $this->assertEquals('test=value&test 2=this is a test?&test3[0]=v1&test3[1]=v2&test3[2]=v3&test4', $this->q->__toString());

        // Use an alternative aggregator
        $this->q->setAggregator(new CommaAggregator());
        $this->assertEquals('test=value&test 2=this is a test?&test3=v1,v2,v3&test4', $this->q->__toString());
    }

    public function testAllowsMultipleValuesPerKey()
    {
        $q = new QueryString();
        $q->add('facet', 'size');
        $q->add('facet', 'width');
        $q->add('facet.field', 'foo');
        // Use the duplicate aggregator
        $q->setAggregator(new DuplicateAggregator());
        $this->assertEquals('facet=size&facet=width&facet.field=foo', $q->__toString());
    }

    public function testAllowsNestedQueryData()
    {
        $this->q->replace(array(
            'test' => 'value',
            't' => array(
                'v1' => 'a',
                'v2' => 'b',
                'v3' => array(
                    'v4' => 'c',
                    'v5' => 'd',
                )
            )
        ));

        $this->q->useUrlEncoding(false);
        $this->assertEquals('test=value&t[v1]=a&t[v2]=b&t[v3][v4]=c&t[v3][v5]=d', $this->q->__toString());
    }

    public function parseQueryProvider()
    {
        return array(
            // Ensure that multiple query string values are allowed per value
            array('q=a&q=b', array('q' => array('a', 'b'))),
            // Ensure that PHP array style query string values are parsed
            array('q[]=a&q[]=b', array('q' => array('a', 'b'))),
            // Ensure that a single PHP array style query string value is parsed into an array
            array('q[]=a', array('q' => array('a'))),
            // Ensure that decimals are allowed in query strings
            array('q.a=a&q.b=b', array(
                'q.a' => 'a',
                'q.b' => 'b'
            )),
            // Ensure that query string values are percent decoded
            array('q%20a=a%20b', array('q a' => 'a b')),
            // Ensure null values can be added
            array('q&a', array('q' => false, 'a' => false)),
        );
    }

    /**
     * @dataProvider parseQueryProvider
     */
    public function testParsesQueryStrings($query, $data)
    {
        $query = QueryString::fromString($query);
        $this->assertEquals($data, $query->getAll());
    }

    public function testProperlyDealsWithDuplicateQueryStringValues()
    {
        $query = QueryString::fromString('foo=a&foo=b&?µ=c');
        $this->assertEquals(array('a', 'b'), $query->get('foo'));
        $this->assertEquals('c', $query->get('?µ'));
    }

    public function testAllowsBlankQueryStringValues()
    {
        $query = QueryString::fromString('foo');
        $this->assertEquals('foo', (string) $query);
        $query->set('foo', QueryString::BLANK);
        $this->assertEquals('foo', (string) $query);
    }

    public function testAllowsFalsyQueryStringValues()
    {
        $query = QueryString::fromString('0');
        $this->assertEquals('0', (string) $query);
        $query->set('0', QueryString::BLANK);
        $this->assertSame('0', (string) $query);
    }

    public function testFromStringIgnoresQuestionMark()
    {
        $query = QueryString::fromString('foo=baz&bar=boo');
        $this->assertEquals('foo=baz&bar=boo', (string) $query);
    }

    public function testConvertsPlusSymbolsToSpaces()
    {
        $query = QueryString::fromString('var=foo+bar');
        $this->assertEquals('foo bar', $query->get('var'));
    }

    public function testFromStringDoesntMangleZeroes()
    {
        $query = QueryString::fromString('var=0');
        $this->assertSame('0', $query->get('var'));
    }

    public function testAllowsZeroValues()
    {
        $query = new QueryString(array(
            'foo' => 0,
            'baz' => '0',
            'bar' => null,
            'boo' => false,
            'bam' => ''
        ));
        $this->assertEquals('foo=0&baz=0&bar&boo&bam=', (string) $query);
    }

    public function testFromStringDoesntStripTrailingEquals()
    {
        $query = QueryString::fromString('data=mF0b3IiLCJUZWFtIERldiJdfX0=');
        $this->assertEquals('mF0b3IiLCJUZWFtIERldiJdfX0=', $query->get('data'));
    }

    public function testGuessesIfDuplicateAggregatorShouldBeUsed()
    {
        $query = QueryString::fromString('test=a&test=b');
        $this->assertEquals('test=a&test=b', (string) $query);
    }

    public function testGuessesIfDuplicateAggregatorShouldBeUsedAndChecksForPhpStyle()
    {
        $query = QueryString::fromString('test[]=a&test[]=b');
        $this->assertEquals('test%5B0%5D=a&test%5B1%5D=b', (string) $query);
    }
}
<?php

namespace Guzzle\Tests\Http\Curl;

use Guzzle\Common\Event;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Curl\CurlMulti;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Tests\Mock\MockMulti;

/**
 * @group server
 * @covers Guzzle\Http\Curl\CurlMulti
 */
class CurlMultiTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var \Guzzle\Http\Curl\CurlMulti */
    private $multi;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->multi = new MockMulti();
    }

    public function tearDown()
    {
        unset($this->multi);
    }

    public function testConstructorCreateMultiHandle()
    {
        $this->assertInternalType('resource', $this->multi->getHandle());
        $this->assertEquals('curl_multi', get_resource_type($this->multi->getHandle()));
    }

    public function testDestructorClosesMultiHandle()
    {
        $handle = $this->multi->getHandle();
        $this->multi->__destruct();
        $this->assertFalse(is_resource($handle));
    }

    public function testRequestsCanBeAddedAndCounted()
    {
        $multi = new CurlMulti();
        $request1 = new Request('GET', 'http://www.google.com/');
        $multi->add($request1);
        $this->assertEquals(array($request1), $multi->all());
        $request2 = new Request('POST', 'http://www.google.com/');
        $multi->add($request2);
        $this->assertEquals(array($request1, $request2), $multi->all());
        $this->assertEquals(2, count($multi));
    }

    public function testRequestsCanBeRemoved()
    {
        $request1 = new Request('GET', 'http://www.google.com/');
        $this->multi->add($request1);
        $request2 = new Request('PUT', 'http://www.google.com/');
        $this->multi->add($request2);
        $this->assertEquals(array($request1, $request2), $this->multi->all());
        $this->assertTrue($this->multi->remove($request1));
        $this->assertFalse($this->multi->remove($request1));
        $this->assertEquals(array($request2), $this->multi->all());
    }

    public function testsResetRemovesRequestsAndResetsState()
    {
        $this->multi->add(new Request('GET', 'http://www.google.com/'));
        $this->multi->reset();
        $this->assertEquals(array(), $this->multi->all());
    }

    public function testSendsRequestsThroughCurl()
    {
        $this->getServer()->enqueue(array(
            "HTTP/1.1 204 No content\r\n" .
            "Content-Length: 0\r\n" .
            "Server: Jetty(6.1.3)\r\n\r\n",
            "HTTP/1.1 200 OK\r\n" .
            "Content-Type: text/html; charset=utf-8\r\n" .
            "Content-Length: 4\r\n" .
            "Server: Jetty(6.1.3)\r\n\r\n" .
            "data"
        ));

        $request1 = new Request('GET', $this->getServer()->getUrl());
        $request2 = new Request('GET', $this->getServer()->getUrl());
        $this->multi->add($request1);
        $this->multi->add($request2);
        $this->multi->send();

        $response1 = $request1->getResponse();
        $response2 = $request2->getResponse();
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response1);
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response2);

        $this->assertTrue($response1->getBody(true) == 'data' || $response2->getBody(true) == 'data');
        $this->assertTrue($response1->getBody(true) == '' || $response2->getBody(true) == '');
        $this->assertTrue($response1->getStatusCode() == '204' || $response2->getStatusCode() == '204');
        $this->assertNotEquals((string) $response1, (string) $response2);
    }

    public function testSendsThroughCurlAndAggregatesRequestExceptions()
    {
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n" .
            "Content-Type: text/html; charset=utf-8\r\n" .
            "Content-Length: 4\r\n" .
            "Server: Jetty(6.1.3)\r\n" .
            "\r\n" .
            "data",
            "HTTP/1.1 204 No content\r\n" .
            "Content-Length: 0\r\n" .
            "Server: Jetty(6.1.3)\r\n" .
            "\r\n",
            "HTTP/1.1 404 Not Found\r\n" .
            "Content-Length: 0\r\n" .
            "\r\n"
        ));

        $request1 = new Request('GET', $this->getServer()->getUrl());
        $request2 = new Request('HEAD', $this->getServer()->getUrl());
        $request3 = new Request('GET', $this->getServer()->getUrl());
        $this->multi->add($request1);
        $this->multi->add($request2);
        $this->multi->add($request3);

        try {
            $this->multi->send();
            $this->fail('MultiTransferException not thrown when aggregating request exceptions');
        } catch (MultiTransferException $e) {

            $this->assertTrue($e->containsRequest($request1));
            $this->assertTrue($e->containsRequest($request2));
            $this->assertTrue($e->containsRequest($request3));
            $this->assertInstanceOf('ArrayIterator', $e->getIterator());
            $this->assertEquals(1, count($e));
            $exceptions = $e->getIterator();

            $response1 = $request1->getResponse();
            $response2 = $request2->getResponse();
            $response3 = $request3->getResponse();

            $this->assertNotEquals((string) $response1, (string) $response2);
            $this->assertNotEquals((string) $response3, (string) $response1);
            $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response1);
            $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response2);
            $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response3);

            $failed = $exceptions[0]->getResponse();
            $this->assertEquals(404, $failed->getStatusCode());
            $this->assertEquals(1, count($e));

            // Test the IteratorAggregate functionality
            foreach ($e as $except) {
                $this->assertEquals($failed, $except->getResponse());
            }

            $this->assertEquals(1, count($e->getFailedRequests()));
            $this->assertEquals(2, count($e->getSuccessfulRequests()));
            $this->assertEquals(3, count($e->getAllRequests()));
        }
    }

    public function testCurlErrorsAreCaught()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        try {
            $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:9876/');
            $request->setClient(new Client());
            $request->getCurlOptions()->set(CURLOPT_FRESH_CONNECT, true);
            $request->getCurlOptions()->set(CURLOPT_FORBID_REUSE, true);
            $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, 5);
            $request->send();
            $this->fail('CurlException not thrown');
        } catch (CurlException $e) {
            $m = $e->getMessage();
            $this->assertContains('[curl] ', $m);
            $this->assertContains('[url] http://127.0.0.1:9876/', $m);
            $this->assertInternalType('array', $e->getCurlInfo());
        }
    }

    public function testRemovesQueuedRequests()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:9876/');
        $r = new Response(200);
        $request->setClient(new Client());
        $request->setResponse($r, true);
        $this->multi->add($request);
        $this->multi->send();
        $this->assertSame($r, $request->getResponse());
    }

    public function testRemovesQueuedRequestsAddedInTransit()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"));
        $client = new Client($this->getServer()->getUrl());
        $r = $client->get();
        $r->getEventDispatcher()->addListener('request.receive.status_line', function (Event $event) use ($client) {
            // Create a request using a queued response
            $request = $client->get()->setResponse(new Response(200), true);
            $request->send();
        });
        $r->send();
        $this->assertEquals(1, count($this->getServer()->getReceivedRequests(false)));
    }

    public function testCatchesExceptionsBeforeSendingSingleRequest()
    {
        $client = new Client($this->getServer()->getUrl());
        $multi = new CurlMulti();
        $client->setCurlMulti($multi);
        $request = $client->get();
        $request->getEventDispatcher()->addListener('request.before_send', function() {
            throw new \RuntimeException('Testing!');
        });
        try {
            $request->send();
            $this->fail('Did not throw');
        } catch (\RuntimeException $e) {
            // Ensure it was removed
            $this->assertEquals(0, count($multi));
        }
    }

    /**
     * @expectedException \Guzzle\Common\Exception\ExceptionCollection
     * @expectedExceptionMessage Thrown before sending!
     */
    public function testCatchesExceptionsBeforeSendingMultipleRequests()
    {
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get();
        $request->getEventDispatcher()->addListener('request.before_send', function() {
            throw new \RuntimeException('Thrown before sending!');
        });
        $client->send(array($request));
    }

    public function testCatchesExceptionsWhenRemovingQueuedRequests()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $r = $client->get();
        $r->getEventDispatcher()->addListener('request.sent', function() use ($client) {
            // Create a request using a queued response
            $client->get()->setResponse(new Response(404), true)->send();
        });
        try {
            $r->send();
            $this->fail('Did not throw');
        } catch (BadResponseException $e) {
            $this->assertCount(0, $client->getCurlMulti());
        }
    }

    public function testCatchesExceptionsWhenRemovingQueuedRequestsBeforeSending()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $r = $client->get();
        $r->getEventDispatcher()->addListener('request.before_send', function() use ($client) {
            // Create a request using a queued response
            $client->get()->setResponse(new Response(404), true)->send();
        });
        try {
            $r->send();
            $this->fail('Did not throw');
        } catch (BadResponseException $e) {
            $this->assertCount(0, $client->getCurlMulti());
        }
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage test
     */
    public function testDoesNotCatchRandomExceptionsThrownDuringPerform()
    {
        $client = new Client($this->getServer()->getUrl());
        $multi = $this->getMock('Guzzle\\Http\\Curl\\CurlMulti', array('perform'));
        $multi->expects($this->once())
            ->method('perform')
            ->will($this->throwException(new \RuntimeException('test')));
        $multi->add($client->get());
        $multi->send();
    }

    public function testDoesNotSendRequestsDecliningToBeSent()
    {
        if (!defined('CURLOPT_TIMEOUT_MS')) {
            $this->markTestSkipped('Update curl');
        }

        // Create a client that is bound to fail connecting
        $client = new Client('http://127.0.0.1:123', array(
            'curl.CURLOPT_PORT'              => 123,
            'curl.CURLOPT_CONNECTTIMEOUT_MS' => 1,
        ));

        $request = $client->get();
        $multi = new CurlMulti();
        $multi->add($request);

        // Listen for request exceptions, and when they occur, first change the
        // state of the request back to transferring, and then just allow it to
        // exception out
        $request->getEventDispatcher()->addListener('request.exception', function(Event $event) use ($multi) {
            $retries = $event['request']->getParams()->get('retries');
            // Allow the first failure to retry
            if ($retries == 0) {
                $event['request']->setState('transfer');
                $event['request']->getParams()->set('retries', 1);
                // Remove the request to try again
                $multi->remove($event['request']);
                $multi->add($event['request']);
            }
        });

        try {
            $multi->send();
            $this->fail('Did not throw an exception at all!?!');
        } catch (\Exception $e) {
            $this->assertEquals(1, $request->getParams()->get('retries'));
        }
    }

    public function testDoesNotThrowExceptionsWhenRequestsRecoverWithRetry()
    {
        $this->getServer()->flush();
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get();
        $request->getEventDispatcher()->addListener('request.before_send', function(Event $event) {
            $event['request']->setResponse(new Response(200));
        });

        $multi = new CurlMulti();
        $multi->add($request);
        $multi->send();
        $this->assertEquals(0, count($this->getServer()->getReceivedRequests(false)));
    }

    public function testDoesNotThrowExceptionsWhenRequestsRecoverWithSuccess()
    {
        // Attempt a port that 99.9% is not listening
        $client = new Client('http://127.0.0.1:123');
        $request = $client->get();
        // Ensure it times out quickly if needed
        $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, 1)->set(CURLOPT_CONNECTTIMEOUT_MS, 1);

        $request->getEventDispatcher()->addListener('request.exception', function(Event $event) use (&$count) {
            $event['request']->setResponse(new Response(200));
        });

        $multi = new CurlMulti();
        $multi->add($request);
        $multi->send();

        // Ensure that the exception was caught, and the response was set manually
        $this->assertEquals(200, $request->getResponse()->getStatusCode());
    }

    public function testHardResetReopensMultiHandle()
    {
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));

        $stream = fopen('php://temp', 'w+');
        $client = new Client($this->getServer()->getUrl());
        $client->getConfig()->set('curl.CURLOPT_VERBOSE', true)->set('curl.CURLOPT_STDERR', $stream);

        $request = $client->get();
        $multi = new CurlMulti();
        $multi->add($request);
        $multi->send();
        $multi->reset(true);
        $multi->add($request);
        $multi->send();

        rewind($stream);
        $this->assertNotContains('Re-using existing connection', stream_get_contents($stream));
    }

    public function testThrowsMeaningfulExceptionsForCurlMultiErrors()
    {
        $multi = new CurlMulti();

        // Set the state of the multi object to sending to trigger the exception
        $reflector = new \ReflectionMethod('Guzzle\Http\Curl\CurlMulti', 'checkCurlResult');
        $reflector->setAccessible(true);

        // Successful
        $reflector->invoke($multi, 0);

        // Known error
        try {
            $reflector->invoke($multi, CURLM_BAD_HANDLE);
            $this->fail('Expected an exception here');
        } catch (CurlException $e) {
            $this->assertContains('The passed-in handle is not a valid CURLM handle.', $e->getMessage());
            $this->assertContains('CURLM_BAD_HANDLE', $e->getMessage());
            $this->assertContains(strval(CURLM_BAD_HANDLE), $e->getMessage());
        }

        // Unknown error
        try {
            $reflector->invoke($multi, 255);
            $this->fail('Expected an exception here');
        } catch (CurlException $e) {
            $this->assertEquals('Unexpected cURL error: 255', $e->getMessage());
        }
    }

    public function testRequestBeforeSendIncludesContentLengthHeaderIfEmptyBody()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $request = new Request('PUT', $this->getServer()->getUrl());
        $that = $this;
        $request->getEventDispatcher()->addListener('request.before_send', function ($event) use ($that) {
            $that->assertEquals(0, $event['request']->getHeader('Content-Length'));
        });
        $this->multi->add($request);
        $this->multi->send();
    }

    public function testRemovesConflictingTransferEncodingHeader()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/', null, fopen($this->getServer()->getUrl(), 'r'));
        $request->setHeader('Content-Length', 4);
        $request->send();
        $received = $this->getServer()->getReceivedRequests(true);
        $this->assertFalse($received[1]->hasHeader('Transfer-Encoding'));
        $this->assertEquals(4, (string) $received[1]->getHeader('Content-Length'));
    }
}
<?php

namespace Guzzle\Tests\Http\Curl;

use Guzzle\Http\Client;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Curl\CurlMultiProxy;

/**
 * @group server
 * @covers Guzzle\Http\Curl\CurlMultiProxy
 */
class CurlMultiProxyTest extends \Guzzle\Tests\GuzzleTestCase
{
    const SELECT_TIMEOUT = 23.1;

    const MAX_HANDLES = 2;

    /** @var \Guzzle\Http\Curl\CurlMultiProxy */
    private $multi;

    protected function setUp()
    {
        parent::setUp();
        $this->multi = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT);
    }

    public function tearDown()
    {
        unset($this->multi);
    }

    public function testConstructorSetsMaxHandles()
    {
        $m = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT);
        $this->assertEquals(self::MAX_HANDLES, $this->readAttribute($m, 'maxHandles'));
    }

    public function testConstructorSetsSelectTimeout()
    {
        $m = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT);
        $this->assertEquals(self::SELECT_TIMEOUT, $this->readAttribute($m, 'selectTimeout'));
    }

    public function testAddingRequestsAddsToQueue()
    {
        $r = new Request('GET', 'http://www.foo.com');
        $this->assertSame($this->multi, $this->multi->add($r));
        $this->assertEquals(1, count($this->multi));
        $this->assertEquals(array($r), $this->multi->all());

        $this->assertTrue($this->multi->remove($r));
        $this->assertFalse($this->multi->remove($r));
        $this->assertEquals(0, count($this->multi));
    }

    public function testResetClearsState()
    {
        $r = new Request('GET', 'http://www.foo.com');
        $this->multi->add($r);
        $this->multi->reset();
        $this->assertEquals(0, count($this->multi));
    }

    public function testSendWillSendQueuedRequestsFirst()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $events = array();
        $client->getCurlMulti()->getEventDispatcher()->addListener(
            CurlMultiProxy::ADD_REQUEST,
            function ($e) use (&$events) {
                $events[] = $e;
            }
        );
        $request = $client->get();
        $request->getEventDispatcher()->addListener('request.complete', function () use ($client) {
            $client->get('/foo')->send();
        });
        $request->send();
        $received = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals(2, count($received));
        $this->assertEquals($this->getServer()->getUrl(), $received[0]->getUrl());
        $this->assertEquals($this->getServer()->getUrl() . 'foo', $received[1]->getUrl());
        $this->assertEquals(2, count($events));
    }

    public function testTrimsDownMaxHandleCount()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));
        $client = new Client($this->getServer()->getUrl());
        $client->setCurlMulti(new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT));
        $request = $client->get();
        $request->send();
        $this->assertEquals(200, $request->getResponse()->getStatusCode());
        $handles = $this->readAttribute($client->getCurlMulti(), 'handles');
        $this->assertEquals(2, count($handles));
    }
}
<?php

namespace Guzzle\Tests\Http\Curl;

use Guzzle\Http\Client;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Curl\RequestMediator;

/**
 * @covers Guzzle\Http\Curl\RequestMediator
 */
class RequestMediatorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public $events = array();

    public function event($event)
    {
        $this->events[] = $event;
    }

    public function testEmitsEvents()
    {
        $request = new EntityEnclosingRequest('PUT', 'http://www.example.com');
        $request->setBody('foo');
        $request->setResponse(new Response(200));

        // Ensure that IO events are emitted
        $request->getCurlOptions()->set('emit_io', true);

        // Attach listeners for each event type
        $request->getEventDispatcher()->addListener('curl.callback.progress', array($this, 'event'));
        $request->getEventDispatcher()->addListener('curl.callback.read', array($this, 'event'));
        $request->getEventDispatcher()->addListener('curl.callback.write', array($this, 'event'));

        $mediator = new RequestMediator($request, true);

        $mediator->progress('a', 'b', 'c', 'd');
        $this->assertEquals(1, count($this->events));
        $this->assertEquals('curl.callback.progress', $this->events[0]->getName());

        $this->assertEquals(3, $mediator->writeResponseBody('foo', 'bar'));
        $this->assertEquals(2, count($this->events));
        $this->assertEquals('curl.callback.write', $this->events[1]->getName());
        $this->assertEquals('bar', $this->events[1]['write']);
        $this->assertSame($request, $this->events[1]['request']);

        $this->assertEquals('foo', $mediator->readRequestBody('a', 'b', 3));
        $this->assertEquals(3, count($this->events));
        $this->assertEquals('curl.callback.read', $this->events[2]->getName());
        $this->assertEquals('foo', $this->events[2]['read']);
        $this->assertSame($request, $this->events[2]['request']);
    }

    public function testDoesNotUseRequestResponseBodyWhenNotCustom()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 307 Foo\r\nLocation: /foo\r\nContent-Length: 2\r\n\r\nHI",
            "HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 2\r\n\r\nFI",
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest",
        ));
        $client = new Client($this->getServer()->getUrl());
        $response = $client->get()->send();
        $this->assertEquals('test', $response->getBody(true));
    }
}
<?php

namespace Guzzle\Tests\Http\Curl;

use Guzzle\Common\Collection;
use Guzzle\Common\Event;
use Guzzle\Http\EntityBody;
use Guzzle\Http\QueryString;
use Guzzle\Http\Client;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Curl\CurlHandle;

/**
 * @group server
 * @covers Guzzle\Http\Curl\CurlHandle
 */
class CurlHandleTest extends \Guzzle\Tests\GuzzleTestCase
{
    public $requestHandle;

    protected function updateForHandle(RequestInterface $request)
    {
        $that = $this;
        $request->getEventDispatcher()->addListener('request.sent', function (Event $e) use ($that) {
            $that->requestHandle = $e['handle'];
        });

        return $request;
    }

    public function setUp()
    {
        $this->requestHandle = null;
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorExpectsCurlResource()
    {
        $h = new CurlHandle(false, array());
    }

    public function testConstructorExpectsProperOptions()
    {
        $h = curl_init($this->getServer()->getUrl());
        try {
            $ha = new CurlHandle($h, false);
            $this->fail('Expected InvalidArgumentException');
        } catch (\InvalidArgumentException $e) {
        }

       $ha = new CurlHandle($h, array(
           CURLOPT_URL => $this->getServer()->getUrl()
       ));
       $this->assertEquals($this->getServer()->getUrl(), $ha->getOptions()->get(CURLOPT_URL));

       $ha = new CurlHandle($h, new Collection(array(
           CURLOPT_URL => $this->getServer()->getUrl()
       )));
       $this->assertEquals($this->getServer()->getUrl(), $ha->getOptions()->get(CURLOPT_URL));
    }

    public function testConstructorInitializesObject()
    {
        $handle = curl_init($this->getServer()->getUrl());
        $h = new CurlHandle($handle, array(
            CURLOPT_URL => $this->getServer()->getUrl()
        ));
        $this->assertSame($handle, $h->getHandle());
        $this->assertInstanceOf('Guzzle\\Http\\Url', $h->getUrl());
        $this->assertEquals($this->getServer()->getUrl(), (string) $h->getUrl());
        $this->assertEquals($this->getServer()->getUrl(), $h->getOptions()->get(CURLOPT_URL));
    }

    public function testStoresStdErr()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://test.com');
        $request->getCurlOptions()->set('debug', true);
        $h = CurlHandle::factory($request);
        $this->assertEquals($h->getStderr(true), $h->getOptions()->get(CURLOPT_STDERR));
        $this->assertInternalType('resource', $h->getStderr(true));
        $this->assertInternalType('string', $h->getStderr(false));
        $r = $h->getStderr(true);
        fwrite($r, 'test');
        $this->assertEquals('test', $h->getStderr(false));
    }

    public function testStoresCurlErrorNumber()
    {
        $h = new CurlHandle(curl_init('http://test.com'), array(CURLOPT_URL => 'http://test.com'));
        $this->assertEquals(CURLE_OK, $h->getErrorNo());
        $h->setErrorNo(CURLE_OPERATION_TIMEOUTED);
        $this->assertEquals(CURLE_OPERATION_TIMEOUTED, $h->getErrorNo());
    }

    public function testAccountsForMissingStdErr()
    {
        $handle = curl_init('http://www.test.com/');
        $h = new CurlHandle($handle, array(
            CURLOPT_URL => 'http://www.test.com/'
        ));
        $this->assertNull($h->getStderr(false));
    }

    public function testDeterminesIfResourceIsAvailable()
    {
        $handle = curl_init($this->getServer()->getUrl());
        $h = new CurlHandle($handle, array());
        $this->assertTrue($h->isAvailable());

        // Mess it up by closing the handle
        curl_close($handle);
        $this->assertFalse($h->isAvailable());

        // Mess it up by unsetting the handle
        $handle = null;
        $this->assertFalse($h->isAvailable());
    }

    public function testWrapsErrorsAndInfo()
    {
        if (!defined('CURLOPT_TIMEOUT_MS')) {
            $this->markTestSkipped('Update curl');
        }

        $settings = array(
            CURLOPT_PORT              => 123,
            CURLOPT_CONNECTTIMEOUT_MS => 1,
            CURLOPT_TIMEOUT_MS        => 1
        );

        $handle = curl_init($this->getServer()->getUrl());
        curl_setopt_array($handle, $settings);
        $h = new CurlHandle($handle, $settings);
        @curl_exec($handle);

        $errors = array(
            "couldn't connect to host",
            'timeout was reached',
            'connection time-out',
            'connect() timed out!',
            'failed connect to 127.0.0.1:123; connection refused',
            'failed to connect to 127.0.0.1 port 123: connection refused'
        );
        $this->assertTrue(in_array(strtolower($h->getError()), $errors), $h->getError() . ' was not the error');

        $this->assertTrue($h->getErrorNo() > 0);

        $this->assertEquals($this->getServer()->getUrl(), $h->getInfo(CURLINFO_EFFECTIVE_URL));
        $this->assertInternalType('array', $h->getInfo());

        curl_close($handle);
        $this->assertEquals(null, $h->getInfo('url'));
    }

    public function testGetInfoWithoutDebugMode()
    {
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get($this->getServer()->getUrl());
        $response = $request->send();

        $info = $response->getInfo();
        $this->assertFalse(empty($info));
        $this->assertEquals($this->getServer()->getUrl(), $info['url']);
    }

    public function testWrapsCurlOptions()
    {
        $handle = curl_init($this->getServer()->getUrl());
        $h = new CurlHandle($handle, array(
            CURLOPT_AUTOREFERER => true,
            CURLOPT_BUFFERSIZE => 1024
        ));

        $this->assertEquals(true, $h->getOptions()->get(CURLOPT_AUTOREFERER));
        $this->assertEquals(1024, $h->getOptions()->get(CURLOPT_BUFFERSIZE));
    }

    /**
     * Data provider for factory tests
     *
     * @return array
     */
    public function dataProvider()
    {
        $testFile = __DIR__ . '/../../../../../phpunit.xml.dist';

        $postBody = new QueryString(array('file' => '@' . $testFile));
        $qs = new QueryString(array(
            'x' => 'y',
            'z' => 'a'
        ));

        $client = new Client();
        $userAgent = $client->getDefaultUserAgent();
        $auth = base64_encode('michael:123');
        $testFileSize = filesize($testFile);

        $tests = array(
            // Send a regular GET
            array('GET', 'http://www.google.com/', null, null, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent),
            )),
            // Test that custom request methods can be used
            array('TRACE', 'http://www.google.com/', null, null, array(
                CURLOPT_CUSTOMREQUEST => 'TRACE'
            )),
            // Send a GET using a port
            array('GET', 'http://127.0.0.1:8080', null, null, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_PORT => 8080,
                CURLOPT_HTTPHEADER => array('Accept:', 'Host: 127.0.0.1:8080', 'User-Agent: ' . $userAgent),
            )),
            // Send a HEAD request
            array('HEAD', 'http://www.google.com/', null, null, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent),
                CURLOPT_NOBODY => 1
            )),
            // Send a GET using basic auth
            array('GET', 'https://michael:123@127.0.0.1/index.html?q=2', null, null, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_HTTPHEADER => array(
                    'Accept:',
                    'Host: 127.0.0.1',
                    'Authorization: Basic ' . $auth,
                    'User-Agent: ' . $userAgent
                ),
                CURLOPT_PORT => 443
            )),
            // Send a GET request with custom headers
            array('GET', 'http://127.0.0.1:8124/', array(
                'x-test-data' => 'Guzzle'
            ), null, array(
                CURLOPT_PORT => 8124,
                CURLOPT_HTTPHEADER => array(
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'x-test-data: Guzzle',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'x-test-data'      => 'Guzzle'
            )),
            // Send a POST using a query string
            array('POST', 'http://127.0.0.1:8124/post.php', null, $qs, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_POSTFIELDS => 'x=y&z=a',
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Length'   => '7',
                '!Expect'          => null,
                'Content-Type'     => 'application/x-www-form-urlencoded; charset=utf-8',
                '!Transfer-Encoding' => null
            )),
            // Send a PUT using raw data
            array('PUT', 'http://127.0.0.1:8124/put.php', null, EntityBody::factory(fopen($testFile, 'r+')), array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_READFUNCTION => 'callback',
                CURLOPT_INFILESIZE => filesize($testFile),
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                '!Expect'           => null,
                'Content-Length'   => $testFileSize,
                '!Transfer-Encoding' => null
            )),
            // Send a POST request using an array of fields
            array('POST', 'http://127.0.0.1:8124/post.php', null, array(
                'x' => 'y',
                'a' => 'b'
            ), array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => 'x=y&a=b',
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Length'   => '7',
                '!Expect'          => null,
                'Content-Type'     => 'application/x-www-form-urlencoded; charset=utf-8',
                '!Transfer-Encoding' => null
            )),
            // Send a POST request with raw POST data and a custom content-type
            array('POST', 'http://127.0.0.1:8124/post.php', array(
                'Content-Type' => 'application/json'
            ), '{"hi":"there"}', array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_UPLOAD => true,
                CURLOPT_INFILESIZE => 14,
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'Content-Type: application/json',
                    'User-Agent: ' . $userAgent
                ),
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Type'     => 'application/json',
                '!Expect'          => null,
                'Content-Length'   => '14',
                '!Transfer-Encoding' => null
            )),
            // Send a POST request with raw POST data, a custom content-type, and use chunked encoding
            array('POST', 'http://127.0.0.1:8124/post.php', array(
                'Content-Type'      => 'application/json',
                'Transfer-Encoding' => 'chunked'
            ), '{"hi":"there"}', array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_UPLOAD => true,
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'Transfer-Encoding: chunked',
                    'Content-Type: application/json',
                    'User-Agent: ' . $userAgent
                ),
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Type'     => 'application/json',
                '!Expect'          => null,
                'Transfer-Encoding' => 'chunked',
                '!Content-Length'  => ''
            )),
            // Send a POST request with no body
            array('POST', 'http://127.0.0.1:8124/post.php', null, '', array(
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Length'   => '0',
                '!Transfer-Encoding' => null
            )),
            // Send a POST request with empty post fields
            array('POST', 'http://127.0.0.1:8124/post.php', null, array(), array(
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Length'   => '0',
                '!Transfer-Encoding' => null
            )),
            // Send a PATCH request
            array('PATCH', 'http://127.0.0.1:8124/patch.php', null, 'body', array(
                CURLOPT_INFILESIZE => 4,
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'User-Agent: ' . $userAgent
                )
            )),
            // Send a DELETE request with a body
            array('DELETE', 'http://127.0.0.1:8124/delete.php', null, 'body', array(
                CURLOPT_CUSTOMREQUEST => 'DELETE',
                CURLOPT_INFILESIZE => 4,
                CURLOPT_HTTPHEADER => array (
                    'Expect:',
                    'Accept:',
                    'Host: 127.0.0.1:8124',
                    'User-Agent: ' . $userAgent
                )
            ), array(
                'Host'             => '*',
                'User-Agent'       => '*',
                'Content-Length'   => '4',
                '!Expect'            => null,
                '!Transfer-Encoding' => null
            )),

            /**
             * Send a request with empty path and a fragment - the fragment must be
             * stripped out before sending it to curl
             *
             * @issue 453
             * @link https://github.com/guzzle/guzzle/issues/453
             */
            array('GET', 'http://www.google.com#head', null, null, array(
                CURLOPT_RETURNTRANSFER => 0,
                CURLOPT_HEADER => 0,
                CURLOPT_CONNECTTIMEOUT => 150,
                CURLOPT_WRITEFUNCTION => 'callback',
                CURLOPT_HEADERFUNCTION => 'callback',
                CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent),
            )),
        );

        $postTest = array('POST', 'http://127.0.0.1:8124/post.php', null, $postBody, array(
            CURLOPT_RETURNTRANSFER => 0,
            CURLOPT_HEADER => 0,
            CURLOPT_CONNECTTIMEOUT => 150,
            CURLOPT_WRITEFUNCTION => 'callback',
            CURLOPT_HEADERFUNCTION => 'callback',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => array(
                'file' => '@' . $testFile . ';filename=phpunit.xml.dist;type=application/octet-stream'
            ),
            CURLOPT_HTTPHEADER => array (
                'Accept:',
                'Host: 127.0.0.1:8124',
                'Content-Type: multipart/form-data',
                'Expect: 100-Continue',
                'User-Agent: ' . $userAgent
            )
        ), array(
            'Host'             => '*',
            'User-Agent'       => '*',
            'Content-Length'   => '*',
            'Expect'           => '100-Continue',
            'Content-Type'     => 'multipart/form-data; boundary=*',
            '!Transfer-Encoding' => null
        ));

        if (version_compare(phpversion(), '5.5.0', '>=')) {
            $postTest[4][CURLOPT_POSTFIELDS] = array(
                'file' => new \CurlFile($testFile, 'application/octet-stream', 'phpunit.xml.dist')
            );
        }

        $tests[] = $postTest;

        return $tests;
    }

    /**
     * @dataProvider dataProvider
     */
    public function testFactoryCreatesCurlBasedOnRequest($method, $url, $headers, $body, $options, $expectedHeaders = null)
    {
        $client = new Client();
        $request = $client->createRequest($method, $url, $headers, $body);
        $request->getCurlOptions()->set('debug', true);

        $originalRequest = clone $request;
        $curlTest = clone $request;
        $handle = CurlHandle::factory($curlTest);

        $this->assertInstanceOf('Guzzle\\Http\\Curl\\CurlHandle', $handle);
        $o = $handle->getOptions()->getAll();

        // Headers are case-insensitive
        if (isset($o[CURLOPT_HTTPHEADER])) {
            $o[CURLOPT_HTTPHEADER] = array_map('strtolower', $o[CURLOPT_HTTPHEADER]);
        }
        if (isset($options[CURLOPT_HTTPHEADER])) {
            $options[CURLOPT_HTTPHEADER] = array_map('strtolower', $options[CURLOPT_HTTPHEADER]);
        }

        $check = 0;
        foreach ($options as $key => $value) {
            $check++;
            $this->assertArrayHasKey($key, $o, '-> Check number ' . $check);
            if ($key != CURLOPT_HTTPHEADER && $key != CURLOPT_POSTFIELDS && (is_array($o[$key])) || $o[$key] instanceof \Closure) {
                $this->assertEquals('callback', $value, '-> Check number ' . $check);
            } else {
                $this->assertTrue($value == $o[$key], '-> Check number ' . $check . ' - ' . var_export($value, true) . ' != ' . var_export($o[$key], true));
            }
        }

        // If we are testing the actual sent headers
        if ($expectedHeaders) {

            // Send the request to the test server
            $client = new Client($this->getServer()->getUrl());
            $request->setClient($client);
            $this->getServer()->flush();
            $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
            $request->send();

            // Get the request that was sent and create a request that we expected
            $requests = $this->getServer()->getReceivedRequests(true);
            $this->assertEquals($method, $requests[0]->getMethod());

            $test = $this->compareHeaders($expectedHeaders, $requests[0]->getHeaders());
            $this->assertFalse($test, $test . "\nSent: \n" . $request . "\n\n" . $requests[0]);

            // Ensure only one Content-Length header is sent
            if ($request->getHeader('Content-Length')) {
                $this->assertEquals((string) $request->getHeader('Content-Length'), (string) $requests[0]->getHeader('Content-Length'));
            }
        }
    }

    public function testFactoryUsesSpecifiedProtocol()
    {
        $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:8124/');
        $request->setProtocolVersion('1.1');
        $handle = CurlHandle::factory($request);
        $options = $handle->getOptions();
        $this->assertEquals(CURL_HTTP_VERSION_1_1, $options[CURLOPT_HTTP_VERSION]);
    }

    public function testUploadsPutData()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");

        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/');
        $request->getCurlOptions()->set('debug', true);
        $request->setBody(EntityBody::factory('test'), 'text/plain', false);
        $request->getCurlOptions()->set('progress', true);

        $o = $this->getWildcardObserver($request);
        $request->send();

        // Make sure that the events were dispatched
        $this->assertTrue($o->has('curl.callback.progress'));

        // Ensure that the request was received exactly as intended
        $r = $this->getServer()->getReceivedRequests(true);
        $this->assertFalse($r[0]->hasHeader('Transfer-Encoding'));
        $this->assertEquals(4, (string) $r[0]->getHeader('Content-Length'));
        $sent = strtolower($r[0]);
        $this->assertContains('put / http/1.1', $sent);
        $this->assertContains('host: 127.0.0.1', $sent);
        $this->assertContains('user-agent:', $sent);
        $this->assertContains('content-type: text/plain', $sent);
    }

    public function testUploadsPutDataUsingChunkedEncodingWhenLengthCannotBeDetermined()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"
        ));
        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/');
        $request->setBody(EntityBody::factory(fopen($this->getServer()->getUrl(), 'r')), 'text/plain');
        $request->send();

        $r = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('chunked', $r[1]->getHeader('Transfer-Encoding'));
        $this->assertFalse($r[1]->hasHeader('Content-Length'));
    }

    public function testUploadsPutDataUsingChunkedEncodingWhenForced()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");

        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/', array('Transfer-Encoding' => 'chunked'), 'hi!');
        $request->send();

        $r = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('chunked', $r[0]->getHeader('Transfer-Encoding'));
        $this->assertFalse($r[0]->hasHeader('Content-Length'));
        $this->assertEquals('hi!', $r[0]->getBody(true));
    }

    public function testSendsPostRequestsWithFields()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");

        $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl());
        $request->getCurlOptions()->set('debug', true);
        $request->setClient(new Client());
        $request->addPostFields(array(
            'a' => 'b',
            'c' => 'ay! ~This is a test, isn\'t it?'
        ));
        $request->send();

        // Make sure that the request was sent correctly
        $r = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('a=b&c=ay%21%20~This%20is%20a%20test%2C%20isn%27t%20it%3F', (string) $r[0]->getBody());
        $this->assertFalse($r[0]->hasHeader('Transfer-Encoding'));
        $this->assertEquals(56, (string) $r[0]->getHeader('Content-Length'));
        $sent = strtolower($r[0]);
        $this->assertContains('post / http/1.1', $sent);
        $this->assertContains('content-type: application/x-www-form-urlencoded; charset=utf-8', $sent);
    }

    public function testSendsPostRequestsWithFiles()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi");

        $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl());
        $request->getCurlOptions()->set('debug', true);
        $request->setClient(new Client());
        $request->addPostFiles(array(
            'foo' => __FILE__,
        ));
        $request->addPostFields(array(
            'bar' => 'baz',
            'arr' => array('a' => 1, 'b' => 2),
        ));
        $this->updateForHandle($request);
        $request->send();

        // Ensure the CURLOPT_POSTFIELDS option was set properly
        $options = $this->requestHandle->getOptions()->getAll();
        if (version_compare(phpversion(), '5.5.0', '<')) {
            $this->assertContains('@' . __FILE__ . ';filename=CurlHandleTest.php;type=text/x-', $options[CURLOPT_POSTFIELDS]['foo']);
        } else{
            $this->assertInstanceOf('CURLFile', $options[CURLOPT_POSTFIELDS]['foo']);
        }
        $this->assertEquals('baz', $options[CURLOPT_POSTFIELDS]['bar']);
        $this->assertEquals('1', $options[CURLOPT_POSTFIELDS]['arr[a]']);
        $this->assertEquals('2', $options[CURLOPT_POSTFIELDS]['arr[b]']);
        // Ensure that a Content-Length header was sent by cURL
        $this->assertTrue($request->hasHeader('Content-Length'));
    }

    public function testCurlConfigurationOptionsAreSet()
    {
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl());
        $request->setClient(new Client('http://www.example.com'));
        $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, 99);
        $request->getCurlOptions()->set('curl.fake_opt', 99);
        $request->getCurlOptions()->set(CURLOPT_PORT, 8181);
        $handle = CurlHandle::factory($request);
        $this->assertEquals(99, $handle->getOptions()->get(CURLOPT_CONNECTTIMEOUT));
        $this->assertEquals(8181, $handle->getOptions()->get(CURLOPT_PORT));
        $this->assertNull($handle->getOptions()->get('curl.fake_opt'));
        $this->assertNull($handle->getOptions()->get('fake_opt'));
    }

    public function testEnsuresRequestsHaveResponsesWhenUpdatingFromTransfer()
    {
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl());
        $handle = CurlHandle::factory($request);
        $handle->updateRequestFromTransfer($request);
    }

    public function testCanSendBodyAsString()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/', null, 'foo');
        $request->getCurlOptions()->set('body_as_string', true);
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(false);
        $this->assertContains('PUT /', $requests[0]);
        $this->assertContains("\nfoo", $requests[0]);
        $this->assertContains('content-length: 3', $requests[0]);
        $this->assertNotContains('content-type', $requests[0]);
    }

    public function testCanSendPostBodyAsString()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->post('/', null, 'foo');
        $request->getCurlOptions()->set('body_as_string', true);
        $request->send();
        $requests = $this->getServer()->getReceivedRequests(false);
        $this->assertContains('POST /', $requests[0]);
        $this->assertContains("\nfoo", $requests[0]);
        $this->assertContains('content-length: 3', $requests[0]);
        $this->assertNotContains('content-type', $requests[0]);
    }

    public function testAllowsWireTransferInfoToBeEnabled()
    {
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl());
        $request->getCurlOptions()->set('debug', true);
        $handle = CurlHandle::factory($request);
        $this->assertNotNull($handle->getOptions()->get(CURLOPT_STDERR));
        $this->assertNotNull($handle->getOptions()->get(CURLOPT_VERBOSE));
    }

    public function testAddsCustomCurlOptions()
    {
        $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl());
        $request->getCurlOptions()->set(CURLOPT_TIMEOUT, 200);
        $handle = CurlHandle::factory($request);
        $this->assertEquals(200, $handle->getOptions()->get(CURLOPT_TIMEOUT));
    }

    public function testSendsPostUploadsWithContentDispositionHeaders()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n");

        $fileToUpload = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'TestData' . DIRECTORY_SEPARATOR . 'test_service.json';

        $client = new Client($this->getServer()->getUrl());
        $request = $client->post();
        $request->addPostFile('foo', $fileToUpload, 'application/json');
        $request->addPostFile('foo', __FILE__);

        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $body = (string) $requests[0]->getBody();

        $this->assertContains('Content-Disposition: form-data; name="foo[0]"; filename="', $body);
        $this->assertContains('Content-Type: application/json', $body);
        $this->assertContains('Content-Type: text/x-', $body);
        $this->assertContains('Content-Disposition: form-data; name="foo[1]"; filename="', $body);
    }

    public function requestMethodProvider()
    {
        return array(array('POST'), array('PUT'), array('PATCH'));
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSendsRequestsWithNoBodyUsingContentLengthZero($method)
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $client->createRequest($method)->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertFalse($requests[0]->hasHeader('Transfer-Encoding'));
        $this->assertTrue($requests[0]->hasHeader('Content-Length'));
        $this->assertEquals('0', (string) $requests[0]->getHeader('Content-Length'));
    }

    /**
     * @dataProvider provideCurlConfig
     */
    public function testParseCurlConfigConvertsStringKeysToConstantKeys($options, $expected)
    {
        $actual = CurlHandle::parseCurlConfig($options);
        $this->assertEquals($expected, $actual);
    }

    /**
     * Data provider for curl configurations
     *
     * @return array
     */
    public function provideCurlConfig()
    {
        return array(
            // Conversion of option name to constant value
            array(
                array(
                    'CURLOPT_PORT' => 10,
                    'CURLOPT_TIMEOUT' => 99
                ),
                array(
                    CURLOPT_PORT => 10,
                    CURLOPT_TIMEOUT => 99
                )
            ),
            // Keeps non constant options
            array(
                array('debug' => true),
                array('debug' => true)
            ),
            // Conversion of constant names to constant values
            array(
                array('debug' => 'CURLPROXY_HTTP'),
                array('debug' => CURLPROXY_HTTP)
            )
        );
    }

    public function testSeeksToBeginningOfStreamWhenSending()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
        ));

        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/', null, 'test');
        $request->send();
        $request->send();

        $received = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals(2, count($received));
        $this->assertEquals('test', (string) $received[0]->getBody());
        $this->assertEquals('test', (string) $received[1]->getBody());
    }

    public function testAllowsCurloptEncodingToBeSet()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");

        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('/', null);
        $request->getCurlOptions()->set(CURLOPT_ENCODING, '');
        $this->updateForHandle($request);
        $request->send();
        $options = $this->requestHandle->getOptions()->getAll();
        $this->assertSame('', $options[CURLOPT_ENCODING]);
        $received = $this->getServer()->getReceivedRequests(false);
        $this->assertContainsIns('accept: */*', $received[0]);
        $this->assertContainsIns('accept-encoding: ', $received[0]);
    }

    public function testSendsExpectHeaderWhenSizeIsGreaterThanCutoff()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->put('/', null, 'test');
        // Start sending the expect header to 2 bytes
        $this->updateForHandle($request);
        $request->setExpectHeaderCutoff(2)->send();
        $options = $this->requestHandle->getOptions()->getAll();
        $this->assertContains('Expect: 100-Continue', $options[CURLOPT_HTTPHEADER]);
        $received = $this->getServer()->getReceivedRequests(false);
        $this->assertContainsIns('expect: 100-continue', $received[0]);
    }

    public function testSetsCurloptEncodingWhenAcceptEncodingHeaderIsSet()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata");
        $client = new Client($this->getServer()->getUrl());
        $request = $client->get('/', array(
            'Accept' => 'application/json',
            'Accept-Encoding' => 'gzip, deflate',
        ));
        $this->updateForHandle($request);
        $request->send();
        $options = $this->requestHandle->getOptions()->getAll();
        $this->assertSame('gzip, deflate', $options[CURLOPT_ENCODING]);
        $received = $this->getServer()->getReceivedRequests(false);
        $this->assertContainsIns('accept: application/json', $received[0]);
        $this->assertContainsIns('accept-encoding: gzip, deflate', $received[0]);
    }

    public function testSendsPostFieldsForNonPostRequests()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n");

        $client = new Client();
        $request = $client->put($this->getServer()->getUrl(), null, array(
            'foo' => 'baz',
            'baz' => 'bar'
        ));

        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('PUT', $requests[0]->getMethod());
        $this->assertEquals(
            'application/x-www-form-urlencoded; charset=utf-8',
            (string) $requests[0]->getHeader('Content-Type')
        );
        $this->assertEquals(15, (string) $requests[0]->getHeader('Content-Length'));
        $this->assertEquals('foo=baz&baz=bar', (string) $requests[0]->getBody());
    }

    public function testSendsPostFilesForNonPostRequests()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n");

        $client = new Client();
        $request = $client->put($this->getServer()->getUrl(), null, array(
            'foo' => '@' . __FILE__
        ));

        $request->send();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals('PUT', $requests[0]->getMethod());
        $this->assertContains('multipart/form-data', (string) $requests[0]->getHeader('Content-Type'));
        $this->assertContains('testSendsPostFilesForNonPostRequests', (string) $requests[0]->getBody());
    }
}
<?php

namespace Guzzle\Tests\Http\Curl;

use Guzzle\Http\Curl\CurlVersion;

/**
 * @covers Guzzle\Http\Curl\CurlVersion
 */
class CurlVersionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCachesCurlInfo()
    {
        $info = curl_version();
        $instance = CurlVersion::getInstance();

        // Clear out the info cache
        $refObject = new \ReflectionObject($instance);
        $refProperty = $refObject->getProperty('version');
        $refProperty->setAccessible(true);
        $refProperty->setValue($instance, array());

        $this->assertEquals($info, $instance->getAll());
        $this->assertEquals($info, $instance->getAll());

        $this->assertEquals($info['version'], $instance->get('version'));
        $this->assertFalse($instance->get('foo'));
    }

    public function testIsSingleton()
    {
        $refObject = new \ReflectionClass('Guzzle\Http\Curl\CurlVersion');
        $refProperty = $refObject->getProperty('instance');
        $refProperty->setAccessible(true);
        $refProperty->setValue(null, null);

        $this->assertInstanceOf('Guzzle\Http\Curl\CurlVersion', CurlVersion::getInstance());
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\QueryString;
use Guzzle\Http\Url;

/**
 * @covers Guzzle\Http\Url
 */
class UrlTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testEmptyUrl()
    {
        $url = Url::factory('');
        $this->assertEquals('', (string) $url);
    }

    public function testPortIsDeterminedFromScheme()
    {
        $this->assertEquals(80, Url::factory('http://www.test.com/')->getPort());
        $this->assertEquals(443, Url::factory('https://www.test.com/')->getPort());
        $this->assertEquals(null, Url::factory('ftp://www.test.com/')->getPort());
        $this->assertEquals(8192, Url::factory('http://www.test.com:8192/')->getPort());
    }

    public function testCloneCreatesNewInternalObjects()
    {
        $u1 = Url::factory('http://www.test.com/');
        $u2 = clone $u1;
        $this->assertNotSame($u1->getQuery(), $u2->getQuery());
    }

    public function testValidatesUrlPartsInFactory()
    {
        $url = Url::factory('/index.php');
        $this->assertEquals('/index.php', (string) $url);
        $this->assertFalse($url->isAbsolute());

        $url = 'http://michael:test@test.com:80/path/123?q=abc#test';
        $u = Url::factory($url);
        $this->assertEquals('http://michael:test@test.com/path/123?q=abc#test', (string) $u);
        $this->assertTrue($u->isAbsolute());
    }

    public function testAllowsFalsyUrlParts()
    {
        $url = Url::factory('http://0:50/0?0#0');
        $this->assertSame('0', $url->getHost());
        $this->assertEquals(50, $url->getPort());
        $this->assertSame('/0', $url->getPath());
        $this->assertEquals('0', (string) $url->getQuery());
        $this->assertSame('0', $url->getFragment());
        $this->assertEquals('http://0:50/0?0#0', (string) $url);

        $url = Url::factory('');
        $this->assertSame('', (string) $url);

        $url = Url::factory('0');
        $this->assertSame('0', (string) $url);
    }

    public function testBuildsRelativeUrlsWithFalsyParts()
    {
        $url = Url::buildUrl(array(
                'host' => '0',
                'path' => '0',
            ));

        $this->assertSame('//0/0', $url);

        $url = Url::buildUrl(array(
                'path' => '0',
            ));
        $this->assertSame('0', $url);
    }

    public function testUrlStoresParts()
    {
        $url = Url::factory('http://test:pass@www.test.com:8081/path/path2/?a=1&b=2#fragment');
        $this->assertEquals('http', $url->getScheme());
        $this->assertEquals('test', $url->getUsername());
        $this->assertEquals('pass', $url->getPassword());
        $this->assertEquals('www.test.com', $url->getHost());
        $this->assertEquals(8081, $url->getPort());
        $this->assertEquals('/path/path2/', $url->getPath());
        $this->assertEquals('fragment', $url->getFragment());
        $this->assertEquals('a=1&b=2', (string) $url->getQuery());

        $this->assertEquals(array(
            'fragment' => 'fragment',
            'host' => 'www.test.com',
            'pass' => 'pass',
            'path' => '/path/path2/',
            'port' => 8081,
            'query' => 'a=1&b=2',
            'scheme' => 'http',
            'user' => 'test'
        ), $url->getParts());
    }

    public function testHandlesPathsCorrectly()
    {
        $url = Url::factory('http://www.test.com');
        $this->assertEquals('', $url->getPath());
        $url->setPath('test');
        $this->assertEquals('test', $url->getPath());

        $url->setPath('/test/123/abc');
        $this->assertEquals(array('test', '123', 'abc'), $url->getPathSegments());

        $parts = parse_url('http://www.test.com/test');
        $parts['path'] = '';
        $this->assertEquals('http://www.test.com', Url::buildUrl($parts));
        $parts['path'] = 'test';
        $this->assertEquals('http://www.test.com/test', Url::buildUrl($parts));
    }

    public function testAddsQueryStringIfPresent()
    {
        $this->assertEquals('?foo=bar', Url::buildUrl(array(
            'query' => 'foo=bar'
        )));
    }

    public function testAddsToPath()
    {
        // Does nothing here
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(false));
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(null));
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(array()));
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(new \stdClass()));
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(''));
        $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/'));
        $this->assertEquals('http://e.com/baz/foo', (string) Url::factory('http://e.com/baz/')->addPath('foo'));
        $this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('relative'));
        $this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/relative'));
        $this->assertEquals('http://e.com/base/0', (string) Url::factory('http://e.com/base')->addPath('0'));
        $this->assertEquals('http://e.com/base/0/1', (string) Url::factory('http://e.com/base')->addPath('0')->addPath('1'));
    }

    /**
     * URL combination data provider
     *
     * @return array
     */
    public function urlCombineDataProvider()
    {
        return array(
            array('http://www.example.com/', 'http://www.example.com/', 'http://www.example.com/'),
            array('http://www.example.com/path', '/absolute', 'http://www.example.com/absolute'),
            array('http://www.example.com/path', '/absolute?q=2', 'http://www.example.com/absolute?q=2'),
            array('http://www.example.com/path', 'more', 'http://www.example.com/path/more'),
            array('http://www.example.com/path', 'more?q=1', 'http://www.example.com/path/more?q=1'),
            array('http://www.example.com/', '?q=1', 'http://www.example.com/?q=1'),
            array('http://www.example.com/path', 'http://test.com', 'http://test.com'),
            array('http://www.example.com:8080/path', 'http://test.com', 'http://test.com'),
            array('http://www.example.com:8080/path', '?q=2#abc', 'http://www.example.com:8080/path?q=2#abc'),
            array('http://u:a@www.example.com/path', 'test', 'http://u:a@www.example.com/path/test'),
            array('http://www.example.com/path', 'http://u:a@www.example.com/', 'http://u:a@www.example.com/'),
            array('/path?q=2', 'http://www.test.com/', 'http://www.test.com/path?q=2'),
            array('http://api.flickr.com/services/', 'http://www.flickr.com/services/oauth/access_token', 'http://www.flickr.com/services/oauth/access_token'),
            array('http://www.example.com/?foo=bar', 'some/path', 'http://www.example.com/some/path?foo=bar'),
            array('http://www.example.com/?foo=bar', 'some/path?boo=moo', 'http://www.example.com/some/path?boo=moo&foo=bar'),
            array('http://www.example.com/some/', 'path?foo=bar&foo=baz', 'http://www.example.com/some/path?foo=bar&foo=baz'),
        );
    }

    /**
     * @dataProvider urlCombineDataProvider
     */
    public function testCombinesUrls($a, $b, $c)
    {
        $this->assertEquals($c, (string) Url::factory($a)->combine($b));
    }

    public function testHasGettersAndSetters()
    {
        $url = Url::factory('http://www.test.com/');
        $this->assertEquals('example.com', $url->setHost('example.com')->getHost());
        $this->assertEquals('8080', $url->setPort(8080)->getPort());
        $this->assertEquals('/foo/bar', $url->setPath(array('foo', 'bar'))->getPath());
        $this->assertEquals('a', $url->setPassword('a')->getPassword());
        $this->assertEquals('b', $url->setUsername('b')->getUsername());
        $this->assertEquals('abc', $url->setFragment('abc')->getFragment());
        $this->assertEquals('https', $url->setScheme('https')->getScheme());
        $this->assertEquals('a=123', (string) $url->setQuery('a=123')->getQuery());
        $this->assertEquals('https://b:a@example.com:8080/foo/bar?a=123#abc', (string) $url);
        $this->assertEquals('b=boo', (string) $url->setQuery(new QueryString(array(
            'b' => 'boo'
        )))->getQuery());
        $this->assertEquals('https://b:a@example.com:8080/foo/bar?b=boo#abc', (string) $url);
    }

    public function testSetQueryAcceptsArray()
    {
        $url = Url::factory('http://www.test.com');
        $url->setQuery(array('a' => 'b'));
        $this->assertEquals('http://www.test.com?a=b', (string) $url);
    }

    public function urlProvider()
    {
        return array(
            array('/foo/..', '/'),
            array('//foo//..', '/'),
            array('/foo/../..', '/'),
            array('/foo/../.', '/'),
            array('/./foo/..', '/'),
            array('/./foo', '/foo'),
            array('/./foo/', '/foo/'),
            array('/./foo/bar/baz/pho/../..', '/foo/bar'),
            array('*', '*'),
            array('/foo', '/foo'),
            array('/abc/123/../foo/', '/abc/foo/'),
            array('/a/b/c/./../../g', '/a/g'),
            array('/b/c/./../../g', '/g'),
            array('/b/c/./../../g', '/g'),
            array('/c/./../../g', '/g'),
            array('/./../../g', '/g'),
        );
    }

    /**
     * @dataProvider urlProvider
     */
    public function testNormalizesPaths($path, $result)
    {
        $url = Url::factory('http://www.example.com/');
        $url->setPath($path)->normalizePath();
        $this->assertEquals($result, $url->getPath());
    }

    public function testSettingHostWithPortModifiesPort()
    {
        $url = Url::factory('http://www.example.com');
        $url->setHost('foo:8983');
        $this->assertEquals('foo', $url->getHost());
        $this->assertEquals(8983, $url->getPort());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesUrlCanBeParsed()
    {
        Url::factory('foo:////');
    }

    public function testConvertsSpecialCharsInPathWhenCastingToString()
    {
        $url = Url::factory('http://foo.com/baz bar?a=b');
        $url->addPath('?');
        $this->assertEquals('http://foo.com/baz%20bar/%3F?a=b', (string) $url);
    }

    /**
     * @link http://tools.ietf.org/html/rfc3986#section-5.4.1
     */
    public function rfc3986UrlProvider()
    {
        $result = array(
            array('g', 'http://a/b/c/g'),
            array('./g', 'http://a/b/c/g'),
            array('g/', 'http://a/b/c/g/'),
            array('/g', 'http://a/g'),
            array('?y', 'http://a/b/c/d;p?y'),
            array('g?y', 'http://a/b/c/g?y'),
            array('#s', 'http://a/b/c/d;p?q#s'),
            array('g#s', 'http://a/b/c/g#s'),
            array('g?y#s', 'http://a/b/c/g?y#s'),
            array(';x', 'http://a/b/c/;x'),
            array('g;x', 'http://a/b/c/g;x'),
            array('g;x?y#s', 'http://a/b/c/g;x?y#s'),
            array('', 'http://a/b/c/d;p?q'),
            array('.', 'http://a/b/c'),
            array('./', 'http://a/b/c/'),
            array('..', 'http://a/b'),
            array('../', 'http://a/b/'),
            array('../g', 'http://a/b/g'),
            array('../..', 'http://a/'),
            array('../../', 'http://a/'),
            array('../../g', 'http://a/g')
        );

        // This support was added in PHP 5.4.7: https://bugs.php.net/bug.php?id=62844
        if (version_compare(PHP_VERSION, '5.4.7', '>=')) {
            $result[] = array('//g', 'http://g');
        }

        return $result;
    }

    /**
     * @dataProvider rfc3986UrlProvider
     */
    public function testCombinesUrlsUsingRfc3986($relative, $result)
    {
        $a = Url::factory('http://a/b/c/d;p?q');
        $b = Url::factory($relative);
        $this->assertEquals($result, trim((string) $a->combine($b, true), '='));
    }
}
<?php

namespace Guzzle\Tests\Http\Exception;

use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Exception\RequestException;
use Guzzle\Http\Exception\BadResponseException;

class ExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @covers Guzzle\Http\Exception\RequestException
     */
    public function testRequestException()
    {
        $e = new RequestException('Message');
        $request = new Request('GET', 'http://www.guzzle-project.com/');
        $e->setRequest($request);
        $this->assertEquals($request, $e->getRequest());
    }

    /**
     * @covers Guzzle\Http\Exception\BadResponseException
     */
    public function testBadResponseException()
    {
        $e = new BadResponseException('Message');
        $response = new Response(200);
        $e->setResponse($response);
        $this->assertEquals($response, $e->getResponse());
    }

    /**
     * @covers Guzzle\Http\Exception\BadResponseException::factory
     */
    public function testCreatesGenericErrorExceptionOnError()
    {
        $request = new Request('GET', 'http://www.example.com');
        $response = new Response(307);
        $e = BadResponseException::factory($request, $response);
        $this->assertInstanceOf('Guzzle\Http\Exception\BadResponseException', $e);
    }

    /**
     * @covers Guzzle\Http\Exception\BadResponseException::factory
     */
    public function testCreatesClientErrorExceptionOnClientError()
    {
        $request = new Request('GET', 'http://www.example.com');
        $response = new Response(404);
        $e = BadResponseException::factory($request, $response);
        $this->assertInstanceOf('Guzzle\Http\Exception\ClientErrorResponseException', $e);
    }

    /**
     * @covers Guzzle\Http\Exception\BadResponseException::factory
     */
    public function testCreatesServerErrorExceptionOnServerError()
    {
        $request = new Request('GET', 'http://www.example.com');
        $response = new Response(503);
        $e = BadResponseException::factory($request, $response);
        $this->assertInstanceOf('Guzzle\Http\Exception\ServerErrorResponseException', $e);
    }
}
<?php

namespace Guzzle\Tests\Http\Exception;

use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Message\Request;

/**
 * @covers Guzzle\Http\Exception\MultiTransferException
 */
class MultiTransferExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testHasRequests()
    {
        $r1 = new Request('GET', 'http://www.foo.com');
        $r2 = new Request('GET', 'http://www.foo.com');
        $e = new MultiTransferException();
        $e->addSuccessfulRequest($r1);
        $e->addFailedRequest($r2);
        $this->assertEquals(array($r1), $e->getSuccessfulRequests());
        $this->assertEquals(array($r2), $e->getSuccessfulRequests());
        $this->assertEquals(array($r1, $r2), $e->getAllRequests());
        $this->assertTrue($e->containsRequest($r1));
        $this->assertTrue($e->containsRequest($r2));
        $this->assertFalse($e->containsRequest(new Request('POST', '/foo')));
    }

    public function testCanSetRequests()
    {
        $s = array($r1 = new Request('GET', 'http://www.foo.com'));
        $f = array($r2 = new Request('GET', 'http://www.foo.com'));
        $e = new MultiTransferException();
        $e->setSuccessfulRequests($s);
        $e->setFailedRequests($f);
        $this->assertEquals(array($r1), $e->getSuccessfulRequests());
        $this->assertEquals(array($r2), $e->getSuccessfulRequests());
    }

    public function testAssociatesExceptionsWithRequests()
    {
        $r1 = new Request('GET', 'http://www.foo.com');
        $re1 = new \Exception('foo');
        $re2 = new \Exception('bar');
        $e = new MultiTransferException();
        $e->add($re2);
        $e->addFailedRequestWithException($r1, $re1);
        $this->assertSame($re1, $e->getExceptionForFailedRequest($r1));
        $this->assertNull($e->getExceptionForFailedRequest(new Request('POST', '/foo')));
    }
}
<?php

namespace Guzzle\Tests\Http\Exception;

use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Curl\CurlHandle;

/**
 * @covers Guzzle\Http\Exception\CurlException
 */
class CurlExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testStoresCurlError()
    {
        $e = new CurlException();
        $this->assertNull($e->getError());
        $this->assertNull($e->getErrorNo());
        $this->assertSame($e, $e->setError('test', 12));
        $this->assertEquals('test', $e->getError());
        $this->assertEquals(12, $e->getErrorNo());

        $handle = new CurlHandle(curl_init(), array());
        $e->setCurlHandle($handle);
        $this->assertSame($handle, $e->getCurlHandle());
        $handle->close();
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Http\EntityBody;

/**
 * @covers Guzzle\Http\AbstractEntityBodyDecorator
 */
class AbstractEntityBodyDecoratorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDecoratesEntityBody()
    {
        $e = EntityBody::factory();
        $mock = $this->getMockForAbstractClass('Guzzle\Http\AbstractEntityBodyDecorator', array($e));

        $this->assertSame($e->getStream(), $mock->getStream());
        $this->assertSame($e->getContentLength(), $mock->getContentLength());
        $this->assertSame($e->getSize(), $mock->getSize());
        $this->assertSame($e->getContentMd5(), $mock->getContentMd5());
        $this->assertSame($e->getContentType(), $mock->getContentType());
        $this->assertSame($e->__toString(), $mock->__toString());
        $this->assertSame($e->getUri(), $mock->getUri());
        $this->assertSame($e->getStreamType(), $mock->getStreamType());
        $this->assertSame($e->getWrapper(), $mock->getWrapper());
        $this->assertSame($e->getWrapperData(), $mock->getWrapperData());
        $this->assertSame($e->isReadable(), $mock->isReadable());
        $this->assertSame($e->isWritable(), $mock->isWritable());
        $this->assertSame($e->isConsumed(), $mock->isConsumed());
        $this->assertSame($e->isLocal(), $mock->isLocal());
        $this->assertSame($e->isSeekable(), $mock->isSeekable());
        $this->assertSame($e->getContentEncoding(), $mock->getContentEncoding());
    }
}
<?php

namespace Guzzle\Tests\Http;

use Guzzle\Common\Collection;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Parser\UriTemplate\UriTemplate;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\Curl\CurlMulti;
use Guzzle\Http\Client;
use Guzzle\Common\Version;

/**
 * @group server
 * @covers Guzzle\Http\Client
 */
class ClientTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @return LogPlugin
     */
    private function getLogPlugin()
    {
        return new LogPlugin(new ClosureLogAdapter(
            function($message, $priority, $extras = null) {
                echo $message . ' ' . $priority . ' ' . implode(' - ', (array) $extras) . "\n";
            }
        ));
    }

    public function testAcceptsConfig()
    {
        $client = new Client('http://www.google.com/');
        $this->assertEquals('http://www.google.com/', $client->getBaseUrl());
        $this->assertSame($client, $client->setConfig(array(
            'test' => '123'
        )));
        $this->assertEquals(array('test' => '123'), $client->getConfig()->getAll());
        $this->assertEquals('123', $client->getConfig('test'));
        $this->assertSame($client, $client->setBaseUrl('http://www.test.com/{test}'));
        $this->assertEquals('http://www.test.com/123', $client->getBaseUrl());
        $this->assertEquals('http://www.test.com/{test}', $client->getBaseUrl(false));

        try {
            $client->setConfig(false);
        } catch (\InvalidArgumentException $e) {
        }
    }

    public function testDescribesEvents()
    {
        $this->assertEquals(array('client.create_request'), Client::getAllEvents());
    }

    public function testConstructorCanAcceptConfig()
    {
        $client = new Client('http://www.test.com/', array(
            'data' => '123'
        ));
        $this->assertEquals('123', $client->getConfig('data'));
    }

    public function testCanUseCollectionAsConfig()
    {
        $client = new Client('http://www.google.com/');
        $client->setConfig(new Collection(array(
            'api' => 'v1',
            'key' => 'value',
            'base_url' => 'http://www.google.com/'
        )));
        $this->assertEquals('v1', $client->getConfig('api'));
    }

    public function testExpandsUriTemplatesUsingConfig()
    {
        $client = new Client('http://www.google.com/');
        $client->setConfig(array('api' => 'v1', 'key' => 'value', 'foo' => 'bar'));
        $ref = new \ReflectionMethod($client, 'expandTemplate');
        $ref->setAccessible(true);
        $this->assertEquals('Testing...api/v1/key/value', $ref->invoke($client, 'Testing...api/{api}/key/{key}'));
    }

    public function testClientAttachersObserversToRequests()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");

        $client = new Client($this->getServer()->getUrl());
        $logPlugin = $this->getLogPlugin();
        $client->getEventDispatcher()->addSubscriber($logPlugin);

        // Get a request from the client and ensure the the observer was
        // attached to the new request
        $request = $client->createRequest();
        $this->assertTrue($this->hasSubscriber($request, $logPlugin));
    }

    public function testClientReturnsValidBaseUrls()
    {
        $client = new Client('http://www.{foo}.{data}/', array(
            'data' => '123',
            'foo' => 'bar'
        ));
        $this->assertEquals('http://www.bar.123/', $client->getBaseUrl());
        $client->setBaseUrl('http://www.google.com/');
        $this->assertEquals('http://www.google.com/', $client->getBaseUrl());
    }

    public function testClientAddsCurlOptionsToRequests()
    {
        $client = new Client('http://www.test.com/', array(
            'api' => 'v1',
            // Adds the option using the curl values
            'curl.options' => array(
                'CURLOPT_HTTPAUTH'     => 'CURLAUTH_DIGEST',
                'abc'                  => 'foo',
                'blacklist'            => 'abc',
                'debug'                => true
            )
        ));

        $request = $client->createRequest();
        $options = $request->getCurlOptions();
        $this->assertEquals(CURLAUTH_DIGEST, $options->get(CURLOPT_HTTPAUTH));
        $this->assertEquals('foo', $options->get('abc'));
        $this->assertEquals('abc', $options->get('blacklist'));
    }

    public function testClientAllowsFineGrainedSslControlButIsSecureByDefault()
    {
        $client = new Client('https://www.secure.com/');

        // secure by default
        $request = $client->createRequest();
        $options = $request->getCurlOptions();
        $this->assertTrue($options->get(CURLOPT_SSL_VERIFYPEER));

        // set a capath if you prefer
        $client = new Client('https://www.secure.com/');
        $client->setSslVerification(__DIR__);
        $request = $client->createRequest();
        $options = $request->getCurlOptions();
        $this->assertSame(__DIR__, $options->get(CURLOPT_CAPATH));
    }

    public function testConfigSettingsControlSslConfiguration()
    {
        // Use the default ca certs on the system
        $client = new Client('https://www.secure.com/', array('ssl.certificate_authority' => 'system'));
        $this->assertNull($client->getConfig('curl.options'));
        // Can set the cacert value as well
        $client = new Client('https://www.secure.com/', array('ssl.certificate_authority' => false));
        $options = $client->getConfig('curl.options');
        $this->assertArrayNotHasKey(CURLOPT_CAINFO, $options);
        $this->assertSame(false, $options[CURLOPT_SSL_VERIFYPEER]);
        $this->assertSame(0, $options[CURLOPT_SSL_VERIFYHOST]);
    }

    public function testClientAllowsUnsafeOperationIfRequested()
    {
        // be really unsafe if you insist
        $client = new Client('https://www.secure.com/', array(
            'api' => 'v1'
        ));

        $client->setSslVerification(false);
        $request = $client->createRequest();
        $options = $request->getCurlOptions();
        $this->assertFalse($options->get(CURLOPT_SSL_VERIFYPEER));
        $this->assertNull($options->get(CURLOPT_CAINFO));
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     */
    public function testThrowsExceptionForInvalidCertificate()
    {
        $client = new Client('https://www.secure.com/');
        $client->setSslVerification('/path/to/missing/file');
    }

    public function testClientAllowsSettingSpecificSslCaInfo()
    {
        // set a file other than the provided cacert.pem
        $client = new Client('https://www.secure.com/', array(
            'api' => 'v1'
        ));

        $client->setSslVerification(__FILE__);
        $request = $client->createRequest();
        $options = $request->getCurlOptions();
        $this->assertSame(__FILE__, $options->get(CURLOPT_CAINFO));
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testClientPreventsInadvertentInsecureVerifyHostSetting()
    {
        // set a file other than the provided cacert.pem
        $client = new Client('https://www.secure.com/', array(
            'api' => 'v1'
        ));
        $client->setSslVerification(__FILE__, true, true);
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testClientPreventsInvalidVerifyPeerSetting()
    {
        // set a file other than the provided cacert.pem
        $client = new Client('https://www.secure.com/', array(
            'api' => 'v1'
        ));
        $client->setSslVerification(__FILE__, 'yes');
    }

    public function testClientAddsParamsToRequests()
    {
        Version::$emitWarnings = false;
        $client = new Client('http://www.example.com', array(
            'api' => 'v1',
            'request.params' => array(
                'foo' => 'bar',
                'baz' => 'jar'
            )
        ));
        $request = $client->createRequest();
        $this->assertEquals('bar', $request->getParams()->get('foo'));
        $this->assertEquals('jar', $request->getParams()->get('baz'));
        Version::$emitWarnings = true;
    }

    public function urlProvider()
    {
        $u = $this->getServer()->getUrl() . 'base/';
        $u2 = $this->getServer()->getUrl() . 'base?z=1';
        return array(
            array($u, '', $u),
            array($u, 'relative/path/to/resource', $u . 'relative/path/to/resource'),
            array($u, 'relative/path/to/resource?a=b&c=d', $u . 'relative/path/to/resource?a=b&c=d'),
            array($u, '/absolute/path/to/resource', $this->getServer()->getUrl() . 'absolute/path/to/resource'),
            array($u, '/absolute/path/to/resource?a=b&c=d', $this->getServer()->getUrl() . 'absolute/path/to/resource?a=b&c=d'),
            array($u2, '/absolute/path/to/resource?a=b&c=d', $this->getServer()->getUrl()  . 'absolute/path/to/resource?a=b&c=d&z=1'),
            array($u2, 'relative/path/to/resource', $this->getServer()->getUrl() . 'base/relative/path/to/resource?z=1'),
            array($u2, 'relative/path/to/resource?another=query', $this->getServer()->getUrl() . 'base/relative/path/to/resource?another=query&z=1')
        );
    }

    /**
     * @dataProvider urlProvider
     */
    public function testBuildsRelativeUrls($baseUrl, $url, $result)
    {
        $client = new Client($baseUrl);
        $this->assertEquals($result, $client->get($url)->getUrl());
    }

    public function testAllowsConfigsToBeChangedAndInjectedInBaseUrl()
    {
        $client = new Client('http://{a}/{b}');
        $this->assertEquals('http:///', $client->getBaseUrl());
        $this->assertEquals('http://{a}/{b}', $client->getBaseUrl(false));
        $client->setConfig(array(
            'a' => 'test.com',
            'b' => 'index.html'
        ));
        $this->assertEquals('http://test.com/index.html', $client->getBaseUrl());
    }

    public function testCreatesRequestsWithDefaultValues()
    {
        $client = new Client($this->getServer()->getUrl() . 'base');

        // Create a GET request
        $request = $client->createRequest();
        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals($client->getBaseUrl(), $request->getUrl());

        // Create a DELETE request
        $request = $client->createRequest('DELETE');
        $this->assertEquals('DELETE', $request->getMethod());
        $this->assertEquals($client->getBaseUrl(), $request->getUrl());

        // Create a HEAD request with custom headers
        $request = $client->createRequest('HEAD', 'http://www.test.com/');
        $this->assertEquals('HEAD', $request->getMethod());
        $this->assertEquals('http://www.test.com/', $request->getUrl());

        // Create a PUT request
        $request = $client->createRequest('PUT');
        $this->assertEquals('PUT', $request->getMethod());

        // Create a PUT request with injected config
        $client->getConfig()->set('a', 1)->set('b', 2);
        $request = $client->createRequest('PUT', '/path/{a}?q={b}');
        $this->assertEquals($request->getUrl(), $this->getServer()->getUrl() . 'path/1?q=2');
    }

    public function testClientHasHelperMethodsForCreatingRequests()
    {
        $url = $this->getServer()->getUrl();
        $client = new Client($url . 'base');
        $this->assertEquals('GET', $client->get()->getMethod());
        $this->assertEquals('PUT', $client->put()->getMethod());
        $this->assertEquals('POST', $client->post()->getMethod());
        $this->assertEquals('HEAD', $client->head()->getMethod());
        $this->assertEquals('DELETE', $client->delete()->getMethod());
        $this->assertEquals('OPTIONS', $client->options()->getMethod());
        $this->assertEquals('PATCH', $client->patch()->getMethod());
        $this->assertEquals($url . 'base/abc', $client->get('abc')->getUrl());
        $this->assertEquals($url . 'zxy', $client->put('/zxy')->getUrl());
        $this->assertEquals($url . 'zxy?a=b', $client->post('/zxy?a=b')->getUrl());
        $this->assertEquals($url . 'base?a=b', $client->head('?a=b')->getUrl());
        $this->assertEquals($url . 'base?a=b', $client->delete('/base?a=b')->getUrl());
    }

    public function testClientInjectsConfigsIntoUrls()
    {
        $client = new Client('http://www.test.com/api/v1', array(
            'test' => '123'
        ));
        $request = $client->get('relative/{test}');
        $this->assertEquals('http://www.test.com/api/v1/relative/123', $request->getUrl());
    }

    public function testAllowsEmptyBaseUrl()
    {
        $client = new Client();
        $request = $client->get('http://www.google.com/');
        $this->assertEquals('http://www.google.com/', $request->getUrl());
        $request->setResponse(new Response(200), true);
        $request->send();
    }

    public function testAllowsCustomCurlMultiObjects()
    {
        $mock = $this->getMock('Guzzle\\Http\\Curl\\CurlMulti', array('add', 'send'));
        $mock->expects($this->once())
            ->method('add')
            ->will($this->returnSelf());
        $mock->expects($this->once())
            ->method('send')
            ->will($this->returnSelf());

        $client = new Client();
        $client->setCurlMulti($mock);

        $request = $client->get();
        $request->setResponse(new Response(200), true);
        $client->send($request);
    }

    public function testClientSendsMultipleRequests()
    {
        $client = new Client($this->getServer()->getUrl());
        $mock = new MockPlugin();

        $responses = array(
            new Response(200),
            new Response(201),
            new Response(202)
        );

        $mock->addResponse($responses[0]);
        $mock->addResponse($responses[1]);
        $mock->addResponse($responses[2]);

        $client->getEventDispatcher()->addSubscriber($mock);

        $requests = array(
            $client->get(),
            $client->head(),
            $client->put('/', null, 'test')
        );

        $this->assertEquals(array(
            $responses[0],
            $responses[1],
            $responses[2]
        ), $client->send($requests));
    }

    public function testClientSendsSingleRequest()
    {
        $client = new Client($this->getServer()->getUrl());
        $mock = new MockPlugin();
        $response = new Response(200);
        $mock->addResponse($response);
        $client->getEventDispatcher()->addSubscriber($mock);
        $this->assertEquals($response, $client->send($client->get()));
    }

    /**
     * @expectedException \Guzzle\Http\Exception\BadResponseException
     */
    public function testClientThrowsExceptionForSingleRequest()
    {
        $client = new Client($this->getServer()->getUrl());
        $mock = new MockPlugin();
        $response = new Response(404);
        $mock->addResponse($response);
        $client->getEventDispatcher()->addSubscriber($mock);
        $client->send($client->get());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\ExceptionCollection
     */
    public function testClientThrowsExceptionForMultipleRequests()
    {
        $client = new Client($this->getServer()->getUrl());
        $mock = new MockPlugin();
        $mock->addResponse(new Response(200));
        $mock->addResponse(new Response(404));
        $client->getEventDispatcher()->addSubscriber($mock);
        $client->send(array($client->get(), $client->head()));
    }

    public function testQueryStringsAreNotDoubleEncoded()
    {
        $client = new Client('http://test.com', array(
            'path'  => array('foo', 'bar'),
            'query' => 'hi there',
            'data'  => array(
                'test' => 'a&b'
            )
        ));

        $request = $client->get('{/path*}{?query,data*}');
        $this->assertEquals('http://test.com/foo/bar?query=hi%20there&test=a%26b', $request->getUrl());
        $this->assertEquals('hi there', $request->getQuery()->get('query'));
        $this->assertEquals('a&b', $request->getQuery()->get('test'));
    }

    public function testQueryStringsAreNotDoubleEncodedUsingAbsolutePaths()
    {
        $client = new Client('http://test.com', array(
            'path'  => array('foo', 'bar'),
            'query' => 'hi there',
        ));
        $request = $client->get('http://test.com{?query}');
        $this->assertEquals('http://test.com?query=hi%20there', $request->getUrl());
        $this->assertEquals('hi there', $request->getQuery()->get('query'));
    }

    public function testAllowsUriTemplateInjection()
    {
        $client = new Client('http://test.com');
        $ref = new \ReflectionMethod($client, 'getUriTemplate');
        $ref->setAccessible(true);
        $a = $ref->invoke($client);
        $this->assertSame($a, $ref->invoke($client));
        $client->setUriTemplate(new UriTemplate());
        $this->assertNotSame($a, $ref->invoke($client));
    }

    public function testAllowsCustomVariablesWhenExpandingTemplates()
    {
        $client = new Client('http://test.com', array('test' => 'hi'));
        $ref = new \ReflectionMethod($client, 'expandTemplate');
        $ref->setAccessible(true);
        $uri = $ref->invoke($client, 'http://{test}{?query*}', array('query' => array('han' => 'solo')));
        $this->assertEquals('http://hi?han=solo', $uri);
    }

    public function testUriArrayAllowsCustomTemplateVariables()
    {
        $client = new Client();
        $vars = array(
            'var' => 'hi'
        );
        $this->assertEquals('/hi', (string) $client->createRequest('GET', array('/{var}', $vars))->getUrl());
        $this->assertEquals('/hi', (string) $client->get(array('/{var}', $vars))->getUrl());
        $this->assertEquals('/hi', (string) $client->put(array('/{var}', $vars))->getUrl());
        $this->assertEquals('/hi', (string) $client->post(array('/{var}', $vars))->getUrl());
        $this->assertEquals('/hi', (string) $client->head(array('/{var}', $vars))->getUrl());
        $this->assertEquals('/hi', (string) $client->options(array('/{var}', $vars))->getUrl());
    }

    public function testAllowsDefaultHeaders()
    {
        Version::$emitWarnings = false;
        $default = array('X-Test' => 'Hi!');
        $other = array('X-Other' => 'Foo');

        $client = new Client();
        $client->setDefaultHeaders($default);
        $this->assertEquals($default, $client->getDefaultHeaders()->getAll());
        $client->setDefaultHeaders(new Collection($default));
        $this->assertEquals($default, $client->getDefaultHeaders()->getAll());

        $request = $client->createRequest('GET', null, $other);
        $this->assertEquals('Hi!', $request->getHeader('X-Test'));
        $this->assertEquals('Foo', $request->getHeader('X-Other'));

        $request = $client->createRequest('GET', null, new Collection($other));
        $this->assertEquals('Hi!', $request->getHeader('X-Test'));
        $this->assertEquals('Foo', $request->getHeader('X-Other'));

        $request = $client->createRequest('GET');
        $this->assertEquals('Hi!', $request->getHeader('X-Test'));
        Version::$emitWarnings = true;
    }

    public function testDontReuseCurlMulti()
    {
        $client1 = new Client();
        $client2 = new Client();
        $this->assertNotSame($client1->getCurlMulti(), $client2->getCurlMulti());
    }

    public function testGetDefaultUserAgent()
    {
        $client = new Client();
        $agent = $this->readAttribute($client, 'userAgent');
        $version = curl_version();
        $testAgent = sprintf('Guzzle/%s curl/%s PHP/%s', Version::VERSION, $version['version'], PHP_VERSION);
        $this->assertEquals($agent, $testAgent);

        $client->setUserAgent('foo');
        $this->assertEquals('foo', $this->readAttribute($client, 'userAgent'));
    }

    public function testOverwritesUserAgent()
    {
        $client = new Client();
        $request = $client->createRequest('GET', 'http://www.foo.com', array('User-agent' => 'foo'));
        $this->assertEquals('foo', (string) $request->getHeader('User-Agent'));
    }

    public function testUsesDefaultUserAgent()
    {
        $client = new Client();
        $request = $client->createRequest('GET', 'http://www.foo.com');
        $this->assertContains('Guzzle/', (string) $request->getHeader('User-Agent'));
    }

    public function testCanSetDefaultRequestOptions()
    {
        $client = new Client();
        $client->getConfig()->set('request.options', array(
            'query' => array('test' => '123', 'other' => 'abc'),
            'headers' => array('Foo' => 'Bar', 'Baz' => 'Bam')
        ));
        $request = $client->createRequest('GET', 'http://www.foo.com?test=hello', array('Foo' => 'Test'));
        // Explicit options on a request should overrule default options
        $this->assertEquals('Test', (string) $request->getHeader('Foo'));
        $this->assertEquals('hello', $request->getQuery()->get('test'));
        // Default options should still be set
        $this->assertEquals('abc', $request->getQuery()->get('other'));
        $this->assertEquals('Bam', (string) $request->getHeader('Baz'));
    }

    public function testCanSetSetOptionsOnRequests()
    {
        $client = new Client();
        $request = $client->createRequest('GET', 'http://www.foo.com?test=hello', array('Foo' => 'Test'), null, array(
            'cookies' => array('michael' => 'test')
        ));
        $this->assertEquals('test', $request->getCookie('michael'));
    }

    public function testHasDefaultOptionsHelperMethods()
    {
        $client = new Client();
        // With path
        $client->setDefaultOption('headers/foo', 'bar');
        $this->assertEquals('bar', $client->getDefaultOption('headers/foo'));
        // With simple key
        $client->setDefaultOption('allow_redirects', false);
        $this->assertFalse($client->getDefaultOption('allow_redirects'));

        $this->assertEquals(array(
            'headers' => array('foo' => 'bar'),
            'allow_redirects' => false
        ), $client->getConfig('request.options'));

        $request = $client->get('/');
        $this->assertEquals('bar', $request->getHeader('foo'));
    }

    public function testHeadCanUseOptions()
    {
        $client = new Client();
        $head = $client->head('http://www.foo.com', array(), array('query' => array('foo' => 'bar')));
        $this->assertEquals('bar', $head->getQuery()->get('foo'));
    }

    public function testCanSetRelativeUrlStartingWithHttp()
    {
        $client = new Client('http://www.foo.com');
        $this->assertEquals(
            'http://www.foo.com/httpfoo',
            $client->createRequest('GET', 'httpfoo')->getUrl()
        );
    }
}
<?php

namespace Guzzle\Tests\Plugin\Redirect;

use Guzzle\Http\Client;
use Guzzle\Http\StaticClient;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\Message\Response;
use Guzzle\Stream\Stream;

/**
 * @covers Guzzle\Http\StaticClient
 */
class StaticClientTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testMountsClient()
    {
        $client = new Client();
        StaticClient::mount('FooBazBar', $client);
        $this->assertTrue(class_exists('FooBazBar'));
        $this->assertSame($client, $this->readAttribute('Guzzle\Http\StaticClient', 'client'));
    }

    public function requestProvider()
    {
        return array_map(
            function ($m) { return array($m); },
            array('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS')
        );
    }

    /**
     * @dataProvider requestProvider
     */
    public function testSendsRequests($method)
    {
        $mock = new MockPlugin(array(new Response(200)));
        call_user_func('Guzzle\Http\StaticClient::' . $method, 'http://foo.com', array(
            'plugins' => array($mock)
        ));
        $requests = $mock->getReceivedRequests();
        $this->assertCount(1, $requests);
        $this->assertEquals($method, $requests[0]->getMethod());
    }

    public function testCanCreateStreamsUsingDefaultFactory()
    {
        $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"));
        $stream = StaticClient::get($this->getServer()->getUrl(), array('stream' => true));
        $this->assertInstanceOf('Guzzle\Stream\StreamInterface', $stream);
        $this->assertEquals('test', (string) $stream);
    }

    public function testCanCreateStreamsUsingCustomFactory()
    {
        $stream = $this->getMockBuilder('Guzzle\Stream\StreamRequestFactoryInterface')
            ->setMethods(array('fromRequest'))
            ->getMockForAbstractClass();
        $resource = new Stream(fopen('php://temp', 'r+'));
        $stream->expects($this->once())
            ->method('fromRequest')
            ->will($this->returnValue($resource));
        $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"));
        $result = StaticClient::get($this->getServer()->getUrl(), array('stream' => $stream));
        $this->assertSame($resource, $result);
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\NotifyingBatch;
use Guzzle\Batch\Batch;

/**
 * @covers Guzzle\Batch\NotifyingBatch
 */
class NotifyingBatchTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testNotifiesAfterFlush()
    {
        $batch = $this->getMock('Guzzle\Batch\Batch', array('flush'), array(
            $this->getMock('Guzzle\Batch\BatchTransferInterface'),
            $this->getMock('Guzzle\Batch\BatchDivisorInterface')
        ));

        $batch->expects($this->once())
            ->method('flush')
            ->will($this->returnValue(array('foo', 'baz')));

        $data = array();
        $decorator = new NotifyingBatch($batch, function ($batch) use (&$data) {
            $data[] = $batch;
        });

        $decorator->add('foo')->add('baz');
        $decorator->flush();
        $this->assertEquals(array(array('foo', 'baz')), $data);
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresCallableIsValid()
    {
        $batch = new Batch(
            $this->getMock('Guzzle\Batch\BatchTransferInterface'),
            $this->getMock('Guzzle\Batch\BatchDivisorInterface')
        );
        $decorator = new NotifyingBatch($batch, 'foo');
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchSizeDivisor;

/**
 * @covers Guzzle\Batch\BatchSizeDivisor
 */
class BatchSizeDivisorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDividesBatch()
    {
        $queue = new \SplQueue();
        $queue[] = 'foo';
        $queue[] = 'baz';
        $queue[] = 'bar';
        $d = new BatchSizeDivisor(3);
        $this->assertEquals(3, $d->getSize());
        $d->setSize(2);
        $batches = $d->createBatches($queue);
        $this->assertEquals(array(array('foo', 'baz'), array('bar')), $batches);
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\HistoryBatch;
use Guzzle\Batch\Batch;

/**
 * @covers Guzzle\Batch\HistoryBatch
 */
class HistoryBatchTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testMaintainsHistoryOfItemsAddedToBatch()
    {
        $batch = new Batch(
            $this->getMock('Guzzle\Batch\BatchTransferInterface'),
            $this->getMock('Guzzle\Batch\BatchDivisorInterface')
        );

        $history = new HistoryBatch($batch);
        $history->add('foo')->add('baz');
        $this->assertEquals(array('foo', 'baz'), $history->getHistory());
        $history->clearHistory();
        $this->assertEquals(array(), $history->getHistory());
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchBuilder;

/**
 * @covers Guzzle\Batch\BatchBuilder
 */
class BatchBuilderTest extends \Guzzle\Tests\GuzzleTestCase
{
    private function getMockTransfer()
    {
        return $this->getMock('Guzzle\Batch\BatchTransferInterface');
    }

    private function getMockDivisor()
    {
        return $this->getMock('Guzzle\Batch\BatchDivisorInterface');
    }

    private function getMockBatchBuilder()
    {
        return BatchBuilder::factory()
            ->transferWith($this->getMockTransfer())
            ->createBatchesWith($this->getMockDivisor());
    }

    public function testFactoryCreatesInstance()
    {
        $builder = BatchBuilder::factory();
        $this->assertInstanceOf('Guzzle\Batch\BatchBuilder', $builder);
    }

    public function testAddsAutoFlush()
    {
        $batch = $this->getMockBatchBuilder()->autoFlushAt(10)->build();
        $this->assertInstanceOf('Guzzle\Batch\FlushingBatch', $batch);
    }

    public function testAddsExceptionBuffering()
    {
        $batch = $this->getMockBatchBuilder()->bufferExceptions()->build();
        $this->assertInstanceOf('Guzzle\Batch\ExceptionBufferingBatch', $batch);
    }

    public function testAddHistory()
    {
        $batch = $this->getMockBatchBuilder()->keepHistory()->build();
        $this->assertInstanceOf('Guzzle\Batch\HistoryBatch', $batch);
    }

    public function testAddsNotify()
    {
        $batch = $this->getMockBatchBuilder()->notify(function() {})->build();
        $this->assertInstanceOf('Guzzle\Batch\NotifyingBatch', $batch);
    }

    /**
     * @expectedException Guzzle\Common\Exception\RuntimeException
     */
    public function testTransferStrategyMustBeSet()
    {
        $batch = BatchBuilder::factory()->createBatchesWith($this->getMockDivisor())->build();
    }

    /**
     * @expectedException Guzzle\Common\Exception\RuntimeException
     */
    public function testDivisorStrategyMustBeSet()
    {
        $batch = BatchBuilder::factory()->transferWith($this->getMockTransfer())->build();
    }

    public function testTransfersRequests()
    {
        $batch = BatchBuilder::factory()->transferRequests(10)->build();
        $this->assertInstanceOf('Guzzle\Batch\BatchRequestTransfer', $this->readAttribute($batch, 'transferStrategy'));
    }

    public function testTransfersCommands()
    {
        $batch = BatchBuilder::factory()->transferCommands(10)->build();
        $this->assertInstanceOf('Guzzle\Batch\BatchCommandTransfer', $this->readAttribute($batch, 'transferStrategy'));
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\FlushingBatch;
use Guzzle\Batch\Batch;

/**
 * @covers Guzzle\Batch\FlushingBatch
 */
class FlushingBatchTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testFlushesWhenSizeMeetsThreshold()
    {
        $t = $this->getMock('Guzzle\Batch\BatchTransferInterface', array('transfer'));
        $d = $this->getMock('Guzzle\Batch\BatchDivisorInterface', array('createBatches'));

        $batch = new Batch($t, $d);
        $queue = $this->readAttribute($batch, 'queue');

        $d->expects($this->exactly(2))
            ->method('createBatches')
            ->will($this->returnCallback(function () use ($queue) {
                $items = array();
                foreach ($queue as $item) {
                    $items[] = $item;
                }
                return array($items);
            }));

        $t->expects($this->exactly(2))
            ->method('transfer');

        $flush = new FlushingBatch($batch, 3);
        $this->assertEquals(3, $flush->getThreshold());
        $flush->setThreshold(2);
        $flush->add('foo')->add('baz')->add('bar')->add('bee')->add('boo');
        $this->assertEquals(1, count($flush));
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchRequestTransfer;
use Guzzle\Http\Client;
use Guzzle\Http\Curl\CurlMulti;

/**
 * @covers Guzzle\Batch\BatchRequestTransfer
 */
class BatchRequestTransferTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCreatesBatchesBasedOnCurlMultiHandles()
    {
        $client1 = new Client('http://www.example.com');
        $client1->setCurlMulti(new CurlMulti());

        $client2 = new Client('http://www.example.com');
        $client2->setCurlMulti(new CurlMulti());

        $request1 = $client1->get();
        $request2 = $client2->get();
        $request3 = $client1->get();
        $request4 = $client2->get();
        $request5 = $client1->get();

        $queue = new \SplQueue();
        $queue[] = $request1;
        $queue[] = $request2;
        $queue[] = $request3;
        $queue[] = $request4;
        $queue[] = $request5;

        $batch = new BatchRequestTransfer(2);
        $this->assertEquals(array(
            array($request1, $request3),
            array($request3),
            array($request2, $request4)
        ), $batch->createBatches($queue));
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresAllItemsAreRequests()
    {
        $queue = new \SplQueue();
        $queue[] = 'foo';
        $batch = new BatchRequestTransfer(2);
        $batch->createBatches($queue);
    }

    public function testTransfersBatches()
    {
        $client = new Client('http://127.0.0.1:123');
        $request = $client->get();
        // For some reason... PHP unit clones the request, which emits a request.clone event. This causes the
        // 'sorted' property of the event dispatcher to contain an array in the cloned request that is not present in
        // the original.
        $request->dispatch('request.clone');

        $multi = $this->getMock('Guzzle\Http\Curl\CurlMultiInterface');
        $client->setCurlMulti($multi);
        $multi->expects($this->once())
            ->method('add')
            ->with($request);
        $multi->expects($this->once())
            ->method('send');

        $batch = new BatchRequestTransfer(2);
        $batch->transfer(array($request));
    }

    public function testDoesNotTransfersEmptyBatches()
    {
        $batch = new BatchRequestTransfer(2);
        $batch->transfer(array());
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchClosureDivisor;

/**
 * @covers Guzzle\Batch\BatchClosureDivisor
 */
class BatchClosureDivisorTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresCallableIsCallable()
    {
        $d = new BatchClosureDivisor(new \stdClass());
    }

    public function testDividesBatch()
    {
        $queue = new \SplQueue();
        $queue[] = 'foo';
        $queue[] = 'baz';

        $d = new BatchClosureDivisor(function (\SplQueue $queue, $context) {
            return array(
                array('foo'),
                array('baz')
            );
        }, 'Bar!');

        $batches = $d->createBatches($queue);
        $this->assertEquals(array(array('foo'), array('baz')), $batches);
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchCommandTransfer;
use Guzzle\Service\Client;
use Guzzle\Tests\Service\Mock\Command\MockCommand as Mc;

/**
 * @covers Guzzle\Batch\BatchCommandTransfer
 */
class BatchCommandTransferTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCreatesBatchesBasedOnClient()
    {
        $client1 = new Client('http://www.example.com');
        $client2 = new Client('http://www.example.com');

        $commands = array(new Mc(), new Mc(), new Mc(), new Mc(), new Mc());

        $queue = new \SplQueue();
        foreach ($commands as $i => $command) {
            if ($i % 2) {
                $command->setClient($client1);
            } else {
                $command->setClient($client2);
            }
            $queue[] = $command;
        }

        $batch = new BatchCommandTransfer(2);
        $this->assertEquals(array(
            array($commands[0], $commands[2]),
            array($commands[4]),
            array($commands[1], $commands[3])
        ), $batch->createBatches($queue));
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresAllItemsAreCommands()
    {
        $queue = new \SplQueue();
        $queue[] = 'foo';
        $batch = new BatchCommandTransfer(2);
        $batch->createBatches($queue);
    }

    public function testTransfersBatches()
    {
        $client = $this->getMockBuilder('Guzzle\Service\Client')
            ->setMethods(array('send'))
            ->getMock();
        $client->expects($this->once())
            ->method('send');
        $command = new Mc();
        $command->setClient($client);
        $batch = new BatchCommandTransfer(2);
        $batch->transfer(array($command));
    }

    public function testDoesNotTransfersEmptyBatches()
    {
        $batch = new BatchCommandTransfer(2);
        $batch->transfer(array());
    }

    /**
     * @expectedException Guzzle\Service\Exception\InconsistentClientTransferException
     */
    public function testEnsuresAllCommandsUseTheSameClient()
    {
        $batch = new BatchCommandTransfer(2);
        $client1 = new Client('http://www.example.com');
        $client2 = new Client('http://www.example.com');
        $command1 = new Mc();
        $command1->setClient($client1);
        $command2 = new Mc();
        $command2->setClient($client2);
        $batch->transfer(array($command1, $command2));
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\Batch;

/**
 * @covers Guzzle\Batch\AbstractBatchDecorator
 */
class AbstractBatchDecoratorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testProxiesToWrappedObject()
    {
        $batch = new Batch(
            $this->getMock('Guzzle\Batch\BatchTransferInterface'),
            $this->getMock('Guzzle\Batch\BatchDivisorInterface')
        );

        $decoratorA = $this->getMockBuilder('Guzzle\Batch\AbstractBatchDecorator')
            ->setConstructorArgs(array($batch))
            ->getMockForAbstractClass();

        $decoratorB = $this->getMockBuilder('Guzzle\Batch\AbstractBatchDecorator')
            ->setConstructorArgs(array($decoratorA))
            ->getMockForAbstractClass();

        $decoratorA->add('foo');
        $this->assertFalse($decoratorB->isEmpty());
        $this->assertFalse($batch->isEmpty());
        $this->assertEquals(array($decoratorB, $decoratorA), $decoratorB->getDecorators());
        $this->assertEquals(array(), $decoratorB->flush());
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\ExceptionBufferingBatch;
use Guzzle\Batch\Batch;
use Guzzle\Batch\BatchSizeDivisor;

/**
 * @covers Guzzle\Batch\ExceptionBufferingBatch
 */
class ExceptionBufferingBatchTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testFlushesEntireBatchWhileBufferingErroredBatches()
    {
        $t = $this->getMockBuilder('Guzzle\Batch\BatchTransferInterface')
            ->setMethods(array('transfer'))
            ->getMock();

        $d = new BatchSizeDivisor(1);
        $batch = new Batch($t, $d);

        $called = 0;
        $t->expects($this->exactly(3))
            ->method('transfer')
            ->will($this->returnCallback(function ($batch) use (&$called) {
                if (++$called === 2) {
                    throw new \Exception('Foo');
                }
            }));

        $decorator = new ExceptionBufferingBatch($batch);
        $decorator->add('foo')->add('baz')->add('bar');
        $result = $decorator->flush();

        $e = $decorator->getExceptions();
        $this->assertEquals(1, count($e));
        $this->assertEquals(array('baz'), $e[0]->getBatch());

        $decorator->clearExceptions();
        $this->assertEquals(0, count($decorator->getExceptions()));

        $this->assertEquals(array('foo', 'bar'), $result);
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\Batch;
use Guzzle\Batch\Exception\BatchTransferException;

/**
 * @covers Guzzle\Batch\Batch
 */
class BatchTest extends \Guzzle\Tests\GuzzleTestCase
{
    private function getMockTransfer()
    {
        return $this->getMock('Guzzle\Batch\BatchTransferInterface');
    }

    private function getMockDivisor()
    {
        return $this->getMock('Guzzle\Batch\BatchDivisorInterface');
    }

    public function testAddsItemsToQueue()
    {
        $batch = new Batch($this->getMockTransfer(), $this->getMockDivisor());
        $this->assertSame($batch, $batch->add('foo'));
        $this->assertEquals(1, count($batch));
    }

    public function testFlushReturnsItems()
    {
        $transfer = $this->getMockTransfer();
        $transfer->expects($this->exactly(2))
            ->method('transfer');

        $divisor = $this->getMockDivisor();
        $divisor->expects($this->once())
            ->method('createBatches')
            ->will($this->returnValue(array(array('foo', 'baz'), array('bar'))));

        $batch = new Batch($transfer, $divisor);

        $batch->add('foo')->add('baz')->add('bar');
        $items = $batch->flush();

        $this->assertEquals(array('foo', 'baz', 'bar'), $items);
    }

    public function testThrowsExceptionContainingTheFailedBatch()
    {
        $called = 0;
        $originalException = new \Exception('Foo!');

        $transfer = $this->getMockTransfer();
        $transfer->expects($this->exactly(2))
            ->method('transfer')
            ->will($this->returnCallback(function () use (&$called, $originalException) {
                if (++$called == 2) {
                    throw $originalException;
                }
            }));

        $divisor = $this->getMockDivisor();
        $batch = new Batch($transfer, $divisor);

        // PHPunit clones objects before passing them to a callback.
        // Horrible hack to get around this!
        $queue = $this->readAttribute($batch, 'queue');

        $divisor->expects($this->once())
            ->method('createBatches')
            ->will($this->returnCallback(function ($batch) use ($queue) {
                foreach ($queue as $item) {
                    $items[] = $item;
                }
                return array_chunk($items, 2);
            }));

        $batch->add('foo')->add('baz')->add('bar')->add('bee')->add('boo');
        $this->assertFalse($batch->isEmpty());

        try {
            $items = $batch->flush();
            $this->fail('Expected exception');
        } catch (BatchTransferException $e) {
            $this->assertEquals($originalException, $e->getPrevious());
            $this->assertEquals(array('bar', 'bee'), array_values($e->getBatch()));
            $this->assertEquals(1, count($batch));
        }
    }
}
<?php

namespace Guzzle\Tests\Batch;

use Guzzle\Batch\BatchClosureTransfer;

/**
 * @covers Guzzle\Batch\BatchClosureTransfer
 */
class BatchClosureTransferTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var \Guzzle\Batch\BatchClosureTransfer The transfer fixture */
    protected $transferStrategy;

    /** @var array|null An array for keeping track of items passed into the transfer closure */
    protected $itemsTransferred;

    protected function setUp()
    {
        $this->itemsTransferred = null;
        $itemsTransferred =& $this->itemsTransferred;

        $this->transferStrategy = new BatchClosureTransfer(function (array $batch) use (&$itemsTransferred) {
            $itemsTransferred = $batch;
            return;
        });
    }

    public function testTransfersBatch()
    {
        $batchedItems = array('foo', 'bar', 'baz');
        $this->transferStrategy->transfer($batchedItems);

        $this->assertEquals($batchedItems, $this->itemsTransferred);
    }

    public function testTransferBailsOnEmptyBatch()
    {
        $batchedItems = array();
        $this->transferStrategy->transfer($batchedItems);

        $this->assertNull($this->itemsTransferred);
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testEnsuresCallableIsCallable()
    {
        $foo = new BatchClosureTransfer('uh oh!');
    }
}
<?php

namespace Guzzle\Tests\Log;

use Guzzle\Log\ArrayLogAdapter;

class ArrayLogAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testLog()
    {
        $adapter = new ArrayLogAdapter();
        $adapter->log('test', \LOG_NOTICE, '127.0.0.1');
        $this->assertEquals(array(array('message' => 'test', 'priority' => \LOG_NOTICE, 'extras' => '127.0.0.1')), $adapter->getLogs());
    }

    public function testClearLog()
    {
        $adapter = new ArrayLogAdapter();
        $adapter->log('test', \LOG_NOTICE, '127.0.0.1');
        $adapter->clearLogs();
        $this->assertEquals(array(), $adapter->getLogs());
    }
}
<?php

namespace Guzzle\Tests\Log;

use Guzzle\Log\Zf2LogAdapter;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;

/**
 * @covers Guzzle\Log\Zf2LogAdapter
 */
class Zf2LogAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Zf2LogAdapter */
    protected $adapter;

    /** @var Logger */
    protected $log;

    /** @var resource */
    protected $stream;

    protected function setUp()
    {
        $this->stream = fopen('php://temp', 'r+');
        $this->log = new Logger();
        $this->log->addWriter(new Stream($this->stream));
        $this->adapter = new Zf2LogAdapter($this->log);

    }

    public function testLogsMessagesToAdaptedObject()
    {
        // Test without a priority
        $this->adapter->log('Zend_Test!', \LOG_NOTICE);
        rewind($this->stream);
        $contents = stream_get_contents($this->stream);
        $this->assertEquals(1, substr_count($contents, 'Zend_Test!'));

        // Test with a priority
        $this->adapter->log('Zend_Test!', \LOG_ALERT);
        rewind($this->stream);
        $contents = stream_get_contents($this->stream);
        $this->assertEquals(2, substr_count($contents, 'Zend_Test!'));
    }

    public function testExposesAdaptedLogObject()
    {
        $this->assertEquals($this->log, $this->adapter->getLogObject());
    }
}
<?php

namespace Guzzle\Tests\Log;

use Guzzle\Http\Client;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Response;
use Guzzle\Log\MessageFormatter;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Log\ClosureLogAdapter;

/**
 * @covers Guzzle\Log\MessageFormatter
 */
class MessageFormatterTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $request;
    protected $response;
    protected $handle;

    public function setUp()
    {
        $this->request = new EntityEnclosingRequest('POST', 'http://foo.com?q=test', array(
            'X-Foo'         => 'bar',
            'Authorization' => 'Baz'
        ));
        $this->request->setBody(EntityBody::factory('Hello'));

        $this->response = new Response(200, array(
            'X-Test' => 'Abc'
        ), 'Foo');

        $this->handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle')
            ->disableOriginalConstructor()
            ->setMethods(array('getError', 'getErrorNo', 'getStderr', 'getInfo'))
            ->getMock();

        $this->handle->expects($this->any())
            ->method('getError')
            ->will($this->returnValue('e'));

        $this->handle->expects($this->any())
            ->method('getErrorNo')
            ->will($this->returnValue('123'));

        $this->handle->expects($this->any())
            ->method('getStderr')
            ->will($this->returnValue('testing'));

        $this->handle->expects($this->any())
            ->method('getInfo')
            ->will($this->returnValueMap(array(
                array(CURLINFO_CONNECT_TIME, '123'),
                array(CURLINFO_TOTAL_TIME, '456')
            )));
    }

    public function logProvider()
    {
        return array(
            // Uses the cache for the second time
            array('{method} - {method}', 'POST - POST'),
            array('{url}', 'http://foo.com?q=test'),
            array('{port}', '80'),
            array('{resource}', '/?q=test'),
            array('{host}', 'foo.com'),
            array('{hostname}', gethostname()),
            array('{protocol}/{version}', 'HTTP/1.1'),
            array('{code} {phrase}', '200 OK'),
            array('{req_header_Foo}', ''),
            array('{req_header_X-Foo}', 'bar'),
            array('{req_header_Authorization}', 'Baz'),
            array('{res_header_foo}', ''),
            array('{res_header_X-Test}', 'Abc'),
            array('{req_body}', 'Hello'),
            array('{res_body}', 'Foo'),
            array('{curl_stderr}', 'testing'),
            array('{curl_error}', 'e'),
            array('{curl_code}', '123'),
            array('{connect_time}', '123'),
            array('{total_time}', '456')
        );
    }

    /**
     * @dataProvider logProvider
     */
    public function testFormatsMessages($template, $output)
    {
        $formatter = new MessageFormatter($template);
        $this->assertEquals($output, $formatter->format($this->request, $this->response, $this->handle));
    }

    public function testFormatsRequestsAndResponses()
    {
        $formatter = new MessageFormatter();
        $formatter->setTemplate('{request}{response}');
        $this->assertEquals($this->request . $this->response, $formatter->format($this->request, $this->response));
    }

    public function testAddsTimestamp()
    {
        $formatter = new MessageFormatter('{ts}');
        $this->assertNotEmpty($formatter->format($this->request, $this->response));
    }

    public function testUsesResponseWhenNoHandleAndGettingCurlInformation()
    {
        $formatter = new MessageFormatter('{connect_time}/{total_time}');
        $response = $this->getMockBuilder('Guzzle\Http\Message\Response')
            ->setConstructorArgs(array(200))
            ->setMethods(array('getInfo'))
            ->getMock();
        $response->expects($this->exactly(2))
            ->method('getInfo')
            ->will($this->returnValueMap(array(
                array('connect_time', '1'),
                array('total_time', '2'),
            )));
        $this->assertEquals('1/2', $formatter->format($this->request, $response));
    }

    public function testUsesEmptyStringWhenNoHandleAndNoResponse()
    {
        $formatter = new MessageFormatter('{connect_time}/{total_time}');
        $this->assertEquals('/', $formatter->format($this->request));
    }

    public function testInjectsTotalTime()
    {
        $out = '';
        $formatter = new MessageFormatter('{connect_time}/{total_time}');
        $adapter = new ClosureLogAdapter(function ($m) use (&$out) { $out .= $m; });
        $log = new LogPlugin($adapter, $formatter);
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nHI");
        $client = new Client($this->getServer()->getUrl());
        $client->addSubscriber($log);
        $client->get('/')->send();
        $this->assertNotEquals('/', $out);
    }
}
<?php

namespace Guzzle\Tests\Log;

use Guzzle\Log\ClosureLogAdapter;

/**
 * @covers Guzzle\Log\ClosureLogAdapter
 */
class ClosureLogAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testClosure()
    {
        $that = $this;
        $modified = null;
        $this->adapter = new ClosureLogAdapter(function($message, $priority, $extras = null) use ($that, &$modified) {
            $modified = array($message, $priority, $extras);
        });
        $this->adapter->log('test', LOG_NOTICE, '127.0.0.1');
        $this->assertEquals(array('test', LOG_NOTICE, '127.0.0.1'), $modified);
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testThrowsExceptionWhenNotCallable()
    {
        $this->adapter = new ClosureLogAdapter(123);
    }
}
<?php

namespace Guzzle\Tests\Log;

use Guzzle\Log\PsrLogAdapter;
use Monolog\Logger;
use Monolog\Handler\TestHandler;

/**
 * @covers Guzzle\Log\PsrLogAdapter
 * @covers Guzzle\Log\AbstractLogAdapter
 */
class PsrLogAdapterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testLogsMessagesToAdaptedObject()
    {
        $log = new Logger('test');
        $handler = new TestHandler();
        $log->pushHandler($handler);
        $adapter = new PsrLogAdapter($log);
        $adapter->log('test!', LOG_INFO);
        $this->assertTrue($handler->hasInfoRecords());
        $this->assertSame($log, $adapter->getLogObject());
    }
}
<?php

namespace Guzzle\Tests\Service\Mock;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;

/**
 * Mock Guzzle Service
 */
class MockClient extends Client
{
    /**
     * Factory method to create a new mock client
     *
     * @param array|Collection $config Configuration data. Array keys:
     *    base_url - Base URL of web service
     *    api_version - API version
     *    scheme - URI scheme: http or https
     *  * username - API username
     *  * password - API password
     *  * subdomain - Unfuddle account subdomain
     *
     * @return MockClient
     */
    public static function factory($config = array())
    {
        $config = Collection::fromConfig($config, array(
            'base_url' => '{scheme}://127.0.0.1:8124/{api_version}/{subdomain}',
            'scheme' => 'http',
            'api_version' => 'v1'
        ), array('username', 'password', 'subdomain'));

        return new self($config->get('base_url'), $config);
    }
}
<?php

namespace Guzzle\Tests\Service\Mock\Model;

use Guzzle\Service\Resource\ResourceIterator;

class MockCommandIterator extends ResourceIterator
{
    public $calledNext = 0;

    protected function sendRequest()
    {
        if ($this->nextToken) {
            $this->command->set('next_token', $this->nextToken);
        }

        $this->command->set('page_size', (int) $this->calculatePageSize());
        $this->command->execute();

        $data = json_decode($this->command->getResponse()->getBody(true), true);

        $this->nextToken = $data['next_token'];

        return $data['resources'];
    }

    public function next()
    {
        $this->calledNext++;
        parent::next();
    }

    public function getResources()
    {
        return $this->resources;
    }

    public function getIteratedCount()
    {
        return $this->iteratedCount;
    }
}
<?php

namespace Guzzle\Tests\Service\Mock\Command;

use Guzzle\Service\Description\Operation;

class IterableCommand extends MockCommand
{
    protected function createOperation()
    {
        return new Operation(array(
            'name'       => 'iterable_command',
            'parameters' => array(
                'page_size' => array('type' => 'integer'),
                'next_token' => array('type' => 'string')
            )
        ));
    }

    protected function build()
    {
        $this->request = $this->client->createRequest('GET');

        // Add the next token and page size query string values
        $this->request->getQuery()->set('next_token', $this->get('next_token'));

        if ($this->get('page_size')) {
            $this->request->getQuery()->set('page_size', $this->get('page_size'));
        }
    }
}
<?php

namespace Guzzle\Tests\Service\Mock\Command;

use Guzzle\Service\Description\Operation;

class OtherCommand extends MockCommand
{
    protected function createOperation()
    {
        return new Operation(array(
            'name'       => 'other_command',
            'parameters' => array(
                'test' => array(
                    'default'  => '123',
                    'required' => true,
                    'doc'      => 'Test argument'
                ),
                'other'  => array(),
                'arg'    => array('type' => 'string'),
                'static' => array('static' => true, 'default' => 'this is static')
            )
        ));
    }

    protected function build()
    {
        $this->request = $this->client->getRequest('HEAD');
    }
}
<?php

namespace Guzzle\Tests\Service\Mock\Command\Sub;

use Guzzle\Tests\Service\Mock\Command\MockCommand;

class Sub extends MockCommand {}
<?php

namespace Guzzle\Tests\Service\Mock\Command;

use Guzzle\Service\Description\Operation;

class MockCommand extends \Guzzle\Service\Command\AbstractCommand
{
    protected function createOperation()
    {
        return new Operation(array(
            'name'       => get_called_class() == __CLASS__ ? 'mock_command' : 'sub.sub',
            'httpMethod' => 'POST',
            'parameters' => array(
                'test' => array(
                    'default'  => 123,
                    'required' => true,
                    'doc'      => 'Test argument'
                ),
                '_internal' => array(
                    'default' => 'abc'
                ),
                'foo' => array('filters' => array('strtoupper'))
            )
        ));
    }

    protected function build()
    {
        $this->request = $this->client->createRequest();
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\ServiceDescription;

/**
 * @covers Guzzle\Service\Description\Operation
 */
class OperationTest extends \Guzzle\Tests\GuzzleTestCase
{
    public static function strtoupper($string)
    {
        return strtoupper($string);
    }

    public function testOperationIsDataObject()
    {
        $c = new Operation(array(
            'name'               => 'test',
            'summary'            => 'doc',
            'notes'              => 'notes',
            'documentationUrl'   => 'http://www.example.com',
            'httpMethod'         => 'POST',
            'uri'                => '/api/v1',
            'responseClass'      => 'array',
            'responseNotes'      => 'returns the json_decoded response',
            'deprecated'         => true,
            'parameters'         => array(
                'key' => array(
                    'required'  => true,
                    'type'      => 'string',
                    'maxLength' => 10
                ),
                'key_2' => array(
                    'required' => true,
                    'type'     => 'integer',
                    'default'  => 10
                )
            )
        ));

        $this->assertEquals('test', $c->getName());
        $this->assertEquals('doc', $c->getSummary());
        $this->assertEquals('http://www.example.com', $c->getDocumentationUrl());
        $this->assertEquals('POST', $c->getHttpMethod());
        $this->assertEquals('/api/v1', $c->getUri());
        $this->assertEquals('array', $c->getResponseClass());
        $this->assertEquals('returns the json_decoded response', $c->getResponseNotes());
        $this->assertTrue($c->getDeprecated());
        $this->assertEquals('Guzzle\\Service\\Command\\OperationCommand', $c->getClass());
        $this->assertEquals(array(
            'key' => new Parameter(array(
                'name'      => 'key',
                'required'  => true,
                'type'      => 'string',
                'maxLength' => 10,
                'parent'    => $c
            )),
            'key_2' => new Parameter(array(
                'name'     => 'key_2',
                'required' => true,
                'type'     => 'integer',
                'default'  => 10,
                'parent'   => $c
            ))
        ), $c->getParams());

        $this->assertEquals(new Parameter(array(
            'name'     => 'key_2',
            'required' => true,
            'type'     => 'integer',
            'default'  => 10,
            'parent'   => $c
        )), $c->getParam('key_2'));

        $this->assertNull($c->getParam('afefwef'));
        $this->assertArrayNotHasKey('parent', $c->getParam('key_2')->toArray());
    }

    public function testAllowsConcreteCommands()
    {
        $c = new Operation(array(
            'name' => 'test',
            'class' => 'Guzzle\\Service\\Command\ClosureCommand',
            'parameters' => array(
                'p' => new Parameter(array(
                    'name' => 'foo'
                ))
            )
        ));
        $this->assertEquals('Guzzle\\Service\\Command\ClosureCommand', $c->getClass());
    }

    public function testConvertsToArray()
    {
        $data = array(
            'name'             => 'test',
            'class'            => 'Guzzle\\Service\\Command\ClosureCommand',
            'summary'          => 'test',
            'documentationUrl' => 'http://www.example.com',
            'httpMethod'       => 'PUT',
            'uri'              => '/',
            'parameters'       => array('p' => array('name' => 'foo'))
        );
        $c = new Operation($data);
        $toArray = $c->toArray();
        unset($data['name']);
        $this->assertArrayHasKey('parameters', $toArray);
        $this->assertInternalType('array', $toArray['parameters']);

        // Normalize the array
        unset($data['parameters']);
        unset($toArray['parameters']);

        $data['responseType'] = 'primitive';
        $data['responseClass'] = 'array';
        $this->assertEquals($data, $toArray);
    }

    public function testDeterminesIfHasParam()
    {
        $command = $this->getTestCommand();
        $this->assertTrue($command->hasParam('data'));
        $this->assertFalse($command->hasParam('baz'));
    }

    public function testReturnsParamNames()
    {
        $command = $this->getTestCommand();
        $this->assertEquals(array('data'), $command->getParamNames());
    }

    protected function getTestCommand()
    {
        return new Operation(array(
            'parameters' => array(
                'data' => new Parameter(array(
                    'type' => 'string'
                ))
            )
        ));
    }

    public function testCanBuildUpCommands()
    {
        $c = new Operation(array());
        $c->setName('foo')
            ->setClass('Baz')
            ->setDeprecated(false)
            ->setSummary('summary')
            ->setDocumentationUrl('http://www.foo.com')
            ->setHttpMethod('PUT')
            ->setResponseNotes('oh')
            ->setResponseClass('string')
            ->setUri('/foo/bar')
            ->addParam(new Parameter(array(
                'name' => 'test'
            )));

        $this->assertEquals('foo', $c->getName());
        $this->assertEquals('Baz', $c->getClass());
        $this->assertEquals(false, $c->getDeprecated());
        $this->assertEquals('summary', $c->getSummary());
        $this->assertEquals('http://www.foo.com', $c->getDocumentationUrl());
        $this->assertEquals('PUT', $c->getHttpMethod());
        $this->assertEquals('oh', $c->getResponseNotes());
        $this->assertEquals('string', $c->getResponseClass());
        $this->assertEquals('/foo/bar', $c->getUri());
        $this->assertEquals(array('test'), $c->getParamNames());
    }

    public function testCanRemoveParams()
    {
        $c = new Operation(array());
        $c->addParam(new Parameter(array('name' => 'foo')));
        $this->assertTrue($c->hasParam('foo'));
        $c->removeParam('foo');
        $this->assertFalse($c->hasParam('foo'));
    }

    public function testAddsNameToParametersIfNeeded()
    {
        $command = new Operation(array('parameters' => array('foo' => new Parameter(array()))));
        $this->assertEquals('foo', $command->getParam('foo')->getName());
    }

    public function testContainsApiErrorInformation()
    {
        $command = $this->getOperation();
        $this->assertEquals(1, count($command->getErrorResponses()));
        $arr = $command->toArray();
        $this->assertEquals(1, count($arr['errorResponses']));
        $command->addErrorResponse(400, 'Foo', 'Baz\\Bar');
        $this->assertEquals(2, count($command->getErrorResponses()));
        $command->setErrorResponses(array());
        $this->assertEquals(0, count($command->getErrorResponses()));
    }

    public function testHasNotes()
    {
        $o = new Operation(array('notes' => 'foo'));
        $this->assertEquals('foo', $o->getNotes());
        $o->setNotes('bar');
        $this->assertEquals('bar', $o->getNotes());
    }

    public function testHasData()
    {
        $o = new Operation(array('data' => array('foo' => 'baz', 'bar' => 123)));
        $o->setData('test', false);
        $this->assertEquals('baz', $o->getData('foo'));
        $this->assertEquals(123, $o->getData('bar'));
        $this->assertNull($o->getData('wfefwe'));
        $this->assertEquals(array(
            'parameters'    => array(),
            'class'         => 'Guzzle\Service\Command\OperationCommand',
            'data'          => array('foo' => 'baz', 'bar' => 123, 'test' => false),
            'responseClass' => 'array',
            'responseType'  => 'primitive'
        ), $o->toArray());
    }

    public function testHasServiceDescription()
    {
        $s = new ServiceDescription();
        $o = new Operation(array(), $s);
        $this->assertSame($s, $o->getServiceDescription());
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesResponseType()
    {
        $o = new Operation(array('responseClass' => 'array', 'responseType' => 'foo'));
    }

    public function testInfersResponseType()
    {
        $o = $this->getOperation();
        $o->setServiceDescription(new ServiceDescription(array('models' => array('Foo' => array()))));
        $this->assertEquals('primitive', $o->getResponseType());
        $this->assertEquals('primitive', $o->setResponseClass('boolean')->getResponseType());
        $this->assertEquals('primitive', $o->setResponseClass('array')->getResponseType());
        $this->assertEquals('primitive', $o->setResponseClass('integer')->getResponseType());
        $this->assertEquals('primitive', $o->setResponseClass('string')->getResponseType());
        $this->assertEquals('class', $o->setResponseClass('foo')->getResponseType());
        $this->assertEquals('class', $o->setResponseClass(__CLASS__)->getResponseType());
        $this->assertEquals('model', $o->setResponseClass('Foo')->getResponseType());
    }

    public function testHasResponseType()
    {
        // infers in the constructor
        $o = new Operation(array('responseClass' => 'array'));
        $this->assertEquals('primitive', $o->getResponseType());
        // Infers when set
        $o = new Operation();
        $this->assertEquals('primitive', $o->getResponseType());
        $this->assertEquals('model', $o->setResponseType('model')->getResponseType());
    }

    public function testHasAdditionalParameters()
    {
        $o = new Operation(array(
            'additionalParameters' => array(
                'type' => 'string', 'name' => 'binks'
            ),
            'parameters' => array(
                'foo' => array('type' => 'integer')
            )
        ));
        $this->assertEquals('string', $o->getAdditionalParameters()->getType());
        $arr = $o->toArray();
        $this->assertEquals(array(
            'type' => 'string'
        ), $arr['additionalParameters']);
    }

    /**
     * @return Operation
     */
    protected function getOperation()
    {
        return new Operation(array(
            'name'       => 'OperationTest',
            'class'      => get_class($this),
            'parameters' => array(
                'test'          => array('type' => 'object'),
                'bool_1'        => array('default' => true, 'type' => 'boolean'),
                'bool_2'        => array('default' => false),
                'float'         => array('type' => 'numeric'),
                'int'           => array('type' => 'integer'),
                'date'          => array('type' => 'string'),
                'timestamp'     => array('type' => 'string'),
                'string'        => array('type' => 'string'),
                'username'      => array('type' => 'string', 'required' => true, 'filters' => 'strtolower'),
                'test_function' => array('type' => 'string', 'filters' => __CLASS__ . '::strtoupper')
            ),
            'errorResponses' => array(
                array('code' => 503, 'reason' => 'InsufficientCapacity', 'class' => 'Guzzle\\Exception\\RuntimeException')
            )
        ));
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\ServiceDescription;

/**
 * @covers Guzzle\Service\Description\Parameter
 */
class ParameterTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $data = array(
        'name'            => 'foo',
        'type'            => 'bar',
        'required'        => true,
        'default'         => '123',
        'description'     => '456',
        'minLength'       => 2,
        'maxLength'       => 5,
        'location'        => 'body',
        'static'          => 'static!',
        'filters'         => array('trim', 'json_encode')
    );

    public function testCreatesParamFromArray()
    {
        $p = new Parameter($this->data);
        $this->assertEquals('foo', $p->getName());
        $this->assertEquals('bar', $p->getType());
        $this->assertEquals(true, $p->getRequired());
        $this->assertEquals('123', $p->getDefault());
        $this->assertEquals('456', $p->getDescription());
        $this->assertEquals(2, $p->getMinLength());
        $this->assertEquals(5, $p->getMaxLength());
        $this->assertEquals('body', $p->getLocation());
        $this->assertEquals('static!', $p->getStatic());
        $this->assertEquals(array('trim', 'json_encode'), $p->getFilters());
    }

    public function testCanConvertToArray()
    {
        $p = new Parameter($this->data);
        unset($this->data['name']);
        $this->assertEquals($this->data, $p->toArray());
    }

    public function testUsesStatic()
    {
        $d = $this->data;
        $d['default'] = 'booboo';
        $d['static'] = true;
        $p = new Parameter($d);
        $this->assertEquals('booboo', $p->getValue('bar'));
    }

    public function testUsesDefault()
    {
        $d = $this->data;
        $d['default'] = 'foo';
        $d['static'] = null;
        $p = new Parameter($d);
        $this->assertEquals('foo', $p->getValue(null));
    }

    public function testReturnsYourValue()
    {
        $d = $this->data;
        $d['static'] = null;
        $p = new Parameter($d);
        $this->assertEquals('foo', $p->getValue('foo'));
    }

    public function testZeroValueDoesNotCauseDefaultToBeReturned()
    {
        $d = $this->data;
        $d['default'] = '1';
        $d['static'] = null;
        $p = new Parameter($d);
        $this->assertEquals('0', $p->getValue('0'));
    }

    public function testFiltersValues()
    {
        $d = $this->data;
        $d['static'] = null;
        $d['filters'] = 'strtoupper';
        $p = new Parameter($d);
        $this->assertEquals('FOO', $p->filter('foo'));
    }

    public function testConvertsBooleans()
    {
        $p = new Parameter(array('type' => 'boolean'));
        $this->assertEquals(true, $p->filter('true'));
        $this->assertEquals(false, $p->filter('false'));
    }

    public function testUsesArrayByDefaultForFilters()
    {
        $d = $this->data;
        $d['filters'] = null;
        $p = new Parameter($d);
        $this->assertEquals(array(), $p->getFilters());
    }

    public function testAllowsSimpleLocationValue()
    {
        $p = new Parameter(array('name' => 'myname', 'location' => 'foo', 'sentAs' => 'Hello'));
        $this->assertEquals('foo', $p->getLocation());
        $this->assertEquals('Hello', $p->getSentAs());
    }

    public function testParsesTypeValues()
    {
        $p = new Parameter(array('type' => 'foo'));
        $this->assertEquals('foo', $p->getType());
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage A [method] value must be specified for each complex filter
     */
    public function testValidatesComplexFilters()
    {
        $p = new Parameter(array('filters' => array(array('args' => 'foo'))));
    }

    public function testCanBuildUpParams()
    {
        $p = new Parameter(array());
        $p->setName('foo')
            ->setDescription('c')
            ->setFilters(array('d'))
            ->setLocation('e')
            ->setSentAs('f')
            ->setMaxLength(1)
            ->setMinLength(1)
            ->setMinimum(2)
            ->setMaximum(2)
            ->setMinItems(3)
            ->setMaxItems(3)
            ->setRequired(true)
            ->setStatic(true)
            ->setDefault('h')
            ->setType('i');

        $p->addFilter('foo');

        $this->assertEquals('foo', $p->getName());
        $this->assertEquals('h', $p->getDefault());
        $this->assertEquals('c', $p->getDescription());
        $this->assertEquals(array('d', 'foo'), $p->getFilters());
        $this->assertEquals('e', $p->getLocation());
        $this->assertEquals('f', $p->getSentAs());
        $this->assertEquals(1, $p->getMaxLength());
        $this->assertEquals(1, $p->getMinLength());
        $this->assertEquals(2, $p->getMaximum());
        $this->assertEquals(2, $p->getMinimum());
        $this->assertEquals(3, $p->getMaxItems());
        $this->assertEquals(3, $p->getMinItems());
        $this->assertEquals(true, $p->getRequired());
        $this->assertEquals(true, $p->getStatic());
        $this->assertEquals('i', $p->getType());
    }

    public function testAllowsNestedShape()
    {
        $command = $this->getServiceBuilder()->get('mock')->getCommand('mock_command')->getOperation();
        $param = new Parameter(array(
            'parent'     => $command,
            'name'       => 'foo',
            'type'       => 'object',
            'location'   => 'query',
            'properties' => array(
                'foo' => array(
                    'type'      => 'object',
                    'required'  => true,
                    'properties' => array(
                        'baz' => array(
                            'name' => 'baz',
                            'type' => 'bool',
                        )
                    )
                ),
                'bar' => array(
                    'name'    => 'bar',
                    'default' => '123'
                )
            )
        ));

        $this->assertSame($command, $param->getParent());
        $this->assertNotEmpty($param->getProperties());
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getProperty('foo'));
        $this->assertSame($param, $param->getProperty('foo')->getParent());
        $this->assertSame($param->getProperty('foo'), $param->getProperty('foo')->getProperty('baz')->getParent());
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getProperty('bar'));
        $this->assertSame($param, $param->getProperty('bar')->getParent());

        $array = $param->toArray();
        $this->assertInternalType('array', $array['properties']);
        $this->assertArrayHasKey('foo', $array['properties']);
        $this->assertArrayHasKey('bar', $array['properties']);
    }

    public function testAllowsComplexFilters()
    {
        $that = $this;
        $param = new Parameter(array());
        $param->setFilters(array(array('method' => function ($a, $b, $c, $d) use ($that, $param) {
            $that->assertEquals('test', $a);
            $that->assertEquals('my_value!', $b);
            $that->assertEquals('bar', $c);
            $that->assertSame($param, $d);
            return 'abc' . $b;
        }, 'args' => array('test', '@value', 'bar', '@api'))));
        $this->assertEquals('abcmy_value!', $param->filter('my_value!'));
    }

    public function testCanChangeParentOfNestedParameter()
    {
        $param1 = new Parameter(array('name' => 'parent'));
        $param2 = new Parameter(array('name' => 'child'));
        $param2->setParent($param1);
        $this->assertSame($param1, $param2->getParent());
    }

    public function testCanRemoveFromNestedStructure()
    {
        $param1 = new Parameter(array('name' => 'parent'));
        $param2 = new Parameter(array('name' => 'child'));
        $param1->addProperty($param2);
        $this->assertSame($param1, $param2->getParent());
        $this->assertSame($param2, $param1->getProperty('child'));

        // Remove a single child from the structure
        $param1->removeProperty('child');
        $this->assertNull($param1->getProperty('child'));
        // Remove the entire structure
        $param1->addProperty($param2);
        $param1->removeProperty('child');
        $this->assertNull($param1->getProperty('child'));
    }

    public function testAddsAdditionalProperties()
    {
        $p = new Parameter(array(
            'type' => 'object',
            'additionalProperties' => array('type' => 'string')
        ));
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $p->getAdditionalProperties());
        $this->assertNull($p->getAdditionalProperties()->getAdditionalProperties());
        $p = new Parameter(array('type' => 'object'));
        $this->assertTrue($p->getAdditionalProperties());
    }

    public function testAddsItems()
    {
        $p = new Parameter(array(
            'type'  => 'array',
            'items' => array('type' => 'string')
        ));
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $p->getItems());
        $out = $p->toArray();
        $this->assertEquals('array', $out['type']);
        $this->assertInternalType('array', $out['items']);
    }

    public function testHasExtraProperties()
    {
        $p = new Parameter();
        $this->assertEquals(array(), $p->getData());
        $p->setData(array('foo' => 'bar'));
        $this->assertEquals('bar', $p->getData('foo'));
        $p->setData('baz', 'boo');
        $this->assertEquals(array('foo' => 'bar', 'baz' => 'boo'), $p->getData());
    }

    public function testCanRetrieveKnownPropertiesUsingDataMethod()
    {
        $p = new Parameter();
        $this->assertEquals(null, $p->getData('foo'));
        $p->setName('test');
        $this->assertEquals('test', $p->getData('name'));
    }

    public function testHasInstanceOf()
    {
        $p = new Parameter();
        $this->assertNull($p->getInstanceOf());
        $p->setInstanceOf('Foo');
        $this->assertEquals('Foo', $p->getInstanceOf());
    }

    public function testHasPattern()
    {
        $p = new Parameter();
        $this->assertNull($p->getPattern());
        $p->setPattern('/[0-9]+/');
        $this->assertEquals('/[0-9]+/', $p->getPattern());
    }

    public function testHasEnum()
    {
        $p = new Parameter();
        $this->assertNull($p->getEnum());
        $p->setEnum(array('foo', 'bar'));
        $this->assertEquals(array('foo', 'bar'), $p->getEnum());
    }

    public function testSerializesItems()
    {
        $p = new Parameter(array(
            'type'  => 'object',
            'additionalProperties' => array('type' => 'string')
        ));
        $this->assertEquals(array(
            'type'  => 'object',
            'additionalProperties' => array('type' => 'string')
        ), $p->toArray());
    }

    public function testResolvesRefKeysRecursively()
    {
        $description = new ServiceDescription(array(
            'models' => array(
                'JarJar' => array('type' => 'string', 'default' => 'Mesa address tha senate!'),
                'Anakin' => array('type' => 'array', 'items' => array('$ref' => 'JarJar'))
            )
        ));
        $p = new Parameter(array('$ref' => 'Anakin', 'description' => 'added'), $description);
        $this->assertEquals(array(
            'type' => 'array',
            'items' => array('type' => 'string', 'default' => 'Mesa address tha senate!'),
            'description' => 'added'
        ), $p->toArray());
    }

    public function testResolvesExtendsRecursively()
    {
        $jarJar = array('type' => 'string', 'default' => 'Mesa address tha senate!', 'description' => 'a');
        $anakin = array('type' => 'array', 'items' => array('extends' => 'JarJar', 'description' => 'b'));
        $description = new ServiceDescription(array(
            'models' => array('JarJar' => $jarJar, 'Anakin' => $anakin)
        ));
        // Description attribute will be updated, and format added
        $p = new Parameter(array('extends' => 'Anakin', 'format' => 'date'), $description);
        $this->assertEquals(array(
            'type'  => 'array',
            'format' => 'date',
            'items' => array(
                'type'    => 'string',
                'default' => 'Mesa address tha senate!',
                'description' => 'b'
            )
        ), $p->toArray());
    }

    public function testHasKeyMethod()
    {
        $p = new Parameter(array('name' => 'foo', 'sentAs' => 'bar'));
        $this->assertEquals('bar', $p->getWireName());
        $p->setSentAs(null);
        $this->assertEquals('foo', $p->getWireName());
    }

    public function testIncludesNameInToArrayWhenItemsAttributeHasName()
    {
        $p = new Parameter(array(
            'type' => 'array',
            'name' => 'Abc',
            'items' => array(
                'name' => 'Foo',
                'type' => 'object'
            )
        ));
        $result = $p->toArray();
        $this->assertEquals(array(
            'type' => 'array',
            'items' => array(
                'name' => 'Foo',
                'type' => 'object',
                'additionalProperties' => true
            )
        ), $result);
    }

    public function dateTimeProvider()
    {
        $d = 'October 13, 2012 16:15:46 UTC';

        return array(
            array($d, 'date-time', '2012-10-13T16:15:46Z'),
            array($d, 'date', '2012-10-13'),
            array($d, 'timestamp', strtotime($d)),
            array(new \DateTime($d), 'timestamp', strtotime($d))
        );
    }

    /**
     * @dataProvider dateTimeProvider
     */
    public function testAppliesFormat($d, $format, $result)
    {
        $p = new Parameter();
        $p->setFormat($format);
        $this->assertEquals($format, $p->getFormat());
        $this->assertEquals($result, $p->filter($d));
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Description\ServiceDescriptionLoader;

/**
 * @covers Guzzle\Service\Description\ServiceDescriptionLoader
 */
class ServiceDescriptionLoaderTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testAllowsExtraData()
    {
        $d = ServiceDescription::factory(array(
            'foo' => true,
            'baz' => array('bar'),
            'apiVersion' => '123',
            'operations' => array()
        ));

        $this->assertEquals(true, $d->getData('foo'));
        $this->assertEquals(array('bar'), $d->getData('baz'));
        $this->assertEquals('123', $d->getApiVersion());
    }

    public function testAllowsDeepNestedInheritance()
    {
        $d = ServiceDescription::factory(array(
            'operations' => array(
                'abstract' => array(
                    'httpMethod' => 'HEAD',
                    'parameters' => array(
                        'test' => array('type' => 'string', 'required' => true)
                    )
                ),
                'abstract2' => array('uri' => '/test', 'extends' => 'abstract'),
                'concrete'  => array('extends' => 'abstract2'),
                'override'  => array('extends' => 'abstract', 'httpMethod' => 'PUT'),
                'override2'  => array('extends' => 'override', 'httpMethod' => 'POST', 'uri' => '/')
            )
        ));

        $c = $d->getOperation('concrete');
        $this->assertEquals('/test', $c->getUri());
        $this->assertEquals('HEAD', $c->getHttpMethod());
        $params = $c->getParams();
        $param = $params['test'];
        $this->assertEquals('string', $param->getType());
        $this->assertTrue($param->getRequired());

        // Ensure that merging HTTP method does not make an array
        $this->assertEquals('PUT', $d->getOperation('override')->getHttpMethod());
        $this->assertEquals('POST', $d->getOperation('override2')->getHttpMethod());
        $this->assertEquals('/', $d->getOperation('override2')->getUri());
    }

    /**
     * @expectedException RuntimeException
     */
    public function testThrowsExceptionWhenExtendingMissingCommand()
    {
        ServiceDescription::factory(array(
            'operations' => array(
                'concrete' => array(
                    'extends' => 'missing'
                )
            )
        ));
    }

    public function testAllowsMultipleInheritance()
    {
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'a' => array(
                    'httpMethod' => 'GET',
                    'parameters' => array(
                        'a1' => array(
                            'default'  => 'foo',
                            'required' => true,
                            'prepend'  => 'hi'
                        )
                    )
                ),
                'b' => array(
                    'extends' => 'a',
                    'parameters' => array(
                        'b2' => array()
                    )
                ),
                'c' => array(
                    'parameters' => array(
                        'a1' => array(
                            'default'     => 'bar',
                            'required'    => true,
                            'description' => 'test'
                        ),
                        'c3' => array()
                    )
                ),
                'd' => array(
                    'httpMethod' => 'DELETE',
                    'extends'    => array('b', 'c'),
                    'parameters' => array(
                        'test' => array()
                    )
                )
            )
        ));

        $command = $description->getOperation('d');
        $this->assertEquals('DELETE', $command->getHttpMethod());
        $this->assertContains('a1', $command->getParamNames());
        $this->assertContains('b2', $command->getParamNames());
        $this->assertContains('c3', $command->getParamNames());
        $this->assertContains('test', $command->getParamNames());

        $this->assertTrue($command->getParam('a1')->getRequired());
        $this->assertEquals('bar', $command->getParam('a1')->getDefault());
        $this->assertEquals('test', $command->getParam('a1')->getDescription());
    }

    public function testAddsOtherFields()
    {
        $description = ServiceDescription::factory(array(
            'operations'  => array(),
            'description' => 'Foo',
            'apiVersion'  => 'bar'
        ));
        $this->assertEquals('Foo', $description->getDescription());
        $this->assertEquals('bar', $description->getApiVersion());
    }

    public function testCanLoadNestedExtends()
    {
        $description = ServiceDescription::factory(array(
            'operations'  => array(
                'root' => array(
                    'class' => 'foo'
                ),
                'foo' => array(
                    'extends' => 'root',
                    'parameters' => array(
                        'baz' => array('type' => 'string')
                    )
                ),
                'foo_2' => array(
                    'extends' => 'foo',
                    'parameters' => array(
                        'bar' => array('type' => 'string')
                    )
                ),
                'foo_3' => array(
                    'class' => 'bar',
                    'parameters' => array(
                        'bar2' => array('type' => 'string')
                    )
                ),
                'foo_4' => array(
                    'extends' => array('foo_2', 'foo_3'),
                    'parameters' => array(
                        'bar3' => array('type' => 'string')
                    )
                )
            )
        ));

        $this->assertTrue($description->hasOperation('foo_4'));
        $foo4 = $description->getOperation('foo_4');
        $this->assertTrue($foo4->hasParam('baz'));
        $this->assertTrue($foo4->hasParam('bar'));
        $this->assertTrue($foo4->hasParam('bar2'));
        $this->assertTrue($foo4->hasParam('bar3'));
        $this->assertEquals('bar', $foo4->getClass());
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Client;

/**
 * @covers Guzzle\Service\Description\ServiceDescription
 */
class ServiceDescriptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $serviceData;

    public function setup()
    {
        $this->serviceData = array(
            'test_command' => new Operation(array(
                'name'        => 'test_command',
                'description' => 'documentationForCommand',
                'httpMethod'  => 'DELETE',
                'class'       => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand',
                'parameters'  => array(
                    'bucket'  => array('required' => true),
                    'key'     => array('required' => true)
                )
            ))
        );
    }

    /**
     * @covers Guzzle\Service\Description\ServiceDescription::factory
     * @covers Guzzle\Service\Description\ServiceDescriptionLoader::build
     */
    public function testFactoryDelegatesToConcreteFactories()
    {
        $jsonFile = __DIR__ . '/../../TestData/test_service.json';
        $this->assertInstanceOf('Guzzle\Service\Description\ServiceDescription', ServiceDescription::factory($jsonFile));
    }

    public function testConstructor()
    {
        $service = new ServiceDescription(array('operations' => $this->serviceData));
        $this->assertEquals(1, count($service->getOperations()));
        $this->assertFalse($service->hasOperation('foobar'));
        $this->assertTrue($service->hasOperation('test_command'));
    }

    public function testIsSerializable()
    {
        $service = new ServiceDescription(array('operations' => $this->serviceData));
        $data = serialize($service);
        $d2 = unserialize($data);
        $this->assertEquals(serialize($service), serialize($d2));
    }

    public function testSerializesParameters()
    {
        $service = new ServiceDescription(array(
            'operations' => array(
                'foo' => new Operation(array('parameters' => array('foo' => array('type' => 'string'))))
            )
        ));
        $serialized = serialize($service);
        $this->assertContains('"parameters":{"foo":', $serialized);
        $service = unserialize($serialized);
        $this->assertTrue($service->getOperation('foo')->hasParam('foo'));
    }

    public function testAllowsForJsonBasedArrayParamsFunctionalTest()
    {
        $description = new ServiceDescription(array(
            'operations' => array(
                'test' => new Operation(array(
                    'httpMethod' => 'PUT',
                    'parameters' => array(
                        'data'   => array(
                            'required' => true,
                            'filters'  => 'json_encode',
                            'location' => 'body'
                        )
                    )
                ))
            )
        ));
        $client = new Client();
        $client->setDescription($description);
        $command = $client->getCommand('test', array(
            'data' => array(
                'foo' => 'bar'
            )
        ));

        $request = $command->prepare();
        $this->assertEquals('{"foo":"bar"}', (string) $request->getBody());
    }

    public function testContainsModels()
    {
        $d = new ServiceDescription(array(
            'operations' => array('foo' => array()),
            'models' => array(
                'Tag'    => array('type' => 'object'),
                'Person' => array('type' => 'object')
            )
        ));
        $this->assertTrue($d->hasModel('Tag'));
        $this->assertTrue($d->hasModel('Person'));
        $this->assertFalse($d->hasModel('Foo'));
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $d->getModel('Tag'));
        $this->assertNull($d->getModel('Foo'));
        $this->assertContains('"models":{', serialize($d));
        $this->assertEquals(array('Tag', 'Person'), array_keys($d->getModels()));
    }

    public function testCanAddModels()
    {
        $d = new ServiceDescription(array());
        $this->assertFalse($d->hasModel('Foo'));
        $d->addModel(new Parameter(array('name' => 'Foo')));
        $this->assertTrue($d->hasModel('Foo'));
    }

    public function testHasAttributes()
    {
        $d = new ServiceDescription(array(
            'operations'  => array(),
            'name'        => 'Name',
            'description' => 'Description',
            'apiVersion'  => '1.24'
        ));

        $this->assertEquals('Name', $d->getName());
        $this->assertEquals('Description', $d->getDescription());
        $this->assertEquals('1.24', $d->getApiVersion());

        $s = serialize($d);
        $this->assertContains('"name":"Name"', $s);
        $this->assertContains('"description":"Description"', $s);
        $this->assertContains('"apiVersion":"1.24"', $s);

        $d = unserialize($s);
        $this->assertEquals('Name', $d->getName());
        $this->assertEquals('Description', $d->getDescription());
        $this->assertEquals('1.24', $d->getApiVersion());
    }

    public function testPersistsCustomAttributes()
    {
        $data = array(
            'operations'  => array('foo' => array('class' => 'foo', 'parameters' => array())),
            'name'        => 'Name',
            'description' => 'Test',
            'apiVersion'  => '1.24',
            'auth'        => 'foo',
            'keyParam'    => 'bar'
        );
        $d = new ServiceDescription($data);
        $d->setData('hello', 'baz');
        $this->assertEquals('foo', $d->getData('auth'));
        $this->assertEquals('baz', $d->getData('hello'));
        $this->assertEquals('bar', $d->getData('keyParam'));
        // responseClass and responseType are added by default
        $data['operations']['foo']['responseClass'] = 'array';
        $data['operations']['foo']['responseType'] = 'primitive';
        $this->assertEquals($data + array('hello' => 'baz'), json_decode($d->serialize(), true));
    }

    public function testHasToArray()
    {
        $data = array(
            'operations'  => array(),
            'name'        => 'Name',
            'description' => 'Test'
        );
        $d = new ServiceDescription($data);
        $arr = $d->toArray();
        $this->assertEquals('Name', $arr['name']);
        $this->assertEquals('Test', $arr['description']);
    }

    public function testReturnsNullWhenRetrievingMissingOperation()
    {
        $s = new ServiceDescription(array());
        $this->assertNull($s->getOperation('foo'));
    }

    public function testCanAddOperations()
    {
        $s = new ServiceDescription(array());
        $this->assertFalse($s->hasOperation('Foo'));
        $s->addOperation(new Operation(array('name' => 'Foo')));
        $this->assertTrue($s->hasOperation('Foo'));
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesOperationTypes()
    {
        $s = new ServiceDescription(array(
            'operations' => array('foo' => new \stdClass())
        ));
    }

    public function testHasBaseUrl()
    {
        $description = new ServiceDescription(array('baseUrl' => 'http://foo.com'));
        $this->assertEquals('http://foo.com', $description->getBaseUrl());
        $description->setBaseUrl('http://foobar.com');
        $this->assertEquals('http://foobar.com', $description->getBaseUrl());
    }

    public function testCanUseBasePath()
    {
        $description = new ServiceDescription(array('basePath' => 'http://foo.com'));
        $this->assertEquals('http://foo.com', $description->getBaseUrl());
    }

    public function testModelsHaveNames()
    {
        $desc = array(
            'models' => array(
                'date' => array('type' => 'string'),
                'user'=> array(
                    'type' => 'object',
                    'properties' => array(
                        'dob' => array('$ref' => 'date')
                    )
                )
            )
        );

        $s = ServiceDescription::factory($desc);
        $this->assertEquals('date', $s->getModel('date')->getName());
        $this->assertEquals('dob', $s->getModel('user')->getProperty('dob')->getName());
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\SchemaValidator;

/**
 * @covers Guzzle\Service\Description\SchemaValidator
 */
class SchemaValidatorTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var SchemaValidator */
    protected $validator;

    public function setUp()
    {
        $this->validator = new SchemaValidator();
    }

    public function testValidatesArrayListsAreNumericallyIndexed()
    {
        $value = array(array(1));
        $this->assertFalse($this->validator->validate($this->getComplexParam(), $value));
        $this->assertEquals(
            array('[Foo][0] must be an array of properties. Got a numerically indexed array.'),
            $this->validator->getErrors()
        );
    }

    public function testValidatesArrayListsContainProperItems()
    {
        $value = array(true);
        $this->assertFalse($this->validator->validate($this->getComplexParam(), $value));
        $this->assertEquals(
            array('[Foo][0] must be of type object'),
            $this->validator->getErrors()
        );
    }

    public function testAddsDefaultValuesInLists()
    {
        $value = array(array());
        $this->assertTrue($this->validator->validate($this->getComplexParam(), $value));
        $this->assertEquals(array(array('Bar' => true)), $value);
    }

    public function testMergesDefaultValuesInLists()
    {
        $value = array(
            array('Baz' => 'hello!'),
            array('Bar' => false)
        );
        $this->assertTrue($this->validator->validate($this->getComplexParam(), $value));
        $this->assertEquals(array(
            array(
                'Baz' => 'hello!',
                'Bar' => true
            ),
            array('Bar' => false)
        ), $value);
    }

    public function testCorrectlyConvertsParametersToArrayWhenArraysArePresent()
    {
        $param = $this->getComplexParam();
        $result = $param->toArray();
        $this->assertInternalType('array', $result['items']);
        $this->assertEquals('array', $result['type']);
        $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getItems());
    }

    public function testAllowsInstanceOf()
    {
        $p = new Parameter(array(
            'name'       => 'foo',
            'type'       => 'object',
            'instanceOf' => get_class($this)
        ));
        $this->assertTrue($this->validator->validate($p, $this));
        $this->assertFalse($this->validator->validate($p, $p));
        $this->assertEquals(array('[foo] must be an instance of ' . __CLASS__), $this->validator->getErrors());
    }

    public function testEnforcesInstanceOfOnlyWhenObject()
    {
        $p = new Parameter(array(
            'name'       => 'foo',
            'type'       => array('object', 'string'),
            'instanceOf' => get_class($this)
        ));
        $this->assertTrue($this->validator->validate($p, $this));
        $s = 'test';
        $this->assertTrue($this->validator->validate($p, $s));
    }

    public function testConvertsObjectsToArraysWhenToArrayInterface()
    {
        $o = $this->getMockBuilder('Guzzle\Common\ToArrayInterface')
            ->setMethods(array('toArray'))
            ->getMockForAbstractClass();
        $o->expects($this->once())
            ->method('toArray')
            ->will($this->returnValue(array(
                'foo' => 'bar'
            )));
        $p = new Parameter(array(
            'name'       => 'test',
            'type'       => 'object',
            'properties' => array(
                'foo' => array('required' => 'true')
            )
        ));
        $this->assertTrue($this->validator->validate($p, $o));
    }

    public function testMergesValidationErrorsInPropertiesWithParent()
    {
        $p = new Parameter(array(
            'name'       => 'foo',
            'type'       => 'object',
            'properties' => array(
                'bar'   => array('type' => 'string', 'required' => true, 'description' => 'This is what it does'),
                'test'  => array('type' => 'string', 'minLength' => 2, 'maxLength' => 5),
                'test2' => array('type' => 'string', 'minLength' => 2, 'maxLength' => 2),
                'test3' => array('type' => 'integer', 'minimum' => 100),
                'test4' => array('type' => 'integer', 'maximum' => 10),
                'test5' => array('type' => 'array', 'maxItems' => 2),
                'test6' => array('type' => 'string', 'enum' => array('a', 'bc')),
                'test7' => array('type' => 'string', 'pattern' => '/[0-9]+/'),
                'test8' => array('type' => 'number'),
                'baz' => array(
                    'type'     => 'array',
                    'minItems' => 2,
                    'required' => true,
                    "items"    => array("type" => "string")
                )
            )
        ));

        $value = array(
            'test' => 'a',
            'test2' => 'abc',
            'baz' => array(false),
            'test3' => 10,
            'test4' => 100,
            'test5' => array(1, 3, 4),
            'test6' => 'Foo',
            'test7' => 'abc',
            'test8' => 'abc'
        );

        $this->assertFalse($this->validator->validate($p, $value));
        $this->assertEquals(array (
            '[foo][bar] is a required string: This is what it does',
            '[foo][baz] must contain 2 or more elements',
            '[foo][baz][0] must be of type string',
            '[foo][test2] length must be less than or equal to 2',
            '[foo][test3] must be greater than or equal to 100',
            '[foo][test4] must be less than or equal to 10',
            '[foo][test5] must contain 2 or fewer elements',
            '[foo][test6] must be one of "a" or "bc"',
            '[foo][test7] must match the following regular expression: /[0-9]+/',
            '[foo][test8] must be of type number',
            '[foo][test] length must be greater than or equal to 2',
        ), $this->validator->getErrors());
    }

    public function testHandlesNullValuesInArraysWithDefaults()
    {
        $p = new Parameter(array(
            'name'       => 'foo',
            'type'       => 'object',
            'required'   => true,
            'properties' => array(
                'bar' => array(
                    'type' => 'object',
                    'required' => true,
                    'properties' => array(
                        'foo' => array('default' => 'hi')
                    )
                )
            )
        ));
        $value = array();
        $this->assertTrue($this->validator->validate($p, $value));
        $this->assertEquals(array('bar' => array('foo' => 'hi')), $value);
    }

    public function testFailsWhenNullValuesInArraysWithNoDefaults()
    {
        $p = new Parameter(array(
            'name'       => 'foo',
            'type'       => 'object',
            'required'   => true,
            'properties' => array(
                'bar' => array(
                    'type' => 'object',
                    'required' => true,
                    'properties' => array('foo' => array('type' => 'string'))
                )
            )
        ));
        $value = array();
        $this->assertFalse($this->validator->validate($p, $value));
        $this->assertEquals(array('[foo][bar] is a required object'), $this->validator->getErrors());
    }

    public function testChecksTypes()
    {
        $p = new SchemaValidator();
        $r = new \ReflectionMethod($p, 'determineType');
        $r->setAccessible(true);
        $this->assertEquals('any', $r->invoke($p, 'any', 'hello'));
        $this->assertEquals(false, $r->invoke($p, 'foo', 'foo'));
        $this->assertEquals('string', $r->invoke($p, 'string', 'hello'));
        $this->assertEquals(false, $r->invoke($p, 'string', false));
        $this->assertEquals('integer', $r->invoke($p, 'integer', 1));
        $this->assertEquals(false, $r->invoke($p, 'integer', 'abc'));
        $this->assertEquals('numeric', $r->invoke($p, 'numeric', 1));
        $this->assertEquals('numeric', $r->invoke($p, 'numeric', '1'));
        $this->assertEquals('number', $r->invoke($p, 'number', 1));
        $this->assertEquals('number', $r->invoke($p, 'number', '1'));
        $this->assertEquals(false, $r->invoke($p, 'numeric', 'a'));
        $this->assertEquals('boolean', $r->invoke($p, 'boolean', true));
        $this->assertEquals('boolean', $r->invoke($p, 'boolean', false));
        $this->assertEquals(false, $r->invoke($p, 'boolean', 'false'));
        $this->assertEquals('null', $r->invoke($p, 'null', null));
        $this->assertEquals(false, $r->invoke($p, 'null', 'abc'));
        $this->assertEquals('array', $r->invoke($p, 'array', array()));
        $this->assertEquals(false, $r->invoke($p, 'array', 'foo'));
    }

    public function testValidatesFalseAdditionalProperties()
    {
        $param = new Parameter(array(
            'name'      => 'foo',
            'type'      => 'object',
            'properties' => array('bar' => array('type' => 'string')),
            'additionalProperties' => false
        ));
        $value = array('test' => '123');
        $this->assertFalse($this->validator->validate($param, $value));
        $this->assertEquals(array('[foo][test] is not an allowed property'), $this->validator->getErrors());
        $value = array('bar' => '123');
        $this->assertTrue($this->validator->validate($param, $value));
    }

    public function testAllowsUndefinedAdditionalProperties()
    {
        $param = new Parameter(array(
            'name'      => 'foo',
            'type'      => 'object',
            'properties' => array('bar' => array('type' => 'string'))
        ));
        $value = array('test' => '123');
        $this->assertTrue($this->validator->validate($param, $value));
    }

    public function testValidatesAdditionalProperties()
    {
        $param = new Parameter(array(
            'name'      => 'foo',
            'type'      => 'object',
            'properties' => array('bar' => array('type' => 'string')),
            'additionalProperties' => array('type' => 'integer')
        ));
        $value = array('test' => 'foo');
        $this->assertFalse($this->validator->validate($param, $value));
        $this->assertEquals(array('[foo][test] must be of type integer'), $this->validator->getErrors());
    }

    public function testValidatesAdditionalPropertiesThatArrayArrays()
    {
        $param = new Parameter(array(
            'name' => 'foo',
            'type' => 'object',
            'additionalProperties' => array(
                'type'  => 'array',
                'items' => array('type' => 'string')
            )
        ));
        $value = array('test' => array(true));
        $this->assertFalse($this->validator->validate($param, $value));
        $this->assertEquals(array('[foo][test][0] must be of type string'), $this->validator->getErrors());
    }

    public function testIntegersCastToStringWhenTypeMismatch()
    {
        $param = new Parameter(array('name' => 'test', 'type' => 'string'));
        $value = 12;
        $this->assertTrue($this->validator->validate($param, $value));
        $this->assertEquals('12', $value);
    }

    public function testRequiredMessageIncludesType()
    {
        $param = new Parameter(array('name' => 'test', 'type' => array('string', 'boolean'), 'required' => true));
        $value = null;
        $this->assertFalse($this->validator->validate($param, $value));
        $this->assertEquals(array('[test] is a required string or boolean'), $this->validator->getErrors());
    }

    protected function getComplexParam()
    {
        return new Parameter(array(
            'name'     => 'Foo',
            'type'     => 'array',
            'required' => true,
            'min'      => 1,
            'items'    => array(
                'type'       => 'object',
                'properties' => array(
                    'Baz' => array(
                        'type'    => 'string',
                    ),
                    'Bar' => array(
                        'required' => true,
                        'type'     => 'boolean',
                        'default'  => true
                    )
                )
            )
        ));
    }
}
<?php

namespace Guzzle\Tests\Service\Description;

use Guzzle\Service\Description\SchemaFormatter;

/**
 * @covers Guzzle\Service\Description\SchemaFormatter
 */
class SchemaFormatterTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function dateTimeProvider()
    {
        $dateUtc = 'October 13, 2012 16:15:46 UTC';
        $dateOffset = 'October 13, 2012 10:15:46 -06:00';
        $expectedDateTime = '2012-10-13T16:15:46Z';

        return array(
            array('foo', 'does-not-exist', 'foo'),
            array($dateUtc, 'date-time', $expectedDateTime),
            array($dateUtc, 'date-time-http', 'Sat, 13 Oct 2012 16:15:46 GMT'),
            array($dateUtc, 'date', '2012-10-13'),
            array($dateUtc, 'timestamp', strtotime($dateUtc)),
            array(new \DateTime($dateUtc), 'timestamp', strtotime($dateUtc)),
            array($dateUtc, 'time', '16:15:46'),
            array(strtotime($dateUtc), 'time', '16:15:46'),
            array(strtotime($dateUtc), 'timestamp', strtotime($dateUtc)),
            array('true', 'boolean-string', 'true'),
            array(true, 'boolean-string', 'true'),
            array('false', 'boolean-string', 'false'),
            array(false, 'boolean-string', 'false'),
            array('1350144946', 'date-time', $expectedDateTime),
            array(1350144946, 'date-time', $expectedDateTime),
            array($dateOffset, 'date-time', $expectedDateTime)
        );
    }

    /**
     * @dataProvider dateTimeProvider
     */
    public function testFilters($value, $format, $result)
    {
        $this->assertEquals($result, SchemaFormatter::format($format, $value));
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesDateTimeInput()
    {
        SchemaFormatter::format('date-time', false);
    }

    public function testEnsuresTimestampsAreIntegers()
    {
        $t = time();
        $result = SchemaFormatter::format('timestamp', $t);
        $this->assertSame($t, $result);
        $this->assertInternalType('int', $result);
    }
}
<?php

namespace Guzzle\Tests\Service;

/**
 * @covers Guzzle\Service\AbstractConfigLoader
 */
class AbstractConfigLoaderTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var \Guzzle\Service\AbstractConfigLoader */
    protected $loader;

    /** @var array Any files that need to be deleted on tear down */
    protected $cleanup = array();

    public function setUp()
    {
        $this->loader = $this->getMockBuilder('Guzzle\Service\AbstractConfigLoader')
            ->setMethods(array('build'))
            ->getMockForAbstractClass();
    }

    public function tearDown()
    {
        foreach ($this->cleanup as $file) {
            unlink($file);
        }
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testOnlyLoadsSupportedTypes()
    {
        $this->loader->load(new \stdClass());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     * @expectedExceptionMessage Unable to open fooooooo.json
     */
    public function testFileMustBeReadable()
    {
        $this->loader->load('fooooooo.json');
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     * @expectedExceptionMessage Unknown file extension
     */
    public function testMustBeSupportedExtension()
    {
        $this->loader->load(dirname(__DIR__) . '/TestData/FileBody.txt');
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     * @expectedExceptionMessage Error loading JSON data from
     */
    public function testJsonMustBeValue()
    {
        $filename = tempnam(sys_get_temp_dir(), 'json') . '.json';
        file_put_contents($filename, '{/{./{}foo');
        $this->cleanup[] = $filename;
        $this->loader->load($filename);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     * @expectedExceptionMessage PHP files must return an array
     */
    public function testPhpFilesMustReturnAnArray()
    {
        $filename = tempnam(sys_get_temp_dir(), 'php') . '.php';
        file_put_contents($filename, '<?php $fdr = false;');
        $this->cleanup[] = $filename;
        $this->loader->load($filename);
    }

    public function testLoadsPhpFileIncludes()
    {
        $filename = tempnam(sys_get_temp_dir(), 'php') . '.php';
        file_put_contents($filename, '<?php return array("foo" => "bar");');
        $this->cleanup[] = $filename;
        $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0));
        $config = $this->loader->load($filename);
        $this->assertEquals(array('foo' => 'bar'), $config);
    }

    public function testCanCreateFromJson()
    {
        $file = dirname(__DIR__) . '/TestData/services/json1.json';
        // The build method will just return the config data
        $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0));
        $data = $this->loader->load($file);
        // Ensure that the config files were merged using the includes directives
        $this->assertArrayHasKey('includes', $data);
        $this->assertArrayHasKey('services', $data);
        $this->assertInternalType('array', $data['services']['foo']);
        $this->assertInternalType('array', $data['services']['abstract']);
        $this->assertInternalType('array', $data['services']['mock']);
        $this->assertEquals('bar', $data['services']['foo']['params']['baz']);
    }

    public function testUsesAliases()
    {
        $file = dirname(__DIR__) . '/TestData/services/json1.json';
        $this->loader->addAlias('foo', $file);
        // The build method will just return the config data
        $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0));
        $data = $this->loader->load('foo');
        $this->assertEquals('bar', $data['services']['foo']['params']['baz']);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     * @expectedExceptionMessage Unable to open foo.json
     */
    public function testCanRemoveAliases()
    {
        $file = dirname(__DIR__) . '/TestData/services/json1.json';
        $this->loader->addAlias('foo.json', $file);
        $this->loader->removeAlias('foo.json');
        $this->loader->load('foo.json');
    }

    public function testCanLoadArraysWithIncludes()
    {
        $file = dirname(__DIR__) . '/TestData/services/json1.json';
        $config = array('includes' => array($file));
        // The build method will just return the config data
        $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0));
        $data = $this->loader->load($config);
        $this->assertEquals('bar', $data['services']['foo']['params']['baz']);
    }

    public function testDoesNotEnterInfiniteLoop()
    {
        $prefix = $file = dirname(__DIR__) . '/TestData/description';
        $this->loader->load("{$prefix}/baz.json");
        $this->assertCount(4, $this->readAttribute($this->loader, 'loadedFiles'));
        // Ensure that the internal list of loaded files is reset
        $this->loader->load("{$prefix}/../test_service2.json");
        $this->assertCount(1, $this->readAttribute($this->loader, 'loadedFiles'));
        // Ensure that previously loaded files will be reloaded when starting fresh
        $this->loader->load("{$prefix}/baz.json");
        $this->assertCount(4, $this->readAttribute($this->loader, 'loadedFiles'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Client;
use Guzzle\Service\Command\AbstractCommand;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\SchemaValidator;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Tests\Service\Mock\Command\MockCommand;
use Guzzle\Tests\Service\Mock\Command\Sub\Sub;

/**
 * @covers Guzzle\Service\Command\AbstractCommand
 */
class CommandTest extends AbstractCommandTest
{
    public function testConstructorAddsDefaultParams()
    {
        $command = new MockCommand();
        $this->assertEquals('123', $command->get('test'));
        $this->assertFalse($command->isPrepared());
        $this->assertFalse($command->isExecuted());
    }

    public function testDeterminesShortName()
    {
        $api = new Operation(array('name' => 'foobar'));
        $command = new MockCommand(array(), $api);
        $this->assertEquals('foobar', $command->getName());

        $command = new MockCommand();
        $this->assertEquals('mock_command', $command->getName());

        $command = new Sub();
        $this->assertEquals('sub.sub', $command->getName());
    }

    /**
     * @expectedException RuntimeException
     */
    public function testGetRequestThrowsExceptionBeforePreparation()
    {
        $command = new MockCommand();
        $command->getRequest();
    }

    public function testGetResponseExecutesCommandsWhenNeeded()
    {
        $response = new Response(200);
        $client = $this->getClient();
        $this->setMockResponse($client, array($response));
        $command = new MockCommand();
        $command->setClient($client);
        $this->assertSame($response, $command->getResponse());
        $this->assertSame($response, $command->getResponse());
    }

    public function testGetResultExecutesCommandsWhenNeeded()
    {
        $response = new Response(200);
        $client = $this->getClient();
        $this->setMockResponse($client, array($response));
        $command = new MockCommand();
        $command->setClient($client);
        $this->assertSame($response, $command->getResult());
        $this->assertSame($response, $command->getResult());
    }

    public function testSetClient()
    {
        $command = new MockCommand();
        $client = $this->getClient();

        $command->setClient($client);
        $this->assertEquals($client, $command->getClient());

        unset($client);
        unset($command);

        $command = new MockCommand();
        $client = $this->getClient();

        $command->setClient($client)->prepare();
        $this->assertEquals($client, $command->getClient());
        $this->assertTrue($command->isPrepared());
    }

    public function testExecute()
    {
        $client = $this->getClient();
        $response = new Response(200, array(
            'Content-Type' => 'application/xml'
        ), '<xml><data>123</data></xml>');
        $this->setMockResponse($client, array($response));
        $command = new MockCommand();
        $this->assertSame($command, $command->setClient($client));

        // Returns the result of the command
        $this->assertInstanceOf('SimpleXMLElement', $command->execute());

        $this->assertTrue($command->isPrepared());
        $this->assertTrue($command->isExecuted());
        $this->assertSame($response, $command->getResponse());
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Request', $command->getRequest());
        // Make sure that the result was automatically set to a SimpleXMLElement
        $this->assertInstanceOf('SimpleXMLElement', $command->getResult());
        $this->assertEquals('123', (string) $command->getResult()->data);
    }

    public function testConvertsJsonResponsesToArray()
    {
        $client = $this->getClient();
        $this->setMockResponse($client, array(
            new \Guzzle\Http\Message\Response(200, array(
                'Content-Type' => 'application/json'
                ), '{ "key": "Hi!" }'
            )
        ));
        $command = new MockCommand();
        $command->setClient($client);
        $command->execute();
        $this->assertEquals(array(
            'key' => 'Hi!'
        ), $command->getResult());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     */
    public function testConvertsInvalidJsonResponsesToArray()
    {
        $json = '{ "key": "Hi!" }invalid';
        // Some implementations of php-json extension are not strict enough
        // and allow to parse invalid json ignoring invalid parts
        // See https://github.com/remicollet/pecl-json-c/issues/5
        if (json_decode($json) && JSON_ERROR_NONE === json_last_error()) {
            $this->markTestSkipped('php-pecl-json library regression issues');
        }

        $client = $this->getClient();
        $this->setMockResponse($client, array(
            new \Guzzle\Http\Message\Response(200, array(
                'Content-Type' => 'application/json'
                ), $json
            )
        ));
        $command = new MockCommand();
        $command->setClient($client);
        $command->execute();
    }

    public function testProcessResponseIsNotXml()
    {
        $client = $this->getClient();
        $this->setMockResponse($client, array(
            new Response(200, array(
                'Content-Type' => 'application/octet-stream'
            ), 'abc,def,ghi')
        ));
        $command = new MockCommand();
        $client->execute($command);

        // Make sure that the result was not converted to XML
        $this->assertFalse($command->getResult() instanceof \SimpleXMLElement);
    }

    /**
     * @expectedException RuntimeException
     */
    public function testExecuteThrowsExceptionWhenNoClientIsSet()
    {
        $command = new MockCommand();
        $command->execute();
    }

    /**
     * @expectedException RuntimeException
     */
    public function testPrepareThrowsExceptionWhenNoClientIsSet()
    {
        $command = new MockCommand();
        $command->prepare();
    }

    public function testCommandsAllowsCustomRequestHeaders()
    {
        $command = new MockCommand();
        $command->getRequestHeaders()->set('test', '123');
        $this->assertInstanceOf('Guzzle\Common\Collection', $command->getRequestHeaders());
        $this->assertEquals('123', $command->getRequestHeaders()->get('test'));

        $command->setClient($this->getClient())->prepare();
        $this->assertEquals('123', (string) $command->getRequest()->getHeader('test'));
    }

    public function testCommandsAllowsCustomRequestHeadersAsArray()
    {
        $command = new MockCommand(array(AbstractCommand::HEADERS_OPTION => array('Foo' => 'Bar')));
        $this->assertInstanceOf('Guzzle\Common\Collection', $command->getRequestHeaders());
        $this->assertEquals('Bar', $command->getRequestHeaders()->get('Foo'));
    }

    private function getOperation()
    {
        return new Operation(array(
            'name'       => 'foobar',
            'httpMethod' => 'POST',
            'class'      => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand',
            'parameters' => array(
                'test' => array(
                    'default' => '123',
                    'type'    => 'string'
                )
        )));
    }

    public function testCommandsUsesOperation()
    {
        $api = $this->getOperation();
        $command = new MockCommand(array(), $api);
        $this->assertSame($api, $command->getOperation());
        $command->setClient($this->getClient())->prepare();
        $this->assertEquals('123', $command->get('test'));
        $this->assertSame($api, $command->getOperation($api));
    }

    public function testCloneMakesNewRequest()
    {
        $client = $this->getClient();
        $command = new MockCommand(array(), $this->getOperation());
        $command->setClient($client);

        $command->prepare();
        $this->assertTrue($command->isPrepared());

        $command2 = clone $command;
        $this->assertFalse($command2->isPrepared());
    }

    public function testHasOnCompleteMethod()
    {
        $that = $this;
        $called = 0;

        $testFunction = function($command) use (&$called, $that) {
            $called++;
            $that->assertInstanceOf('Guzzle\Service\Command\CommandInterface', $command);
        };

        $client = $this->getClient();
        $command = new MockCommand(array(
            'command.on_complete' => $testFunction
        ), $this->getOperation());
        $command->setClient($client);

        $command->prepare()->setResponse(new Response(200), true);
        $command->execute();
        $this->assertEquals(1, $called);
    }

    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testOnCompleteMustBeCallable()
    {
        $client = $this->getClient();
        $command = new MockCommand();
        $command->setOnComplete('foo');
    }

    public function testCanSetResultManually()
    {
        $client = $this->getClient();
        $client->getEventDispatcher()->addSubscriber(new MockPlugin(array(
            new Response(200)
        )));
        $command = new MockCommand();
        $client->execute($command);
        $command->setResult('foo!');
        $this->assertEquals('foo!', $command->getResult());
    }

    public function testCanInitConfig()
    {
        $command = $this->getMockBuilder('Guzzle\\Service\\Command\\AbstractCommand')
            ->setConstructorArgs(array(array(
                'foo' => 'bar'
            ), new Operation(array(
                'parameters' => array(
                    'baz' => new Parameter(array(
                        'default' => 'baaar'
                    ))
                )
            ))))
            ->getMockForAbstractClass();

        $this->assertEquals('bar', $command['foo']);
        $this->assertEquals('baaar', $command['baz']);
    }

    public function testAddsCurlOptionsToRequestsWhenPreparing()
    {
        $command = new MockCommand(array(
            'foo' => 'bar',
            'curl.options' => array('CURLOPT_PROXYPORT' => 8080)
        ));
        $client = new Client();
        $command->setClient($client);
        $request = $command->prepare();
        $this->assertEquals(8080, $request->getCurlOptions()->get(CURLOPT_PROXYPORT));
    }

    public function testIsInvokable()
    {
        $client = $this->getClient();
        $response = new Response(200);
        $this->setMockResponse($client, array($response));
        $command = new MockCommand();
        $command->setClient($client);
        // Returns the result of the command
        $this->assertSame($response, $command());
    }

    public function testCreatesDefaultOperation()
    {
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')->getMockForAbstractClass();
        $this->assertInstanceOf('Guzzle\Service\Description\Operation', $command->getOperation());
    }

    public function testAllowsValidatorToBeInjected()
    {
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')->getMockForAbstractClass();
        $v = new SchemaValidator();
        $command->setValidator($v);
        $this->assertSame($v, $this->readAttribute($command, 'validator'));
    }

    public function testCanDisableValidation()
    {
        $command = new MockCommand();
        $command->setClient(new \Guzzle\Service\Client());
        $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator')
            ->setMethods(array('validate'))
            ->getMock();
        $v->expects($this->never())->method('validate');
        $command->setValidator($v);
        $command->set(AbstractCommand::DISABLE_VALIDATION, true);
        $command->prepare();
    }

    public function testValidatorDoesNotUpdateNonDefaultValues()
    {
        $command = new MockCommand(array('test' => 123, 'foo' => 'bar'));
        $command->setClient(new \Guzzle\Service\Client());
        $command->prepare();
        $this->assertEquals(123, $command->get('test'));
        $this->assertEquals('bar', $command->get('foo'));
    }

    public function testValidatorUpdatesDefaultValues()
    {
        $command = new MockCommand();
        $command->setClient(new \Guzzle\Service\Client());
        $command->prepare();
        $this->assertEquals(123, $command->get('test'));
        $this->assertEquals('abc', $command->get('_internal'));
    }

    /**
     * @expectedException \Guzzle\Service\Exception\ValidationException
     * @expectedExceptionMessage [Foo] Baz
     */
    public function testValidatesCommandBeforeSending()
    {
        $command = new MockCommand();
        $command->setClient(new \Guzzle\Service\Client());
        $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator')
            ->setMethods(array('validate', 'getErrors'))
            ->getMock();
        $v->expects($this->any())->method('validate')->will($this->returnValue(false));
        $v->expects($this->any())->method('getErrors')->will($this->returnValue(array('[Foo] Baz', '[Bar] Boo')));
        $command->setValidator($v);
        $command->prepare();
    }

    /**
     * @expectedException \Guzzle\Service\Exception\ValidationException
     * @expectedExceptionMessage Validation errors: [abc] must be of type string
     */
    public function testValidatesAdditionalParameters()
    {
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'foo' => array(
                    'parameters' => array(
                        'baz' => array('type' => 'integer')
                    ),
                    'additionalParameters' => array(
                        'type' => 'string'
                    )
                )
            )
        ));

        $client = new Client();
        $client->setDescription($description);
        $command = $client->getCommand('foo', array(
            'abc'             => false,
            'command.headers' => array('foo' => 'bar')
        ));
        $command->prepare();
    }

    public function testCanAccessValidationErrorsFromCommand()
    {
        $validationErrors = array('[Foo] Baz', '[Bar] Boo');
        $command = new MockCommand();
        $command->setClient(new \Guzzle\Service\Client());

        $this->assertFalse($command->getValidationErrors());

        $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator')
            ->setMethods(array('validate', 'getErrors'))
            ->getMock();
        $v->expects($this->any())->method('getErrors')->will($this->returnValue($validationErrors));
        $command->setValidator($v);

        $this->assertEquals($validationErrors, $command->getValidationErrors());
    }

    public function testCanChangeResponseBody()
    {
        $body = EntityBody::factory();
        $command = new MockCommand();
        $command->setClient(new \Guzzle\Service\Client());
        $command->set(AbstractCommand::RESPONSE_BODY, $body);
        $request = $command->prepare();
        $this->assertSame($body, $this->readAttribute($request, 'responseBody'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Command\DefaultRequestSerializer;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor;
use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;

/**
 * @covers Guzzle\Service\Command\DefaultRequestSerializer
 */
class DefaultRequestSerializerTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var EntityEnclosingRequest */
    protected $request;

    /** @var \Guzzle\Service\Command\AbstractCommand */
    protected $command;

    /** @var Client */
    protected $client;

    /** @var DefaultRequestSerializer */
    protected $serializer;

    /** @var Operation */
    protected $operation;

    public function setUp()
    {
        $this->serializer = DefaultRequestSerializer::getInstance();
        $this->client = new Client('http://foo.com/baz');
        $this->operation = new Operation(array('httpMethod' => 'POST'));
        $this->command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')
            ->setConstructorArgs(array(array(), $this->operation))
            ->getMockForAbstractClass();
        $this->command->setClient($this->client);
    }

    public function testAllowsCustomVisitor()
    {
        $this->serializer->addVisitor('custom', new HeaderVisitor());
        $this->command['test'] = '123';
        $this->operation->addParam(new Parameter(array('name' => 'test', 'location' => 'custom')));
        $request = $this->serializer->prepare($this->command);
        $this->assertEquals('123', (string) $request->getHeader('test'));
    }

    public function testUsesRelativePath()
    {
        $this->operation->setUri('bar');
        $request = $this->serializer->prepare($this->command);
        $this->assertEquals('http://foo.com/baz/bar', (string) $request->getUrl());
    }

    public function testUsesRelativePathWithUriLocations()
    {
        $this->command['test'] = '123';
        $this->operation->setUri('bar/{test}');
        $this->operation->addParam(new Parameter(array('name' => 'test', 'location' => 'uri')));
        $request = $this->serializer->prepare($this->command);
        $this->assertEquals('http://foo.com/baz/bar/123', (string) $request->getUrl());
    }

    public function testAllowsCustomFactory()
    {
        $f = new VisitorFlyweight();
        $serializer = new DefaultRequestSerializer($f);
        $this->assertSame($f, $this->readAttribute($serializer, 'factory'));
    }

    public function testMixedParams()
    {
        $this->operation->setUri('bar{?limit,fields}');
        $this->operation->addParam(new Parameter(array(
            'name' => 'limit',
            'location' => 'uri',
            'required' => false,
        )));
        $this->operation->addParam(new Parameter(array(
            'name' => 'fields',
            'location' => 'uri',
            'required' => true,
        )));

        $this->command['fields'] = array('id', 'name');

        $request = $this->serializer->prepare($this->command);
        $this->assertEquals('http://foo.com/baz/bar?fields='.urlencode('id,name'), (string) $request->getUrl());
    }

    public function testValidatesAdditionalParameters()
    {
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'foo' => array(
                    'httpMethod' => 'PUT',
                    'parameters' => array(
                        'bar' => array('location' => 'header')
                    ),
                    'additionalParameters' => array(
                        'location' => 'json'
                    )
                )
            )
        ));

        $client = new Client();
        $client->setDescription($description);
        $command = $client->getCommand('foo');
        $command['bar'] = 'test';
        $command['hello'] = 'abc';
        $request = $command->prepare();
        $this->assertEquals('test', (string) $request->getHeader('bar'));
        $this->assertEquals('{"hello":"abc"}', (string) $request->getBody());
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Client;
use Guzzle\Service\Command\OperationResponseParser;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor;
use Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor;
use Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor;
use Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor;
use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;

/**
 * @covers Guzzle\Service\Command\OperationResponseParser
 * @covers Guzzle\Service\Command\CreateResponseClassEvent
 */
class OperationResponseParserTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testHasVisitors()
    {
        $p = new OperationResponseParser(new VisitorFlyweight(array()));
        $visitor = new BodyVisitor();
        $p->addVisitor('foo', $visitor);
        $this->assertSame($visitor, $this->readAttribute($p, 'factory')->getResponseVisitor('foo'));
    }

    public function testUsesParentParser()
    {
        $p = new OperationResponseParser(new VisitorFlyweight());
        $operation = new Operation();
        $operation->setServiceDescription(new ServiceDescription());
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($p)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/xml'), '<F><B>C</B></F>'), true);
        $this->assertInstanceOf('SimpleXMLElement', $op->execute());
    }

    public function testVisitsLocations()
    {
        $parser = new OperationResponseParser(new VisitorFlyweight(array()));
        $parser->addVisitor('statusCode', new StatusCodeVisitor());
        $parser->addVisitor('reasonPhrase', new ReasonPhraseVisitor());
        $parser->addVisitor('json', new JsonVisitor());
        $op = new OperationCommand(array(), $this->getDescription()->getOperation('test'));
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(201), true);
        $result = $op->execute();
        $this->assertEquals(201, $result['code']);
        $this->assertEquals('Created', $result['phrase']);
    }

    public function testVisitsLocationsForJsonResponse()
    {
        $parser = OperationResponseParser::getInstance();
        $operation = $this->getDescription()->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array(
            'Content-Type' => 'application/json'
        ), '{"baz":"bar","enigma":"123"}'), true);
        $result = $op->execute();
        $this->assertEquals(array(
            'baz'    => 'bar',
            'enigma' => '123',
            'code'   => 200,
            'phrase' => 'OK'
        ), $result->toArray());
    }

    public function testSkipsUnkownModels()
    {
        $parser = OperationResponseParser::getInstance();
        $operation = $this->getDescription()->getOperation('test');
        $operation->setResponseClass('Baz')->setResponseType('model');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(201), true);
        $this->assertInstanceOf('Guzzle\Http\Message\Response', $op->execute());
    }

    public function testAllowsModelProcessingToBeDisabled()
    {
        $parser = OperationResponseParser::getInstance();
        $operation = $this->getDescription()->getOperation('test');
        $op = new OperationCommand(array('command.response_processing' => 'native'), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array(
            'Content-Type' => 'application/json'
        ), '{"baz":"bar","enigma":"123"}'), true);
        $result = $op->execute();
        $this->assertInstanceOf('Guzzle\Service\Resource\Model', $result);
        $this->assertEquals(array(
            'baz'    => 'bar',
            'enigma' => '123'
        ), $result->toArray());
    }

    public function testCanInjectModelSchemaIntoModels()
    {
        $parser = new OperationResponseParser(VisitorFlyweight::getInstance(), true);
        $desc = $this->getDescription();
        $operation = $desc->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array(
            'Content-Type' => 'application/json'
        ), '{"baz":"bar","enigma":"123"}'), true);
        $result = $op->execute();
        $this->assertSame($result->getStructure(), $desc->getModel('Foo'));
    }

    public function testDoesNotParseXmlWhenNotUsingXmlVisitor()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo')),
            'models' => array(
                'Foo' => array(
                    'type'       => 'object',
                    'properties' => array('baz' => array('location' => 'body'))
                )
            )
        ));
        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $brokenXml = '<broken><><><<xml>>>>>';
        $op->prepare()->setResponse(new Response(200, array(
            'Content-Type' => 'application/xml'
        ), $brokenXml), true);
        $result = $op->execute();
        $this->assertEquals(array('baz'), $result->getKeys());
        $this->assertEquals($brokenXml, (string) $result['baz']);
    }

    public function testVisitsAdditionalProperties()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo')),
            'models' => array(
                'Foo' => array(
                    'type' => 'object',
                    'properties' => array(
                        'code' => array('location' => 'statusCode')
                    ),
                    'additionalProperties' => array(
                        'location' => 'json',
                        'type' => 'object',
                        'properties' => array(
                            'a' => array(
                                'type' => 'string',
                                'filters' => 'strtoupper'
                            )
                        )
                    )
                )
            )
        ));

        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $json = '[{"a":"test"},{"a":"baz"}]';
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true);
        $result = $op->execute()->toArray();
        $this->assertEquals(array(
            'code' => 200,
            array('a' => 'TEST'),
            array('a' => 'BAZ')
        ), $result);
    }

    /**
     * @group issue-399
     * @link https://github.com/guzzle/guzzle/issues/399
     */
    public function testAdditionalPropertiesDisabledDiscardsData()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo')),
            'models'     => array(
                'Foo' => array(
                    'type'       => 'object',
                    'additionalProperties' => false,
                    'properties' => array(
                        'name'   => array(
                            'location' => 'json',
                            'type'     => 'string',
                        ),
                        'nested' => array(
                            'location'             => 'json',
                            'type'                 => 'object',
                            'additionalProperties' => false,
                            'properties'           => array(
                                'width' => array(
                                    'type' => 'integer'
                                )
                            ),
                        ),
                        'code'   => array('location' => 'statusCode')
                    ),

                )
            )
        ));

        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $json = '{"name":"test", "volume":2.0, "nested":{"width":10,"bogus":1}}';
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true);
        $result = $op->execute()->toArray();
        $this->assertEquals(array(
            'name' => 'test',
            'nested' => array(
                'width' => 10,
            ),
            'code' => 200
        ), $result);
    }

    public function testCreatesCustomResponseClassInterface()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Guzzle\Tests\Mock\CustomResponseModel'))
        ));
        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true);
        $result = $op->execute();
        $this->assertInstanceOf('Guzzle\Tests\Mock\CustomResponseModel', $result);
        $this->assertSame($op, $result->command);
    }

    /**
     * @expectedException \Guzzle\Service\Exception\ResponseClassException
     * @expectedExceptionMessage must exist
     */
    public function testEnsuresResponseClassExists()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo\Baz\Bar'))
        ));
        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true);
        $op->execute();
    }

    /**
     * @expectedException \Guzzle\Service\Exception\ResponseClassException
     * @expectedExceptionMessage and implement
     */
    public function testEnsuresResponseClassImplementsResponseClassInterface()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => __CLASS__))
        ));
        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true);
        $op->execute();
    }

    protected function getDescription()
    {
        return ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo')),
            'models' => array(
                'Foo' => array(
                    'type'       => 'object',
                    'properties' => array(
                        'baz'    => array('type' => 'string', 'location' => 'json'),
                        'code'   => array('location' => 'statusCode'),
                        'phrase' => array('location' => 'reasonPhrase'),
                    )
                )
            )
        ));
    }

    public function testCanAddListenerToParseDomainObjects()
    {
        $client = new Client();
        $client->setDescription(ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'FooBazBar'))
        )));
        $foo = new \stdClass();
        $client->getEventDispatcher()->addListener('command.parse_response', function ($e) use ($foo) {
             $e['result'] = $foo;
        });
        $command = $client->getCommand('test');
        $command->prepare()->setResponse(new Response(200), true);
        $result = $command->execute();
        $this->assertSame($result, $foo);
    }

    /**
     * @group issue-399
     * @link https://github.com/guzzle/guzzle/issues/501
     */
    public function testAdditionalPropertiesWithRefAreResolved()
    {
        $parser = OperationResponseParser::getInstance();
        $description = ServiceDescription::factory(array(
            'operations' => array('test' => array('responseClass' => 'Foo')),
            'models'     => array(
                'Baz' => array('type' => 'string'),
                'Foo' => array(
                    'type' => 'object',
                    'additionalProperties' => array('$ref' => 'Baz', 'location' => 'json')
                )
            )
        ));
        $operation = $description->getOperation('test');
        $op = new OperationCommand(array(), $operation);
        $op->setResponseParser($parser)->setClient(new Client());
        $json = '{"a":"a","b":"b","c":"c"}';
        $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true);
        $result = $op->execute()->toArray();
        $this->assertEquals(array('a' => 'a', 'b' => 'b', 'c' => 'c'), $result);
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Client;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Command\DefaultRequestSerializer;
use Guzzle\Service\Resource\Model;
use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;

/**
 * @covers Guzzle\Service\Command\OperationCommand
 */
class OperationCommandTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testHasRequestSerializer()
    {
        $operation = new OperationCommand();
        $a = $operation->getRequestSerializer();
        $b = new DefaultRequestSerializer(VisitorFlyweight::getInstance());
        $operation->setRequestSerializer($b);
        $this->assertNotSame($a, $operation->getRequestSerializer());
    }

    public function testPreparesRequestUsingSerializer()
    {
        $op = new OperationCommand(array(), new Operation());
        $op->setClient(new Client());
        $s = $this->getMockBuilder('Guzzle\Service\Command\RequestSerializerInterface')
            ->setMethods(array('prepare'))
            ->getMockForAbstractClass();
        $s->expects($this->once())
            ->method('prepare')
            ->will($this->returnValue(new EntityEnclosingRequest('POST', 'http://foo.com')));
        $op->setRequestSerializer($s);
        $op->prepare();
    }

    public function testParsesResponsesWithResponseParser()
    {
        $op = new OperationCommand(array(), new Operation());
        $p = $this->getMockBuilder('Guzzle\Service\Command\ResponseParserInterface')
            ->setMethods(array('parse'))
            ->getMockForAbstractClass();
        $p->expects($this->once())
            ->method('parse')
            ->will($this->returnValue(array('foo' => 'bar')));
        $op->setResponseParser($p);
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200), true);
        $this->assertEquals(array('foo' => 'bar'), $op->execute());
    }

    public function testParsesResponsesUsingModelParserWhenMatchingModelIsFound()
    {
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'foo' => array('responseClass' => 'bar', 'responseType' => 'model')
            ),
            'models' => array(
                'bar' => array(
                    'type' => 'object',
                    'properties' => array(
                        'Baz' => array('type' => 'string', 'location' => 'xml')
                    )
                )
            )
        ));

        $op = new OperationCommand(array(), $description->getOperation('foo'));
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200, array(
            'Content-Type' => 'application/xml'
        ), '<Foo><Baz>Bar</Baz></Foo>'), true);
        $result = $op->execute();
        $this->assertEquals(new Model(array('Baz' => 'Bar')), $result);
    }

    public function testAllowsRawResponses()
    {
        $description = new ServiceDescription(array(
            'operations' => array('foo' => array('responseClass' => 'bar', 'responseType' => 'model')),
            'models'     => array('bar' => array())
        ));
        $op = new OperationCommand(array(
            OperationCommand::RESPONSE_PROCESSING => OperationCommand::TYPE_RAW
        ), $description->getOperation('foo'));
        $op->setClient(new Client());
        $request = $op->prepare();
        $response = new Response(200, array(
            'Content-Type' => 'application/xml'
        ), '<Foo><Baz>Bar</Baz></Foo>');
        $request->setResponse($response, true);
        $this->assertSame($response, $op->execute());
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Client;
use Guzzle\Service\Command\DefaultResponseParser;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Description\Operation;

/**
 * @covers Guzzle\Service\Command\DefaultResponseParser
 */
class DefaultResponseParserTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testParsesXmlResponses()
    {
        $op = new OperationCommand(array(), new Operation());
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200, array(
            'Content-Type' => 'application/xml'
        ), '<Foo><Baz>Bar</Baz></Foo>'), true);
        $this->assertInstanceOf('SimpleXMLElement', $op->execute());
    }

    public function testParsesJsonResponses()
    {
        $op = new OperationCommand(array(), new Operation());
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200, array(
            'Content-Type' => 'application/json'
        ), '{"Baz":"Bar"}'), true);
        $this->assertEquals(array('Baz' => 'Bar'), $op->execute());
    }

    /**
     * @expectedException \Guzzle\Common\Exception\RuntimeException
     */
    public function testThrowsExceptionWhenParsingJsonFails()
    {
        $op = new OperationCommand(array(), new Operation());
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200, array('Content-Type' => 'application/json'), '{"Baz":ddw}'), true);
        $op->execute();
    }

    public function testAddsContentTypeWhenExpectsIsSetOnCommand()
    {
        $op = new OperationCommand(array(), new Operation());
        $op['command.expects'] = 'application/json';
        $op->setClient(new Client());
        $request = $op->prepare();
        $request->setResponse(new Response(200, null, '{"Baz":"Bar"}'), true);
        $this->assertEquals(array('Baz' => 'Bar'), $op->execute());
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

abstract class AbstractCommandTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getClient()
    {
        $client = new Client('http://www.google.com/');

        return $client->setDescription(ServiceDescription::factory(__DIR__ . '/../../TestData/test_service.json'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Http\Message\RequestFactory;
use Guzzle\Service\Command\ClosureCommand;
use Guzzle\Service\Client;

/**
 * @covers Guzzle\Service\Command\ClosureCommand
 */
class ClosureCommandTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage A closure must be passed in the parameters array
     */
    public function testConstructorValidatesClosure()
    {
        $c = new ClosureCommand();
    }

    public function testExecutesClosure()
    {
        $c = new ClosureCommand(array(
            'closure' => function($command, $api) {
                $command->set('testing', '123');
                $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
                return $request;
            }
        ));

        $client = $this->getServiceBuilder()->get('mock');
        $c->setClient($client)->prepare();
        $this->assertEquals('123', $c->get('testing'));
        $this->assertEquals('http://www.test.com/', $c->getRequest()->getUrl());
    }

    /**
     * @expectedException UnexpectedValueException
     * @expectedExceptionMessage Closure command did not return a RequestInterface object
     */
    public function testMustReturnRequest()
    {
        $c = new ClosureCommand(array(
            'closure' => function($command, $api) {
                return false;
            }
        ));

        $client = $this->getServiceBuilder()->get('mock');
        $c->setClient($client)->prepare();
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Tests\Service\Mock\MockClient;
use Guzzle\Service\Command\Factory\ConcreteClassFactory;

/**
 * @covers Guzzle\Service\Command\Factory\ConcreteClassFactory
 */
class ConcreteClassFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testProvider()
    {
        return array(
            array('foo', null, 'Guzzle\\Tests\\Service\\Mock\\Command\\'),
            array('mock_command', 'Guzzle\Tests\Service\Mock\Command\MockCommand', 'Guzzle\\Tests\\Service\\Mock\\Command\\'),
            array('other_command', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', 'Guzzle\\Tests\\Service\\Mock\\Command\\'),
            array('sub.sub', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', 'Guzzle\\Tests\\Service\\Mock\\Command\\'),
            array('sub.sub', null, 'Guzzle\\Foo\\'),
            array('foo', null, null),
            array('mock_command', 'Guzzle\Tests\Service\Mock\Command\MockCommand', null),
            array('other_command', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', null),
            array('sub.sub', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', null)
        );
    }

    /**
     * @dataProvider testProvider
     */
    public function testCreatesConcreteCommands($key, $result, $prefix)
    {
        if (!$prefix) {
            $client = new MockClient();
        } else {
            $client = new MockClient('', array(
                'command.prefix' => $prefix
            ));
        }

        $factory = new ConcreteClassFactory($client);

        if (is_null($result)) {
            $this->assertNull($factory->factory($key));
        } else {
            $this->assertInstanceof($result, $factory->factory($key));
        }
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Client;
use Guzzle\Service\Command\Factory\AliasFactory;
use Guzzle\Service\Command\Factory\MapFactory;
use Guzzle\Service\Command\Factory\CompositeFactory;

/**
 * @covers Guzzle\Service\Command\Factory\AliasFactory
 */
class AliasFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    private $factory;
    private $client;

    public function setup()
    {
        $this->client = new Client();

        $map = new MapFactory(array(
            'test'  => 'Guzzle\Tests\Service\Mock\Command\MockCommand',
            'test1' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand'
        ));

        $this->factory = new AliasFactory($this->client, array(
            'foo'      => 'test',
            'bar'      => 'sub',
            'sub'      => 'test1',
            'krull'    => 'test3',
            'krull_2'  => 'krull',
            'sub_2'    => 'bar',
            'bad_link' => 'jarjar'
        ));

        $map2 = new MapFactory(array(
            'test3'  => 'Guzzle\Tests\Service\Mock\Command\Sub\Sub'
        ));

        $this->client->setCommandFactory(new CompositeFactory(array($map, $this->factory, $map2)));
    }

    public function aliasProvider()
    {
        return array(
            array('foo', 'Guzzle\Tests\Service\Mock\Command\MockCommand', false),
            array('bar', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false),
            array('sub', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false),
            array('sub_2', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false),
            array('krull', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', false),
            array('krull_2', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', false),
            array('missing', null, true),
            array('bad_link', null, true)
        );
    }

    /**
     * @dataProvider aliasProvider
     */
    public function testAliasesCommands($key, $result, $exception)
    {
        try {
            $command = $this->client->getCommand($key);
            if (is_null($result)) {
                $this->assertNull($command);
            } else {
                $this->assertInstanceof($result, $command);
            }
        } catch (\Exception $e) {
            if (!$exception) {
                $this->fail('Got exception when it was not expected');
            }
        }
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Command\Factory\MapFactory;

/**
 * @covers Guzzle\Service\Command\Factory\MapFactory
 */
class MapFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function mapProvider()
    {
        return array(
            array('foo', null),
            array('test', 'Guzzle\Tests\Service\Mock\Command\MockCommand'),
            array('test1', 'Guzzle\Tests\Service\Mock\Command\OtherCommand')
        );
    }

    /**
     * @dataProvider mapProvider
     */
    public function testCreatesCommandsUsingMappings($key, $result)
    {
        $factory = new MapFactory(array(
            'test'  => 'Guzzle\Tests\Service\Mock\Command\MockCommand',
            'test1' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand'
        ));

        if (is_null($result)) {
            $this->assertNull($factory->factory($key));
        } else {
            $this->assertInstanceof($result, $factory->factory($key));
        }
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Command\Factory\ServiceDescriptionFactory;
use Guzzle\Inflection\Inflector;

/**
 * @covers Guzzle\Service\Command\Factory\ServiceDescriptionFactory
 */
class ServiceDescriptionFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testProvider()
    {
        return array(
            array('foo', null),
            array('jar_jar', 'Guzzle\Tests\Service\Mock\Command\MockCommand'),
            array('binks', 'Guzzle\Tests\Service\Mock\Command\OtherCommand')
        );
    }

    /**
     * @dataProvider testProvider
     */
    public function testCreatesCommandsUsingServiceDescriptions($key, $result)
    {
        $d = $this->getDescription();

        $factory = new ServiceDescriptionFactory($d);
        $this->assertSame($d, $factory->getServiceDescription());

        if (is_null($result)) {
            $this->assertNull($factory->factory($key));
        } else {
            $this->assertInstanceof($result, $factory->factory($key));
        }
    }

    public function testUsesUcFirstIfNoExactMatch()
    {
        $d = $this->getDescription();
        $factory = new ServiceDescriptionFactory($d, new Inflector());
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('Test'));
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('test'));
    }

    public function testUsesInflectionIfNoExactMatch()
    {
        $d = $this->getDescription();
        $factory = new ServiceDescriptionFactory($d, new Inflector());
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('Binks'));
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('binks'));
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\MockCommand', $factory->factory('JarJar'));
        $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\MockCommand', $factory->factory('jar_jar'));
    }

    protected function getDescription()
    {
        return ServiceDescription::factory(array(
            'operations' => array(
                'jar_jar' => array('class' => 'Guzzle\Tests\Service\Mock\Command\MockCommand'),
                'binks' => array('class' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand'),
                'Test' => array('class' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand')
            )
        ));
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Command\Factory\CompositeFactory;

/**
 * @covers Guzzle\Service\Command\Factory\CompositeFactory
 */
class CompositeFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    private function getFactory($class = 'Guzzle\\Service\\Command\\Factory\\MapFactory')
    {
        return $mock = $this->getMockBuilder($class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testIsIterable()
    {
        $factory = new CompositeFactory(array($this->getFactory(), $this->getFactory()));
        $this->assertEquals(2, count($factory));
        $this->assertEquals(2, count(iterator_to_array($factory->getIterator())));
    }

    public function testFindsFactories()
    {
        $f1 = $this->getFactory();
        $f2 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory');
        $factory = new CompositeFactory(array($f1, $f2));
        $this->assertNull($factory->find('foo'));
        $this->assertNull($factory->find($this->getFactory()));
        $this->assertSame($f1, $factory->find('Guzzle\\Service\\Command\\Factory\\MapFactory'));
        $this->assertSame($f2, $factory->find('Guzzle\\Service\\Command\\Factory\\CompositeFactory'));
        $this->assertSame($f1, $factory->find($f1));
        $this->assertSame($f2, $factory->find($f2));

        $this->assertFalse($factory->has('foo'));
        $this->assertTrue($factory->has('Guzzle\\Service\\Command\\Factory\\MapFactory'));
        $this->assertTrue($factory->has('Guzzle\\Service\\Command\\Factory\\CompositeFactory'));
    }

    public function testCreatesCommands()
    {
        $factory = new CompositeFactory();
        $this->assertNull($factory->factory('foo'));

        $f1 = $this->getFactory();
        $mockCommand1 = $this->getMockForAbstractClass('Guzzle\\Service\\Command\\AbstractCommand');

        $f1->expects($this->once())
           ->method('factory')
           ->with($this->equalTo('foo'))
           ->will($this->returnValue($mockCommand1));

        $factory = new CompositeFactory(array($f1));
        $this->assertSame($mockCommand1, $factory->factory('foo'));
    }

    public function testAllowsRemovalOfFactories()
    {
        $f1 = $this->getFactory();
        $f2 = $this->getFactory();
        $f3 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory');
        $factories = array($f1, $f2, $f3);
        $factory = new CompositeFactory($factories);

        $factory->remove('foo');
        $this->assertEquals($factories, $factory->getIterator()->getArrayCopy());

        $factory->remove($f1);
        $this->assertEquals(array($f2, $f3), $factory->getIterator()->getArrayCopy());

        $factory->remove('Guzzle\\Service\\Command\\Factory\\MapFactory');
        $this->assertEquals(array($f3), $factory->getIterator()->getArrayCopy());

        $factory->remove('Guzzle\\Service\\Command\\Factory\\CompositeFactory');
        $this->assertEquals(array(), $factory->getIterator()->getArrayCopy());

        $factory->remove('foo');
        $this->assertEquals(array(), $factory->getIterator()->getArrayCopy());
    }

    public function testAddsFactoriesBeforeAndAtEnd()
    {
        $f1 = $this->getFactory();
        $f2 = $this->getFactory();
        $f3 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory');
        $f4 = $this->getFactory();

        $factory = new CompositeFactory();

        $factory->add($f1);
        $this->assertEquals(array($f1), $factory->getIterator()->getArrayCopy());

        $factory->add($f2);
        $this->assertEquals(array($f1, $f2), $factory->getIterator()->getArrayCopy());

        $factory->add($f3, $f2);
        $this->assertEquals(array($f1, $f3, $f2), $factory->getIterator()->getArrayCopy());

        $factory->add($f4, 'Guzzle\\Service\\Command\\Factory\\CompositeFactory');
        $this->assertEquals(array($f1, $f4, $f3, $f2), $factory->getIterator()->getArrayCopy());
    }

    public function testProvidesDefaultChainForClients()
    {
        $client = $this->getMock('Guzzle\\Service\\Client');
        $chain = CompositeFactory::getDefaultChain($client);
        $a = $chain->getIterator()->getArrayCopy();
        $this->assertEquals(1, count($a));
        $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory', $a[0]);

        $description = $this->getMock('Guzzle\\Service\\Description\\ServiceDescription');
        $client->expects($this->once())
               ->method('getDescription')
               ->will($this->returnValue($description));
        $chain = CompositeFactory::getDefaultChain($client);
        $a = $chain->getIterator()->getArrayCopy();
        $this->assertEquals(2, count($a));
        $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ServiceDescriptionFactory', $a[0]);
        $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory', $a[1]);
    }
}
<?php

namespace Guzzle\Tests\Service\Command;

use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;
use Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor as JsonRequestVisitor;
use Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor as JsonResponseVisitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\VisitorFlyweight
 */
class VisitorFlyweightTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testUsesDefaultMappingsWithGetInstance()
    {
        $f = VisitorFlyweight::getInstance();
        $this->assertInstanceOf('Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor', $f->getRequestVisitor('json'));
        $this->assertInstanceOf('Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor', $f->getResponseVisitor('json'));
    }

    public function testCanUseCustomMappings()
    {
        $f = new VisitorFlyweight(array());
        $this->assertEquals(array(), $this->readAttribute($f, 'mappings'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage No request visitor has been mapped for foo
     */
    public function testThrowsExceptionWhenRetrievingUnknownVisitor()
    {
        VisitorFlyweight::getInstance()->getRequestVisitor('foo');
    }

    public function testCachesVisitors()
    {
        $f = new VisitorFlyweight();
        $v1 = $f->getRequestVisitor('json');
        $this->assertSame($v1, $f->getRequestVisitor('json'));
    }

    public function testAllowsAddingVisitors()
    {
        $f = new VisitorFlyweight();
        $j1 = new JsonRequestVisitor();
        $j2 = new JsonResponseVisitor();
        $f->addRequestVisitor('json', $j1);
        $f->addResponseVisitor('json', $j2);
        $this->assertSame($j1, $f->getRequestVisitor('json'));
        $this->assertSame($j2, $f->getResponseVisitor('json'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Tests\Service\Mock\Command\MockCommand;
use Guzzle\Http\Message\Response;

abstract class AbstractResponseVisitorTest extends \Guzzle\Tests\GuzzleTestCase
{
    /** @var Response */
    protected $response;

    /** @var MockCommand */
    protected $command;

    /** @var array */
    protected $value;

    public function setUp()
    {
        $this->value = array();
        $this->command = new MockCommand();
        $this->response = new Response(200, array(
            'X-Foo'          => 'bar',
            'Content-Length' => 3,
            'Content-Type'   => 'text/plain'
        ), 'Foo');
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor
 */
class BodyVisitorTest extends AbstractResponseVisitorTest
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = new Parameter(array('location' => 'body', 'name' => 'foo'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('Foo', (string) $this->value['foo']);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor
 */
class HeaderVisitorTest extends AbstractResponseVisitorTest
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location' => 'header',
            'name'     => 'ContentType',
            'sentAs'   => 'Content-Type'
        ));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('text/plain', $this->value['ContentType']);
    }

    public function testVisitsLocationWithFilters()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location' => 'header',
            'name'     => 'Content-Type',
            'filters'  => array('strtoupper')
        ));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('TEXT/PLAIN', $this->value['Content-Type']);
    }

    public function testVisitsMappedPrefixHeaders()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location'             => 'header',
            'name'                 => 'Metadata',
            'sentAs'               => 'X-Baz-',
            'type'                 => 'object',
            'additionalProperties' => array(
                'type' => 'string'
            )
        ));
        $response = new Response(200, array(
            'X-Baz-Test'     => 'ABC',
            'X-Baz-Bar'      => array('123', '456'),
            'Content-Length' => 3
        ), 'Foo');
        $visitor->visit($this->command, $response, $param, $this->value);
        $this->assertEquals(array(
            'Metadata' => array(
                'Test' => 'ABC',
                'Bar'  => array('123', '456')
            )
        ), $this->value);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownHeaders()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location'             => 'header',
            'name'                 => 'Content-Type',
            'additionalParameters' => false
        ));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('text/plain', $this->value['Content-Type']);
        $this->assertArrayNotHasKey('X-Foo', $this->value);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownPropertiesWithAliasing()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location'             => 'header',
            'name'                 => 'ContentType',
            'sentAs'               => 'Content-Type',
            'additionalParameters' => false
        ));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('text/plain', $this->value['ContentType']);
        $this->assertArrayNotHasKey('X-Foo', $this->value);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor
 */
class JsonVisitorTest extends AbstractResponseVisitorTest
{
    public function testBeforeMethodParsesXml()
    {
        $visitor = new Visitor();
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')
            ->setMethods(array('getResponse'))
            ->getMockForAbstractClass();
        $command->expects($this->once())
            ->method('getResponse')
            ->will($this->returnValue(new Response(200, null, '{"foo":"bar"}')));
        $result = array();
        $visitor->before($command, $result);
        $this->assertEquals(array('foo' => 'bar'), $result);
    }

    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name' => 'foo',
            'type' => 'array',
            'items' => array(
                'filters' => 'strtoupper',
                'type'    => 'string'
            )
        ));
        $this->value = array('foo' => array('a', 'b', 'c'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('A', 'B', 'C'), $this->value['foo']);
    }

    public function testRenamesTopLevelValues()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'   => 'foo',
            'sentAs' => 'Baz',
            'type'   => 'string',
        ));
        $this->value = array('Baz' => 'test');
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => 'test'), $this->value);
    }

    public function testRenamesDoesNotFailForNonExistentKey()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'          => 'foo',
            'type'          => 'object',
            'properties'    => array(
                'bar' => array(
                    'name'      => 'bar',
                    'sentAs'    => 'baz',
                ),
            ),
        ));
        $this->value = array('foo' => array('unknown' => 'Unknown'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => array('unknown' => 'Unknown')), $this->value);
    }

    public function testTraversesObjectsAndAppliesFilters()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name' => 'foo',
            'type' => 'object',
            'properties' => array(
                'foo' => array('filters' => 'strtoupper'),
                'bar' => array('filters' => 'strtolower')
            )
        ));
        $this->value = array('foo' => array('foo' => 'hello', 'bar' => 'THERE'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => 'HELLO', 'bar' => 'there'), $this->value['foo']);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownProperties()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'additionalProperties' => false,
            'properties'           => array(
                'bar' => array(
                    'type' => 'string',
                    'name' => 'bar',
                ),
            ),
        ));
        $this->value = array('foo' => array('bar' => 15, 'unknown' => 'Unknown'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => array('bar' => 15)), $this->value);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownPropertiesWithAliasing()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'additionalProperties' => false,
            'properties'           => array(
                'bar' => array(
                    'name'   => 'bar',
                    'sentAs' => 'baz',
                ),
            ),
        ));
        $this->value = array('foo' => array('baz' => 15, 'unknown' => 'Unknown'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => array('bar' => 15)), $this->value);
    }

    public function testWalksAdditionalProperties()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'additionalProperties' => array(
                'type' => 'object',
                'properties' => array(
                    'bar' => array(
                        'type' => 'string',
                        'filters' => array('base64_decode')
                    )
                ),
            ),
        ));
        $this->value = array('foo' => array('baz' => array('bar' => 'Zm9v')));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('foo', $this->value['foo']['baz']['bar']);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor
 */
class XmlVisitorTest extends AbstractResponseVisitorTest
{
    public function testBeforeMethodParsesXml()
    {
        $visitor = new Visitor();
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')
            ->setMethods(array('getResponse'))
            ->getMockForAbstractClass();
        $command->expects($this->once())
            ->method('getResponse')
            ->will($this->returnValue(new Response(200, null, '<foo><Bar>test</Bar></foo>')));
        $result = array();
        $visitor->before($command, $result);
        $this->assertEquals(array('Bar' => 'test'), $result);
    }

    public function testBeforeMethodParsesXmlWithNamespace()
    {
        $this->markTestSkipped("Response/XmlVisitor cannot accept 'xmlns' in response, see #368 (http://git.io/USa1mA).");

        $visitor = new Visitor();
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')
            ->setMethods(array('getResponse'))
            ->getMockForAbstractClass();
        $command->expects($this->once())
            ->method('getResponse')
            ->will($this->returnValue(new Response(200, null, '<foo xmlns="urn:foo"><bar:Bar xmlns:bar="urn:bar">test</bar:Bar></foo>')));
        $result = array();
        $visitor->before($command, $result);
        $this->assertEquals(array('Bar' => 'test'), $result);
    }

    public function testBeforeMethodParsesNestedXml()
    {
        $visitor = new Visitor();
        $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')
            ->setMethods(array('getResponse'))
            ->getMockForAbstractClass();
        $command->expects($this->once())
            ->method('getResponse')
            ->will($this->returnValue(new Response(200, null, '<foo><Items><Bar>test</Bar></Items></foo>')));
        $result = array();
        $visitor->before($command, $result);
        $this->assertEquals(array('Items' => array('Bar' => 'test')), $result);
    }

    public function testCanExtractAndRenameTopLevelXmlValues()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location' => 'xml',
            'name'     => 'foo',
            'sentAs'   => 'Bar'
        ));
        $value = array('Bar' => 'test');
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertArrayHasKey('foo', $value);
        $this->assertEquals('test', $value['foo']);
    }

    public function testEnsuresRepeatedArraysAreInCorrectLocations()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location' => 'xml',
            'name'     => 'foo',
            'sentAs'   => 'Foo',
            'type'     => 'array',
            'items'    => array(
                'type' => 'object',
                'properties' => array(
                    'Bar' => array('type' => 'string'),
                    'Baz' => array('type' => 'string'),
                    'Bam' => array('type' => 'string')
                )
            )
        ));

        $xml = new \SimpleXMLElement('<Test><Foo><Bar>1</Bar><Baz>2</Baz></Foo></Test>');
        $value = json_decode(json_encode($xml), true);
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals(array(
            'foo' => array(
                array (
                    'Bar' => '1',
                    'Baz' => '2'
                )
            )
        ), $value);
    }

    public function testEnsuresFlatArraysAreFlat()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'location' => 'xml',
            'name'     => 'foo',
            'type'     => 'array',
            'items'    => array('type' => 'string')
        ));

        $value = array('foo' => array('bar', 'baz'));
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals(array('foo' => array('bar', 'baz')), $value);

        $value = array('foo' => 'bar');
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals(array('foo' => array('bar')), $value);
    }

    public function xmlDataProvider()
    {
        $param = new Parameter(array(
            'location' => 'xml',
            'name'     => 'Items',
            'type'     => 'array',
            'items'    => array(
                'type' => 'object',
                'name' => 'Item',
                'properties' => array(
                    'Bar' => array('type' => 'string'),
                    'Baz' => array('type' => 'string')
                )
            )
        ));

        return array(
            array($param, '<Test><Items><Item><Bar>1</Bar></Item><Item><Bar>2</Bar></Item></Items></Test>', array(
                'Items' => array(
                    array('Bar' => 1),
                    array('Bar' => 2)
                )
            )),
            array($param, '<Test><Items><Item><Bar>1</Bar></Item></Items></Test>', array(
                'Items' => array(
                    array('Bar' => 1)
                )
            )),
            array($param, '<Test><Items /></Test>', array(
                'Items' => array()
            ))
        );
    }

    /**
     * @dataProvider xmlDataProvider
     */
    public function testEnsuresWrappedArraysAreInCorrectLocations($param, $xml, $result)
    {
        $visitor = new Visitor();
        $xml = new \SimpleXMLElement($xml);
        $value = json_decode(json_encode($xml), true);
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals($result, $value);
    }

    public function testCanRenameValues()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'     => 'TerminatingInstances',
            'type'     => 'array',
            'location' => 'xml',
            'sentAs'   => 'instancesSet',
            'items'    => array(
                'name' => 'item',
                'type' => 'object',
                'sentAs' => 'item',
                'properties' => array(
                    'InstanceId' => array(
                        'type'   => 'string',
                        'sentAs' => 'instanceId',
                    ),
                    'CurrentState' => array(
                        'type'   => 'object',
                        'sentAs' => 'currentState',
                        'properties' => array(
                            'Code' => array(
                                'type' => 'numeric',
                                'sentAs' => 'code',
                            ),
                            'Name' => array(
                                'type' => 'string',
                                'sentAs' => 'name',
                            ),
                        ),
                    ),
                    'PreviousState' => array(
                        'type'   => 'object',
                        'sentAs' => 'previousState',
                        'properties' => array(
                            'Code' => array(
                                'type' => 'numeric',
                                'sentAs' => 'code',
                            ),
                            'Name' => array(
                                'type' => 'string',
                                'sentAs' => 'name',
                            ),
                        ),
                    ),
                ),
            )
        ));

        $value = array(
            'instancesSet' => array (
                'item' => array (
                    'instanceId' => 'i-3ea74257',
                    'currentState' => array(
                        'code' => '32',
                        'name' => 'shutting-down',
                    ),
                    'previousState' => array(
                        'code' => '16',
                        'name' => 'running',
                    ),
                ),
            )
        );

        $visitor->visit($this->command, $this->response, $param, $value);

        $this->assertEquals(array(
            'TerminatingInstances' => array(
                array(
                    'InstanceId' => 'i-3ea74257',
                    'CurrentState' => array(
                        'Code' => '32',
                        'Name' => 'shutting-down',
                    ),
                    'PreviousState' => array(
                        'Code' => '16',
                        'Name' => 'running',
                    )
                )
            )
        ), $value);
    }

    public function testCanRenameAttributes()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'     => 'RunningQueues',
            'type'     => 'array',
            'location' => 'xml',
            'items'    => array(
                'type' => 'object',
                'sentAs' => 'item',
                'properties' => array(
                    'QueueId' => array(
                        'type'   => 'string',
                        'sentAs' => 'queue_id',
                        'data'   => array(
                            'xmlAttribute' => true,
                        ),
                    ),
                    'CurrentState' => array(
                        'type'       => 'object',
                        'properties' => array(
                            'Code' => array(
                                'type'   => 'numeric',
                                'sentAs' => 'code',
                                'data'   => array(
                                    'xmlAttribute' => true,
                                ),
                            ),
                            'Name' => array(
                                'sentAs' => 'name',
                                'data'   => array(
                                    'xmlAttribute' => true,
                                ),
                            ),
                        ),
                    ),
                    'PreviousState' => array(
                        'type'       => 'object',
                        'properties' => array(
                            'Code' => array(
                                'type'   => 'numeric',
                                'sentAs' => 'code',
                                'data'   => array(
                                    'xmlAttribute' => true,
                                ),
                            ),
                            'Name' => array(
                                'sentAs' => 'name',
                                'data'   => array(
                                    'xmlAttribute' => true,
                                ),
                            ),
                        ),
                    ),
                ),
            )
        ));

        $xml = '<wrap><RunningQueues><item queue_id="q-3ea74257"><CurrentState code="32" name="processing" /><PreviousState code="16" name="wait" /></item></RunningQueues></wrap>';
        $value = json_decode(json_encode(new \SimpleXMLElement($xml)), true);
        $visitor->visit($this->command, $this->response, $param, $value);

        $this->assertEquals(array(
            'RunningQueues' => array(
                array(
                    'QueueId' => 'q-3ea74257',
                    'CurrentState' => array(
                        'Code' => '32',
                        'Name' => 'processing',
                    ),
                    'PreviousState' => array(
                        'Code' => '16',
                        'Name' => 'wait',
                    ),
                ),
            )
        ), $value);
    }

    public function testAddsEmptyArraysWhenValueIsMissing()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'     => 'Foo',
            'type'     => 'array',
            'location' => 'xml',
            'items' => array(
                'type' => 'object',
                'properties' => array(
                    'Baz' => array('type' => 'array'),
                    'Bar' => array(
                        'type'   => 'object',
                        'properties' => array(
                            'Baz' => array('type' => 'array'),
                         )
                    )
                )
            )
        ));

        $value = array();
        $visitor->visit($this->command, $this->response, $param, $value);

        $value = array(
            'Foo' => array(
                'Bar' => array()
            )
        );
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals(array(
            'Foo' => array(
                array(
                    'Bar' => array()
                )
            )
        ), $value);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownProperties()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'additionalProperties' => false,
            'properties'           => array(
                'bar' => array(
                    'type' => 'string',
                    'name' => 'bar',
                ),
            ),
        ));
        $this->value = array('foo' => array('bar' => 15, 'unknown' => 'Unknown'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => array('bar' => 15)), $this->value);
    }

    /**
     * @group issue-399
     * @link  https://github.com/guzzle/guzzle/issues/399
     */
    public function testDiscardingUnknownPropertiesWithAliasing()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'additionalProperties' => false,
            'properties'           => array(
                'bar' => array(
                    'name'   => 'bar',
                    'sentAs' => 'baz',
                ),
            ),
        ));
        $this->value = array('foo' => array('baz' => 15, 'unknown' => 'Unknown'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(array('foo' => array('bar' => 15)), $this->value);
    }

    public function testProperlyHandlesEmptyStringValues()
    {
        $visitor = new Visitor();
        $param = new Parameter(array(
            'name'                 => 'foo',
            'type'                 => 'object',
            'properties'           => array(
                'bar' => array('type' => 'string')
            ),
        ));
        $xml = '<wrapper><foo><bar /></foo></wrapper>';
        $value = json_decode(json_encode(new \SimpleXMLElement($xml)), true);
        $visitor->visit($this->command, $this->response, $param, $value);
        $this->assertEquals(array('foo' => array('bar' => '')), $value);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor
 */
class StatusCodeVisitorTest extends AbstractResponseVisitorTest
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = new Parameter(array('location' => 'statusCode', 'name' => 'code'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals(200, $this->value['code']);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Description\Parameter;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor
 */
class ReasonPhraseVisitorTest extends AbstractResponseVisitorTest
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = new Parameter(array('location' => 'reasonPhrase', 'name' => 'phrase'));
        $visitor->visit($this->command, $this->response, $param, $this->value);
        $this->assertEquals('OK', $this->value['phrase']);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\SchemaValidator;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Tests\Service\Mock\Command\MockCommand;
use Guzzle\Tests\Service\Mock\MockClient;

abstract class AbstractVisitorTestCase extends \Guzzle\Tests\GuzzleTestCase
{
    protected $command;
    protected $request;
    protected $param;
    protected $validator;

    public function setUp()
    {
        $this->command = new MockCommand();
        $this->request = new EntityEnclosingRequest('POST', 'http://www.test.com/some/path.php');
        $this->validator = new SchemaValidator();
    }

    protected function getCommand($location)
    {
        $command = new OperationCommand(array(), $this->getNestedCommand($location));
        $command->setClient(new MockClient());

        return $command;
    }

    protected function getNestedCommand($location)
    {
        return new Operation(array(
            'httpMethod' => 'POST',
            'parameters' => array(
                'foo' => new Parameter(array(
                    'type'         => 'object',
                    'location'     => $location,
                    'sentAs'       => 'Foo',
                    'required'     => true,
                    'properties'   => array(
                        'test' => array(
                            'type'      => 'object',
                            'required'  => true,
                            'properties' => array(
                                'baz' => array(
                                    'type'    => 'boolean',
                                    'default' => true
                                ),
                                'jenga' => array(
                                    'type'    => 'string',
                                    'default' => 'hello',
                                    'sentAs'  => 'Jenga_Yall!',
                                    'filters' => array('strtoupper')
                                )
                            )
                        ),
                        'bar' => array('default' => 123)
                    ),
                    'additionalProperties' => array(
                        'type' => 'string',
                        'filters' => array('strtoupper'),
                        'location' => $location
                    )
                )),
                'arr' => new Parameter(array(
                    'type'         => 'array',
                    'location'     => $location,
                    'items' => array(
                        'type' => 'string',
                        'filters' => array('strtoupper')
                     )
                )),
            )
        ));
    }

    protected function getCommandWithArrayParamAndFilters()
    {
        $operation = new Operation(array(
            'httpMethod' => 'POST',
            'parameters' => array(
                'foo' => new Parameter(array(
                    'type' => 'string',
                    'location' => 'query',
                    'sentAs' => 'Foo',
                    'required' => true,
                    'default' => 'bar',
                    'filters' => array('strtoupper')
                )),
                'arr' => new Parameter(array(
                    'type' => 'array',
                    'location' => 'query',
                    'sentAs' => 'Arr',
                    'required' => true,
                    'default' => array(123, 456, 789),
                    'filters' => array(array('method' => 'implode', 'args' => array(',', '@value')))
                ))
            )
        ));
        $command = new OperationCommand(array(), $operation);
        $command->setClient(new MockClient());

        return $command;
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor
 */
class PostFieldVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('postField')->getParam('foo');
        $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123');
        $this->assertEquals('123', (string) $this->request->getPostField('test'));
    }

    public function testRecursivelyBuildsPostFields()
    {
        $command = $this->getCommand('postField');
        $request = $command->prepare();
        $visitor = new Visitor();
        $param = $command->getOperation()->getParam('foo');
        $visitor->visit($command, $request, $param, $command['foo']);
        $visitor->after($command, $request);
        $this->assertEquals(
            'Foo[test][baz]=1&Foo[test][Jenga_Yall!]=HELLO&Foo[bar]=123',
            rawurldecode((string) $request->getPostFields())
        );
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor
 */
class ResponseBodyVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('response_body')->getParam('foo');
        $visitor->visit($this->command, $this->request, $param, sys_get_temp_dir() . '/foo.txt');
        $body = $this->readAttribute($this->request, 'responseBody');
        $this->assertContains('/foo.txt', $body->getUri());
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Http\EntityBody;
use Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor
 */
class BodyVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo');
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertEquals('123', (string) $this->request->getBody());
        $this->assertNull($this->request->getHeader('Expect'));
    }

    public function testAddsExpectHeaderWhenSetToTrue()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo');
        $param->setData('expect_header', true);
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertEquals('123', (string) $this->request->getBody());
    }

    public function testCanDisableExpectHeader()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo');
        $param->setData('expect_header', false);
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertNull($this->request->getHeader('Expect'));
    }

    public function testCanSetExpectHeaderBasedOnSize()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo');
        // The body is less than the cutoff
        $param->setData('expect_header', 5);
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertNull($this->request->getHeader('Expect'));
        // Now check when the body is greater than the cutoff
        $param->setData('expect_header', 2);
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertEquals('100-Continue', (string) $this->request->getHeader('Expect'));
    }

    public function testAddsContentEncodingWhenSetOnBody()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo');
        $body = EntityBody::factory('foo');
        $body->compress();
        $visitor->visit($this->command, $this->request, $param, $body);
        $this->assertEquals('gzip', (string) $this->request->getHeader('Content-Encoding'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor
 */
class HeaderVisitorTest extends AbstractVisitorTestCase
{
    /**
     * @expectedException \Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testValidatesHeaderMapsAreArrays()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('header')->getParam('foo')->setSentAs('test');
        $param->setAdditionalProperties(new Parameter(array()));
        $visitor->visit($this->command, $this->request, $param, 'test');
    }

    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('header')->getParam('foo')->setSentAs('test');
        $param->setAdditionalProperties(false);
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertEquals('123', (string) $this->request->getHeader('test'));
    }

    public function testVisitsMappedPrefixHeaders()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('header')->getParam('foo')->setSentAs('test');
        $param->setSentAs('x-foo-');
        $param->setAdditionalProperties(new Parameter(array(
            'type' => 'string'
        )));
        $visitor->visit($this->command, $this->request, $param, array(
            'bar' => 'test',
            'baz' => '123'
        ));
        $this->assertEquals('test', (string) $this->request->getHeader('x-foo-bar'));
        $this->assertEquals('123', (string) $this->request->getHeader('x-foo-baz'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor
 * @covers Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor::resolveRecursively
 */
class JsonVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        // Test after when no body query values were found
        $visitor->after($this->command, $this->request);

        $param = $this->getNestedCommand('json')->getParam('foo');
        $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123');
        $visitor->visit($this->command, $this->request, $param->setSentAs('test2'), 'abc');
        $visitor->after($this->command, $this->request);
        $this->assertEquals('{"test":"123","test2":"abc"}', (string) $this->request->getBody());
    }

    public function testAddsJsonHeader()
    {
        $visitor = new Visitor();
        $visitor->setContentTypeHeader('application/json-foo');
        $param = $this->getNestedCommand('json')->getParam('foo');
        $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123');
        $visitor->after($this->command, $this->request);
        $this->assertEquals('application/json-foo', (string) $this->request->getHeader('Content-Type'));
    }

    public function testRecursivelyBuildsJsonBodies()
    {
        $command = $this->getCommand('json');
        $request = $command->prepare();
        $this->assertEquals('{"Foo":{"test":{"baz":true,"Jenga_Yall!":"HELLO"},"bar":123}}', (string) $request->getBody());
    }

    public function testAppliesFiltersToAdditionalProperties()
    {
        $command = $this->getCommand('json');
        $command->set('foo', array('not_set' => 'abc'));
        $request = $command->prepare();
        $result = json_decode($request->getBody(), true);
        $this->assertEquals('ABC', $result['Foo']['not_set']);
    }

    public function testAppliesFiltersToArrayItemValues()
    {
        $command = $this->getCommand('json');
        $command->set('arr', array('a', 'b'));
        $request = $command->prepare();
        $result = json_decode($request->getBody(), true);
        $this->assertEquals(array('A', 'B'), $result['arr']);
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor;
use Guzzle\Service\Client;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\Operation;
use Guzzle\Http\Message\EntityEnclosingRequest;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor
 */
class XmlVisitorTest extends AbstractVisitorTestCase
{
    public function xmlProvider()
    {
        return array(
            array(
                array(
                    'data' => array(
                        'xmlRoot' => array(
                            'name'       => 'test',
                            'namespaces' => 'http://foo.com'
                        )
                    ),
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string'),
                        'Baz' => array('location' => 'xml', 'type' => 'string')
                    )
                ),
                array('Foo' => 'test', 'Baz' => 'bar'),
                '<test xmlns="http://foo.com"><Foo>test</Foo><Baz>bar</Baz></test>'
            ),
            // Ensure that the content-type is not added
            array(array('parameters' => array('Foo' => array('location' => 'xml', 'type' => 'string'))), array(), ''),
            // Test with adding attributes and no namespace
            array(
                array(
                    'data' => array(
                        'xmlRoot' => array(
                            'name' => 'test'
                        )
                    ),
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string', 'data' => array('xmlAttribute' => true))
                    )
                ),
                array('Foo' => 'test', 'Baz' => 'bar'),
                '<test Foo="test"/>'
            ),
            // Test adding with an array
            array(
                array(
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string'),
                        'Baz' => array(
                            'type'     => 'array',
                            'location' => 'xml',
                            'items' => array(
                                'type'   => 'numeric',
                                'sentAs' => 'Bar'
                            )
                        )
                    )
                ),
                array('Foo' => 'test', 'Baz' => array(1, 2)),
                '<Request><Foo>test</Foo><Baz><Bar>1</Bar><Bar>2</Bar></Baz></Request>'
            ),
            // Test adding an object
            array(
                array(
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string'),
                        'Baz' => array(
                            'type'     => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Bar' => array('type' => 'string'),
                                'Bam' => array()
                            )
                        )
                    )
                ),
                array('Foo' => 'test', 'Baz' => array('Bar' => 'abc', 'Bam' => 'foo')),
                '<Request><Foo>test</Foo><Baz><Bar>abc</Bar><Bam>foo</Bam></Baz></Request>'
            ),
            // Add an array that contains an object
            array(
                array(
                    'parameters' => array(
                        'Baz' => array(
                            'type'     => 'array',
                            'location' => 'xml',
                            'items' => array(
                                'type'       => 'object',
                                'sentAs'     => 'Bar',
                                'properties' => array('A' => array(), 'B' => array())
                            )
                        )
                    )
                ),
                array('Baz' => array(
                    array('A' => '1', 'B' => '2'),
                    array('A' => '3', 'B' => '4')
                )),
                '<Request><Baz><Bar><A>1</A><B>2</B></Bar><Bar><A>3</A><B>4</B></Bar></Baz></Request>'
            ),
            // Add an object of attributes
            array(
                array(
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string'),
                        'Baz' => array(
                            'type'     => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Bar' => array('type' => 'string', 'data' => array('xmlAttribute' => true)),
                                'Bam' => array()
                            )
                        )
                    )
                ),
                array('Foo' => 'test', 'Baz' => array('Bar' => 'abc', 'Bam' => 'foo')),
                '<Request><Foo>test</Foo><Baz Bar="abc"><Bam>foo</Bam></Baz></Request>'
            ),
            // Check order doesn't matter
            array(
                array(
                    'parameters' => array(
                        'Foo' => array('location' => 'xml', 'type' => 'string'),
                        'Baz' => array(
                            'type'     => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Bar' => array('type' => 'string', 'data' => array('xmlAttribute' => true)),
                                'Bam' => array()
                            )
                        )
                    )
                ),
                array('Foo' => 'test', 'Baz' => array('Bam' => 'foo', 'Bar' => 'abc')),
                '<Request><Foo>test</Foo><Baz Bar="abc"><Bam>foo</Bam></Baz></Request>'
            ),
            // Add values with custom namespaces
            array(
                array(
                    'parameters' => array(
                        'Foo' => array(
                            'location' => 'xml',
                            'type' => 'string',
                            'data' => array(
                                'xmlNamespace' => 'http://foo.com'
                            )
                        )
                    )
                ),
                array('Foo' => 'test'),
                '<Request><Foo xmlns="http://foo.com">test</Foo></Request>'
            ),
            // Add attributes with custom namespace prefix
            array(
                array(
                    'parameters' => array(
                        'Wrap' => array(
                            'type' => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Foo' => array(
                                    'type' => 'string',
                                    'sentAs' => 'xsi:baz',
                                    'data' => array(
                                        'xmlNamespace' => 'http://foo.com',
                                        'xmlAttribute' => true
                                    )
                                )
                            )
                        ),
                    )
                ),
                array('Wrap' => array(
                    'Foo' => 'test'
                )),
                '<Request><Wrap xsi:baz="test" xmlns:xsi="http://foo.com"/></Request>'
            ),
            // Add nodes with custom namespace prefix
            array(
                array(
                    'parameters' => array(
                        'Wrap' => array(
                            'type' => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Foo' => array(
                                    'type' => 'string',
                                    'sentAs' => 'xsi:Foo',
                                    'data' => array(
                                        'xmlNamespace' => 'http://foobar.com'
                                    )
                                )
                            )
                        ),
                    )
                ),
                array('Wrap' => array(
                    'Foo' => 'test'
                )),
                '<Request><Wrap><xsi:Foo xmlns:xsi="http://foobar.com">test</xsi:Foo></Wrap></Request>'
            ),
            array(
                array(
                    'parameters' => array(
                        'Foo' => array(
                            'location' => 'xml',
                            'type' => 'string',
                            'data' => array(
                                'xmlNamespace' => 'http://foo.com'
                            )
                        )
                    )
                ),
                array('Foo' => '<h1>This is a title</h1>'),
                '<Request><Foo xmlns="http://foo.com"><![CDATA[<h1>This is a title</h1>]]></Foo></Request>'
            ),
            // Flat array at top level
            array(
                array(
                    'parameters' => array(
                        'Bars' => array(
                            'type'     => 'array',
                            'data'     => array('xmlFlattened' => true),
                            'location' => 'xml',
                            'items' => array(
                                'type'       => 'object',
                                'sentAs'     => 'Bar',
                                'properties' => array(
                                    'A' => array(),
                                    'B' => array()
                                )
                            )
                        ),
                        'Boos' => array(
                            'type'     => 'array',
                            'data'     => array('xmlFlattened' => true),
                            'location' => 'xml',
                            'items'  => array(
                                'sentAs' => 'Boo',
                                'type' => 'string'
                            )
                        )
                    )
                ),
                array(
                    'Bars' => array(
                        array('A' => '1', 'B' => '2'),
                        array('A' => '3', 'B' => '4')
                    ),
                    'Boos' => array('test', '123')
                ),
                '<Request><Bar><A>1</A><B>2</B></Bar><Bar><A>3</A><B>4</B></Bar><Boo>test</Boo><Boo>123</Boo></Request>'
            ),
            // Nested flat arrays
            array(
                array(
                    'parameters' => array(
                        'Delete' => array(
                            'type'     => 'object',
                            'location' => 'xml',
                            'properties' => array(
                                'Items' => array(
                                    'type' => 'array',
                                    'data' => array('xmlFlattened' => true),
                                    'items' => array(
                                        'type'       => 'object',
                                        'sentAs'     => 'Item',
                                        'properties' => array(
                                            'A' => array(),
                                            'B' => array()
                                        )
                                    )
                                )
                            )
                        )
                    )
                ),
                array(
                    'Delete' => array(
                        'Items' => array(
                            array('A' => '1', 'B' => '2'),
                            array('A' => '3', 'B' => '4')
                        )
                    )
                ),
                '<Request><Delete><Item><A>1</A><B>2</B></Item><Item><A>3</A><B>4</B></Item></Delete></Request>'
            )
        );
    }

    /**
     * @dataProvider xmlProvider
     */
    public function testSerializesXml(array $operation, array $input, $xml)
    {
        $operation = new Operation($operation);
        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array($input, $operation))
            ->getMockForAbstractClass();
        $command->setClient(new Client('http://www.test.com/some/path.php'));
        $request = $command->prepare();
        if (!empty($input)) {
            $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type'));
        } else {
            $this->assertNull($request->getHeader('Content-Type'));
        }
        $body = str_replace(array("\n", "<?xml version=\"1.0\"?>"), '', (string) $request->getBody());
        $this->assertEquals($xml, $body);
    }

    public function testAddsContentTypeAndTopLevelValues()
    {
        $operation = new Operation(array(
            'data' => array(
                'xmlRoot'      => array(
                    'name' => 'test',
                    'namespaces' => array(
                        'xsi' => 'http://foo.com'
                    )
                )
            ),
            'parameters' => array(
                'Foo' => array('location' => 'xml', 'type' => 'string'),
                'Baz' => array('location' => 'xml', 'type' => 'string')
            )
        ));

        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array(
                'Foo' => 'test',
                'Baz' => 'bar'
            ), $operation))
            ->getMockForAbstractClass();

        $command->setClient(new Client());
        $request = $command->prepare();
        $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type'));
        $this->assertEquals(
            '<?xml version="1.0"?>' . "\n"
            . '<test xmlns:xsi="http://foo.com"><Foo>test</Foo><Baz>bar</Baz></test>' . "\n",
            (string) $request->getBody()
        );
    }

    public function testCanChangeContentType()
    {
        $visitor = new XmlVisitor();
        $visitor->setContentTypeHeader('application/foo');
        $this->assertEquals('application/foo', $this->readAttribute($visitor, 'contentType'));
    }

    public function testCanAddArrayOfSimpleTypes()
    {
        $request = new EntityEnclosingRequest('POST', 'http://foo.com');
        $visitor = new XmlVisitor();
        $param = new Parameter(array(
            'type'     => 'object',
            'location' => 'xml',
            'name'     => 'Out',
            'properties' => array(
                'Nodes' => array(
                    'required' => true,
                    'type'     => 'array',
                    'min'      => 1,
                    'items'    => array('type' => 'string', 'sentAs' => 'Node')
                )
            )
        ));

        $param->setParent(new Operation(array(
            'data' => array(
                'xmlRoot' => array(
                    'name' => 'Test',
                    'namespaces' => array(
                        'https://foo/'
                    )
                )
            )
        )));

        $value = array('Nodes' => array('foo', 'baz'));
        $this->assertTrue($this->validator->validate($param, $value));
        $visitor->visit($this->command, $request, $param, $value);
        $visitor->after($this->command, $request);

        $this->assertEquals(
            "<?xml version=\"1.0\"?>\n"
            . "<Test xmlns=\"https://foo/\"><Out><Nodes><Node>foo</Node><Node>baz</Node></Nodes></Out></Test>\n",
            (string) $request->getBody()
        );
    }

    public function testCanAddMultipleNamespacesToRoot()
    {
        $operation = new Operation(array(
            'data' => array(
                'xmlRoot' => array(
                    'name' => 'Hi',
                    'namespaces' => array(
                        'xsi' => 'http://foo.com',
                        'foo' => 'http://foobar.com'
                    )
                )
            ),
            'parameters' => array(
                'Foo' => array('location' => 'xml', 'type' => 'string')
            )
        ));

        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array(
                'Foo' => 'test'
            ), $operation))
            ->getMockForAbstractClass();

        $command->setClient(new Client());
        $request = $command->prepare();
        $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type'));
        $this->assertEquals(
            '<?xml version="1.0"?>' . "\n"
            . '<Hi xmlns:xsi="http://foo.com" xmlns:foo="http://foobar.com"><Foo>test</Foo></Hi>' . "\n",
            (string) $request->getBody()
        );
    }

    public function testValuesAreFiltered()
    {
        $operation = new Operation(array(
            'parameters' => array(
                'Foo' => array(
                    'location' => 'xml',
                    'type'     => 'string',
                    'filters'  => array('strtoupper')
                ),
                'Bar' => array(
                    'location' => 'xml',
                    'type'     => 'object',
                    'properties' => array(
                        'Baz' => array(
                            'filters'  => array('strtoupper')
                        )
                    )
                )
            )
        ));

        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array(
                'Foo' => 'test',
                'Bar' => array(
                    'Baz' => 'abc'
                )
            ), $operation))
            ->getMockForAbstractClass();

        $command->setClient(new Client());
        $request = $command->prepare();
        $this->assertEquals(
            '<?xml version="1.0"?>' . "\n"
            . '<Request><Foo>TEST</Foo><Bar><Baz>ABC</Baz></Bar></Request>' . "\n",
            (string) $request->getBody()
        );
    }

    public function testSkipsNullValues()
    {
        $operation = new Operation(array(
            'parameters' => array(
                'Foo' => array(
                    'location' => 'xml',
                    'type'     => 'string'
                ),
                'Bar' => array(
                    'location' => 'xml',
                    'type'     => 'object',
                    'properties' => array(
                        'Baz' => array(),
                        'Bam' => array(),
                    )
                ),
                'Arr' => array(
                    'type'  => 'array',
                    'items' => array(
                        'type' => 'string'
                    )
                )
            )
        ));

        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array(
                'Foo' => null,
                'Bar' => array(
                    'Bar' => null,
                    'Bam' => 'test'
                ),
                'Arr' => array(null)
            ), $operation))
            ->getMockForAbstractClass();

        $command->setClient(new Client());
        $request = $command->prepare();
        $this->assertEquals(
            '<?xml version="1.0"?>' . "\n"
            . '<Request><Bar><Bam>test</Bam></Bar></Request>' . "\n",
            (string) $request->getBody()
        );
    }

    public function testAllowsXmlEncoding()
    {
        $operation = new Operation(array(
            'data' => array(
                'xmlEncoding' => 'UTF-8'
            ),
            'parameters' => array(
                'Foo' => array('location' => 'xml')
            )
        ));
        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array('Foo' => 'test'), $operation))
            ->getMockForAbstractClass();
        $command->setClient(new Client());
        $request = $command->prepare();
        $this->assertEquals(
            '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
                . '<Request><Foo>test</Foo></Request>' . "\n",
            (string) $request->getBody()
        );
    }

    public function testAllowsSendingXmlPayloadIfNoXmlParamsWereSet()
    {
        $operation = new Operation(array(
            'httpMethod' => 'POST',
            'data' => array('xmlAllowEmpty' => true),
            'parameters' => array('Foo' => array('location' => 'xml'))
        ));
        $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand')
            ->setConstructorArgs(array(array(), $operation))
            ->getMockForAbstractClass();
        $command->setClient(new Client('http://foo.com'));
        $request = $command->prepare();
        $this->assertEquals(
            '<?xml version="1.0"?>' . "\n"
            . '<Request/>' . "\n",
            (string) $request->getBody()
        );
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor
 */
class QueryVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('query')->getParam('foo')->setSentAs('test');
        $visitor->visit($this->command, $this->request, $param, '123');
        $this->assertEquals('123', $this->request->getQuery()->get('test'));
    }

    /**
     * @covers Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor
     * @covers Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor::resolveRecursively
     */
    public function testRecursivelyBuildsQueryStrings()
    {
        $command = $this->getCommand('query');
        $command->getOperation()->getParam('foo')->setSentAs('Foo');
        $request = $command->prepare();
        $this->assertEquals(
            'Foo[test][baz]=1&Foo[test][Jenga_Yall!]=HELLO&Foo[bar]=123',
            rawurldecode($request->getQuery())
        );
    }

    /**
     * @covers Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor::resolveRecursively
     */
    public function testFiltersAreAppliedToArrayParamType()
    {
        $command = $this->getCommandWithArrayParamAndFilters();
        $request = $command->prepare();
        $query = $request->getQuery();
        // param type 'string'
        $this->assertEquals('BAR', $query->get('Foo'));
        // param type 'array'
        $this->assertEquals('123,456,789', $query->get('Arr'));
    }
}
<?php

namespace Guzzle\Tests\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Http\Message\PostFile;
use Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor as Visitor;

/**
 * @covers Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor
 */
class PostFileVisitorTest extends AbstractVisitorTestCase
{
    public function testVisitsLocation()
    {
        $visitor = new Visitor();
        $param = $this->getNestedCommand('postFile')->getParam('foo');

        // Test using a path to a file
        $visitor->visit($this->command, $this->request, $param->setSentAs('test_3'), __FILE__);
        $this->assertInternalType('array', $this->request->getPostFile('test_3'));

        // Test with a PostFile
        $visitor->visit($this->command, $this->request, $param->setSentAs(null), new PostFile('baz', __FILE__));
        $this->assertInternalType('array', $this->request->getPostFile('baz'));
    }

    public function testVisitsLocationWithMultipleFiles()
    {
        $description = ServiceDescription::factory(array(
            'operations' => array(
                'DoPost' => array(
                    'httpMethod' => 'POST',
                    'parameters' => array(
                        'foo' => array(
                            'location' => 'postFile',
                            'type' => array('string', 'array')
                        )
                    )
                )
            )
        ));
        $this->getServer()->flush();
        $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n"));
        $client = new Client($this->getServer()->getUrl());
        $client->setDescription($description);
        $command = $client->getCommand('DoPost', array('foo' => array(__FILE__, __FILE__)));
        $command->execute();
        $received = $this->getServer()->getReceivedRequests();
        $this->assertContains('name="foo[0]";', $received[0]);
        $this->assertContains('name="foo[1]";', $received[0]);
    }
}
<?php

namespace Guzzle\Tests\Service\Resource;

use Guzzle\Service\Resource\Model;
use Guzzle\Service\Description\Parameter;
use Guzzle\Common\Collection;

/**
 * @covers Guzzle\Service\Resource\Model
 */
class ModelTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testOwnsStructure()
    {
        $param = new Parameter(array('type' => 'object'));
        $model = new Model(array('foo' => 'bar'), $param);
        $this->assertSame($param, $model->getStructure());
        $this->assertEquals('bar', $model->get('foo'));
        $this->assertEquals('bar', $model['foo']);
    }

    public function testCanBeUsedWithoutStructure()
    {
        $model = new Model(array(
            'Foo' => 'baz',
            'Bar' => array(
                'Boo' => 'Bam'
            )
        ));
        $transform = function ($key, $value) {
            return ($value && is_array($value)) ? new Collection($value) : $value;
        };
        $model = $model->map($transform);
        $this->assertInstanceOf('Guzzle\Common\Collection', $model->getPath('Bar'));
    }

    public function testAllowsFiltering()
    {
        $model = new Model(array(
            'Foo' => 'baz',
            'Bar' => 'a'
        ));
        $model = $model->filter(function ($i, $v) {
            return $v[0] == 'a';
        });
        $this->assertEquals(array('Bar' => 'a'), $model->toArray());
    }

    public function testDoesNotIncludeEmptyStructureInString()
    {
        $model = new Model(array('Foo' => 'baz'));
        $str = (string) $model;
        $this->assertContains('Debug output of model', $str);
        $this->assertNotContains('Model structure', $str);
    }

    public function testDoesIncludeModelStructureInString()
    {
        $model = new Model(array('Foo' => 'baz'), new Parameter(array('name' => 'Foo')));
        $str = (string) $model;
        $this->assertContains('Debug output of Foo model', $str);
        $this->assertContains('Model structure', $str);
    }
}
<?php

namespace Guzzle\Tests\Service\Resource;

use Guzzle\Service\Resource\ResourceIterator;
use Guzzle\Tests\Service\Mock\Model\MockCommandIterator;

/**
 * @group server
 * @covers Guzzle\Service\Resource\ResourceIterator
 */
class ResourceIteratorTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testDescribesEvents()
    {
        $this->assertInternalType('array', ResourceIterator::getAllEvents());
    }

    public function testConstructorConfiguresDefaults()
    {
        $ri = $this->getMockForAbstractClass('Guzzle\\Service\\Resource\\ResourceIterator', array(
            $this->getServiceBuilder()->get('mock')->getCommand('iterable_command'),
            array(
                'limit' => 10,
                'page_size' => 3
            )
        ), 'MockIterator');

        $this->assertEquals(false, $ri->getNextToken());
        $this->assertEquals(false, $ri->current());
    }

    public function testSendsRequestsForNextSetOfResources()
    {
        // Queue up an array of responses for iterating
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"j\"] }"
        ));

        // Create a new resource iterator using the IterableCommand mock
        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'), array(
            'page_size' => 3
        ));

        // Ensure that no requests have been sent yet
        $this->assertEquals(0, count($this->getServer()->getReceivedRequests(false)));

        //$this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $ri->toArray());
        $ri->toArray();
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals(3, count($requests));

        $this->assertEquals(3, $requests[0]->getQuery()->get('page_size'));
        $this->assertEquals(3, $requests[1]->getQuery()->get('page_size'));
        $this->assertEquals(3, $requests[2]->getQuery()->get('page_size'));

        // Reset and resend
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"j\"] }",
        ));

        $d = array();
        foreach ($ri as $data) {
            $d[] = $data;
        }
        $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $d);
    }

    public function testCalculatesPageSize()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"j\", \"k\"] }"
        ));

        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'), array(
            'page_size' => 3,
            'limit' => 7
        ));

        $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $ri->toArray());
        $requests = $this->getServer()->getReceivedRequests(true);
        $this->assertEquals(3, count($requests));
        $this->assertEquals(3, $requests[0]->getQuery()->get('page_size'));
        $this->assertEquals(3, $requests[1]->getQuery()->get('page_size'));
        $this->assertEquals(1, $requests[2]->getQuery()->get('page_size'));
    }

    public function testUseAsArray()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"g\", \"h\", \"i\"] }"
        ));

        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'));

        // Ensure that the key is never < 0
        $this->assertEquals(0, $ri->key());
        $this->assertEquals(0, count($ri));

        // Ensure that the iterator can be used as KVP array
        $data = array();
        foreach ($ri as $key => $value) {
            $data[$key] = $value;
        }

        // Ensure that the iterate is countable
        $this->assertEquals(6, count($ri));
        $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i'), $data);
    }

    public function testBailsWhenSendReturnsNoResults()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [] }"
        ));

        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'));

        // Ensure that the iterator can be used as KVP array
        $data = $ri->toArray();

        // Ensure that the iterate is countable
        $this->assertEquals(3, count($ri));
        $this->assertEquals(array('d', 'e', 'f'), $data);

        $this->assertEquals(2, $ri->getRequestCount());
    }

    public function testHoldsDataOptions()
    {
        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'));
        $this->assertNull($ri->get('foo'));
        $this->assertSame($ri, $ri->set('foo', 'bar'));
        $this->assertEquals('bar', $ri->get('foo'));
    }

    public function testSettingLimitOrPageSizeClearsData()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }",
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }"
        ));

        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'));
        $ri->toArray();
        $this->assertNotEmpty($this->readAttribute($ri, 'resources'));

        $ri->setLimit(10);
        $this->assertEmpty($this->readAttribute($ri, 'resources'));

        $ri->toArray();
        $this->assertNotEmpty($this->readAttribute($ri, 'resources'));
        $ri->setPageSize(10);
        $this->assertEmpty($this->readAttribute($ri, 'resources'));
    }

    public function testWorksWithCustomAppendIterator()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }"
        ));
        $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'));
        $a = new \Guzzle\Iterator\AppendIterator();
        $a->append($ri);
        $results = iterator_to_array($a, false);
        $this->assertEquals(4, $ri->calledNext);
    }
}
<?php

namespace Guzzle\Tests\Service\Resource;

use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Tests\Service\Mock\Command\MockCommand;

/**
 * @covers Guzzle\Service\Resource\ResourceIteratorClassFactory
 * @covers Guzzle\Service\Resource\AbstractResourceIteratorFactory
 */
class ResourceIteratorClassFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Iterator was not found for mock_command
     */
    public function testEnsuresIteratorClassExists()
    {
        $factory = new ResourceIteratorClassFactory(array('Foo', 'Bar'));
        $factory->registerNamespace('Baz');
        $command = new MockCommand();
        $factory->build($command);
    }

    public function testBuildsResourceIterators()
    {
        $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model');
        $command = new MockCommand();
        $iterator = $factory->build($command, array('client.namespace' => 'Guzzle\Tests\Service\Mock'));
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
    }

    public function testChecksIfCanBuild()
    {
        $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service');
        $this->assertFalse($factory->canBuild(new MockCommand()));
        $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model');
        $this->assertTrue($factory->canBuild(new MockCommand()));
    }
}
<?php

namespace Guzzle\Tests\Service\Resource;

use Guzzle\Service\Resource\MapResourceIteratorFactory;
use Guzzle\Tests\Service\Mock\Command\MockCommand;

/**
 * @covers Guzzle\Service\Resource\MapResourceIteratorFactory
 */
class MapResourceIteratorFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Iterator was not found for mock_command
     */
    public function testEnsuresIteratorClassExists()
    {
        $factory = new MapResourceIteratorFactory(array('Foo', 'Bar'));
        $factory->build(new MockCommand());
    }

    public function testBuildsResourceIterators()
    {
        $factory = new MapResourceIteratorFactory(array(
            'mock_command' => 'Guzzle\Tests\Service\Mock\Model\MockCommandIterator'
        ));
        $iterator = $factory->build(new MockCommand());
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
    }

    public function testUsesWildcardMappings()
    {
        $factory = new MapResourceIteratorFactory(array(
            '*' => 'Guzzle\Tests\Service\Mock\Model\MockCommandIterator'
        ));
        $iterator = $factory->build(new MockCommand());
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
    }
}
<?php

namespace Guzzle\Tests\Service\Resource;

use Guzzle\Service\Resource\CompositeResourceIteratorFactory;
use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Tests\Service\Mock\Command\MockCommand;

/**
 * @covers Guzzle\Service\Resource\CompositeResourceIteratorFactory
 */
class CompositeResourceIteratorFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Iterator was not found for mock_command
     */
    public function testEnsuresIteratorClassExists()
    {
        $factory = new CompositeResourceIteratorFactory(array(
            new ResourceIteratorClassFactory(array('Foo', 'Bar'))
        ));
        $cmd = new MockCommand();
        $this->assertFalse($factory->canBuild($cmd));
        $factory->build($cmd);
    }

    public function testBuildsResourceIterators()
    {
        $f1 = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model');
        $factory = new CompositeResourceIteratorFactory(array());
        $factory->addFactory($f1);
        $command = new MockCommand();
        $iterator = $factory->build($command, array('client.namespace' => 'Guzzle\Tests\Service\Mock'));
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
    }
}
<?php

namespace Guzzle\Tests\Service\Builder;

use Guzzle\Service\Builder\ServiceBuilderLoader;

/**
 * @covers Guzzle\Service\Builder\ServiceBuilderLoader
 */
class ServiceBuilderLoaderTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testBuildsServiceBuilders()
    {
        $arrayFactory = new ServiceBuilderLoader();

        $data = array(
            'services' => array(
                'abstract' => array(
                    'params' => array(
                        'access_key' => 'xyz',
                        'secret' => 'abc',
                    ),
                ),
                'foo' => array(
                    'extends' => 'abstract',
                    'params' => array(
                        'baz' => 'bar',
                    ),
                ),
                'mock' => array(
                    'extends' => 'abstract',
                    'params' => array(
                        'username' => 'foo',
                        'password' => 'baz',
                        'subdomain' => 'bar',
                    )
                )
            )
        );

        $builder = $arrayFactory->load($data);

        // Ensure that services were parsed
        $this->assertTrue(isset($builder['mock']));
        $this->assertTrue(isset($builder['abstract']));
        $this->assertTrue(isset($builder['foo']));
        $this->assertFalse(isset($builder['jimmy']));
    }

    /**
     * @expectedException Guzzle\Service\Exception\ServiceNotFoundException
     * @expectedExceptionMessage foo is trying to extend a non-existent service: abstract
     */
    public function testThrowsExceptionWhenExtendingNonExistentService()
    {
        $arrayFactory = new ServiceBuilderLoader();

        $data = array(
            'services' => array(
                'foo' => array(
                    'extends' => 'abstract'
                )
            )
        );

        $builder = $arrayFactory->load($data);
    }

    public function testAllowsGlobalParameterOverrides()
    {
        $arrayFactory = new ServiceBuilderLoader();

        $data = array(
            'services' => array(
                'foo' => array(
                    'params' => array(
                        'foo' => 'baz',
                        'bar' => 'boo'
                    )
                )
            )
        );

        $builder = $arrayFactory->load($data, array(
            'bar' => 'jar',
            'far' => 'car'
        ));

        $compiled = json_decode($builder->serialize(), true);
        $this->assertEquals(array(
            'foo' => 'baz',
            'bar' => 'jar',
            'far' => 'car'
        ), $compiled['foo']['params']);
    }

    public function tstDoesNotErrorOnCircularReferences()
    {
        $arrayFactory = new ServiceBuilderLoader();
        $arrayFactory->load(array(
            'services' => array(
                'too' => array('extends' => 'ball'),
                'ball' => array('extends' => 'too'),
            )
        ));
    }

    public function configProvider()
    {
        $foo = array(
            'extends' => 'bar',
            'class'   => 'stdClass',
            'params'  => array('a' => 'test', 'b' => '456')
        );

        return array(
            array(
                // Does not extend the existing `foo` service but overwrites it
                array(
                    'services' => array(
                        'foo' => $foo,
                        'bar' => array('params' => array('baz' => '123'))
                    )
                ),
                array(
                    'services' => array(
                        'foo' => array('class' => 'Baz')
                    )
                ),
                array(
                    'services' => array(
                        'foo' => array('class' => 'Baz'),
                        'bar' => array('params' => array('baz' => '123'))
                    )
                )
            ),
            array(
                // Extends the existing `foo` service
                array(
                    'services' => array(
                        'foo' => $foo,
                        'bar' => array('params' => array('baz' => '123'))
                    )
                ),
                array(
                    'services' => array(
                        'foo' => array(
                            'extends' => 'foo',
                            'params' => array('b' => '123', 'c' => 'def')
                        )
                    )
                ),
                array(
                    'services' => array(
                        'foo' => array(
                            'extends' => 'bar',
                            'class' => 'stdClass',
                            'params' => array('a' => 'test', 'b' => '123', 'c' => 'def')
                        ),
                        'bar' => array('params' => array('baz' => '123'))
                    )
                )
            )
        );
    }

    /**
     * @dataProvider configProvider
     */
    public function testCombinesConfigs($a, $b, $c)
    {
        $l = new ServiceBuilderLoader();
        $m = new \ReflectionMethod($l, 'mergeData');
        $m->setAccessible(true);
        $this->assertEquals($c, $m->invoke($l, $a, $b));
    }
}
<?php

namespace Guzzle\Tests\Service;

use Guzzle\Plugin\History\HistoryPlugin;
use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Service\Client;

/**
 * @covers Guzzle\Service\Builder\ServiceBuilder
 */
class ServiceBuilderTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $arrayData = array(
        'michael.mock' => array(
            'class' => 'Guzzle\Tests\Service\Mock\MockClient',
            'params' => array(
                'username' => 'michael',
                'password' => 'testing123',
                'subdomain' => 'michael',
            ),
        ),
        'billy.mock' => array(
            'alias' => 'Hello!',
            'class' => 'Guzzle\Tests\Service\Mock\MockClient',
            'params' => array(
                'username' => 'billy',
                'password' => 'passw0rd',
                'subdomain' => 'billy',
            ),
        ),
        'billy.testing' => array(
            'extends' => 'billy.mock',
            'params' => array(
                'subdomain' => 'test.billy',
            ),
        ),
        'missing_params' => array(
            'extends' => 'billy.mock'
        )
    );

    public function testAllowsSerialization()
    {
        $builder = ServiceBuilder::factory($this->arrayData);
        $cached = unserialize(serialize($builder));
        $this->assertEquals($cached, $builder);
    }

    public function testDelegatesFactoryMethodToAbstractFactory()
    {
        $builder = ServiceBuilder::factory($this->arrayData);
        $c = $builder->get('michael.mock');
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $c);
    }

    /**
     * @expectedException Guzzle\Service\Exception\ServiceNotFoundException
     * @expectedExceptionMessage No service is registered as foobar
     */
    public function testThrowsExceptionWhenGettingInvalidClient()
    {
        ServiceBuilder::factory($this->arrayData)->get('foobar');
    }

    public function testStoresClientCopy()
    {
        $builder = ServiceBuilder::factory($this->arrayData);
        $client = $builder->get('michael.mock');
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client);
        $this->assertEquals('http://127.0.0.1:8124/v1/michael', $client->getBaseUrl());
        $this->assertEquals($client, $builder->get('michael.mock'));

        // Get another client but throw this one away
        $client2 = $builder->get('billy.mock', true);
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client2);
        $this->assertEquals('http://127.0.0.1:8124/v1/billy', $client2->getBaseUrl());

        // Make sure the original client is still there and set
        $this->assertTrue($client === $builder->get('michael.mock'));

        // Create a new billy.mock client that is stored
        $client3 = $builder->get('billy.mock');

        // Make sure that the stored billy.mock client is equal to the other stored client
        $this->assertTrue($client3 === $builder->get('billy.mock'));

        // Make sure that this client is not equal to the previous throwaway client
        $this->assertFalse($client2 === $builder->get('billy.mock'));
    }

    public function testBuildersPassOptionsThroughToClients()
    {
        $s = new ServiceBuilder(array(
            'michael.mock' => array(
                'class' => 'Guzzle\Tests\Service\Mock\MockClient',
                'params' => array(
                    'base_url' => 'http://www.test.com/',
                    'subdomain' => 'michael',
                    'password' => 'test',
                    'username' => 'michael',
                    'curl.curlopt_proxyport' => 8080
                )
            )
        ));

        $c = $s->get('michael.mock');
        $this->assertEquals(8080, $c->getConfig('curl.curlopt_proxyport'));
    }

    public function testUsesTheDefaultBuilderWhenNoBuilderIsSpecified()
    {
        $s = new ServiceBuilder(array(
            'michael.mock' => array(
                'class' => 'Guzzle\Tests\Service\Mock\MockClient',
                'params' => array(
                    'base_url' => 'http://www.test.com/',
                    'subdomain' => 'michael',
                    'password' => 'test',
                    'username' => 'michael',
                    'curl.curlopt_proxyport' => 8080
                )
            )
        ));

        $c = $s->get('michael.mock');
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $c);
    }

    public function testUsedAsArray()
    {
        $b = ServiceBuilder::factory($this->arrayData);
        $this->assertTrue($b->offsetExists('michael.mock'));
        $this->assertFalse($b->offsetExists('not_there'));
        $this->assertInstanceOf('Guzzle\Service\Client', $b['michael.mock']);

        unset($b['michael.mock']);
        $this->assertFalse($b->offsetExists('michael.mock'));

        $b['michael.mock'] = new Client('http://www.test.com/');
        $this->assertInstanceOf('Guzzle\Service\Client', $b['michael.mock']);
    }

    public function testFactoryCanCreateFromJson()
    {
        $tmp = sys_get_temp_dir() . '/test.js';
        file_put_contents($tmp, json_encode($this->arrayData));
        $b = ServiceBuilder::factory($tmp);
        unlink($tmp);
        $s = $b->get('billy.testing');
        $this->assertEquals('test.billy', $s->getConfig('subdomain'));
        $this->assertEquals('billy', $s->getConfig('username'));
    }

    public function testFactoryCanCreateFromArray()
    {
        $b = ServiceBuilder::factory($this->arrayData);
        $s = $b->get('billy.testing');
        $this->assertEquals('test.billy', $s->getConfig('subdomain'));
        $this->assertEquals('billy', $s->getConfig('username'));
    }

    public function testFactoryDoesNotRequireParams()
    {
        $b = ServiceBuilder::factory($this->arrayData);
        $s = $b->get('missing_params');
        $this->assertEquals('billy', $s->getConfig('username'));
    }

    public function testBuilderAllowsReferencesBetweenClients()
    {
        $builder = ServiceBuilder::factory(array(
            'a' => array(
                'class' => 'Guzzle\Tests\Service\Mock\MockClient',
                'params' => array(
                    'other_client' => '{b}',
                    'username'     => 'x',
                    'password'     => 'y',
                    'subdomain'    => 'z'
                )
            ),
            'b' => array(
                'class' => 'Guzzle\Tests\Service\Mock\MockClient',
                'params' => array(
                    'username'  => '1',
                    'password'  => '2',
                    'subdomain' => '3'
                )
            )
        ));

        $client = $builder['a'];
        $this->assertEquals('x', $client->getConfig('username'));
        $this->assertSame($builder['b'], $client->getConfig('other_client'));
        $this->assertEquals('1', $builder['b']->getConfig('username'));
    }

    public function testEmitsEventsWhenClientsAreCreated()
    {
        // Ensure that the client signals that it emits an event
        $this->assertEquals(array('service_builder.create_client'), ServiceBuilder::getAllEvents());

        // Create a test service builder
        $builder = ServiceBuilder::factory(array(
            'a' => array(
                'class' => 'Guzzle\Tests\Service\Mock\MockClient',
                'params' => array(
                    'username'  => 'test',
                    'password'  => '123',
                    'subdomain' => 'z'
                )
            )
        ));

        // Add an event listener to pick up client creation events
        $emits = 0;
        $builder->getEventDispatcher()->addListener('service_builder.create_client', function($event) use (&$emits) {
            $emits++;
        });

        // Get the 'a' client by name
        $client = $builder->get('a');

        // Ensure that the event was emitted once, and that the client was present
        $this->assertEquals(1, $emits);
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client);
    }

    public function testCanAddGlobalParametersToServicesOnLoad()
    {
        $builder = ServiceBuilder::factory($this->arrayData, array(
            'username'  => 'fred',
            'new_value' => 'test'
        ));

        $data = json_decode($builder->serialize(), true);

        foreach ($data as $service) {
            $this->assertEquals('fred', $service['params']['username']);
            $this->assertEquals('test', $service['params']['new_value']);
        }
    }

    public function testAddsGlobalPlugins()
    {
        $b = new ServiceBuilder($this->arrayData);
        $b->addGlobalPlugin(new HistoryPlugin());
        $s = $b->get('michael.mock');
        $this->assertTrue($s->getEventDispatcher()->hasListeners('request.sent'));
    }

    public function testCanGetData()
    {
        $b = new ServiceBuilder($this->arrayData);
        $this->assertEquals($this->arrayData['michael.mock'], $b->getData('michael.mock'));
        $this->assertNull($b->getData('ewofweoweofe'));
    }

    public function testCanGetByAlias()
    {
        $b = new ServiceBuilder($this->arrayData);
        $this->assertSame($b->get('billy.mock'), $b->get('Hello!'));
    }

    public function testCanOverwriteParametersForThrowawayClients()
    {
        $b = new ServiceBuilder($this->arrayData);

        $c1 = $b->get('michael.mock');
        $this->assertEquals('michael', $c1->getConfig('username'));

        $c2 = $b->get('michael.mock', array('username' => 'jeremy'));
        $this->assertEquals('jeremy', $c2->getConfig('username'));
    }

    public function testGettingAThrowawayClientWithParametersDoesNotAffectGettingOtherClients()
    {
        $b = new ServiceBuilder($this->arrayData);

        $c1 = $b->get('michael.mock', array('username' => 'jeremy'));
        $this->assertEquals('jeremy', $c1->getConfig('username'));

        $c2 = $b->get('michael.mock');
        $this->assertEquals('michael', $c2->getConfig('username'));
    }

    public function testCanUseArbitraryData()
    {
        $b = new ServiceBuilder();
        $b['a'] = 'foo';
        $this->assertTrue(isset($b['a']));
        $this->assertEquals('foo', $b['a']);
        unset($b['a']);
        $this->assertFalse(isset($b['a']));
    }

    public function testCanRegisterServiceData()
    {
        $b = new ServiceBuilder();
        $b['a'] = array(
            'class' => 'Guzzle\Tests\Service\Mock\MockClient',
            'params' => array(
                'username' => 'billy',
                'password' => 'passw0rd',
                'subdomain' => 'billy',
            )
        );
        $this->assertTrue(isset($b['a']));
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $b['a']);
        $client = $b['a'];
        unset($b['a']);
        $this->assertFalse(isset($b['a']));
        // Ensure that instantiated clients can be registered
        $b['mock'] = $client;
        $this->assertSame($client, $b['mock']);
    }
}
<?php

namespace Guzzle\Tests\Service\Exception;

use Guzzle\Service\Exception\ValidationException;

class ValidationExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testCanSetAndRetrieveErrors()
    {
        $errors = array('foo', 'bar');

        $e = new ValidationException('Foo');
        $e->setErrors($errors);
        $this->assertEquals($errors, $e->getErrors());
    }
}
<?php

namespace Guzzle\Tests\Service\Exception;

use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Http\Message\Request;
use Guzzle\Service\Exception\CommandTransferException;
use Guzzle\Tests\Service\Mock\Command\MockCommand;

/**
 * @covers Guzzle\Service\Exception\CommandTransferException
 */
class CommandTransferExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testStoresCommands()
    {
        $c1 = new MockCommand();
        $c2 = new MockCommand();
        $e = new CommandTransferException('Test');
        $e->addSuccessfulCommand($c1)->addFailedCommand($c2);
        $this->assertSame(array($c1), $e->getSuccessfulCommands());
        $this->assertSame(array($c2), $e->getFailedCommands());
        $this->assertSame(array($c1, $c2), $e->getAllCommands());
    }

    public function testConvertsMultiExceptionIntoCommandTransfer()
    {
        $r1 = new Request('GET', 'http://foo.com');
        $r2 = new Request('GET', 'http://foobaz.com');
        $e = new MultiTransferException('Test', 123);
        $e->addSuccessfulRequest($r1)->addFailedRequest($r2);
        $ce = CommandTransferException::fromMultiTransferException($e);

        $this->assertInstanceOf('Guzzle\Service\Exception\CommandTransferException', $ce);
        $this->assertEquals('Test', $ce->getMessage());
        $this->assertEquals(123, $ce->getCode());
        $this->assertSame(array($r1), $ce->getSuccessfulRequests());
        $this->assertSame(array($r2), $ce->getFailedRequests());
    }

    public function testCanRetrieveExceptionForCommand()
    {
        $r1 = new Request('GET', 'http://foo.com');
        $e1 = new \Exception('foo');
        $c1 = $this->getMockBuilder('Guzzle\Tests\Service\Mock\Command\MockCommand')
            ->setMethods(array('getRequest'))
            ->getMock();
        $c1->expects($this->once())->method('getRequest')->will($this->returnValue($r1));

        $e = new MultiTransferException('Test', 123);
        $e->addFailedRequestWithException($r1, $e1);
        $ce = CommandTransferException::fromMultiTransferException($e);
        $ce->addFailedCommand($c1);

        $this->assertSame($e1, $ce->getExceptionForFailedCommand($c1));
    }

    public function testAddsNonRequestExceptions()
    {
        $e = new MultiTransferException();
        $e->add(new \Exception('bar'));
        $e->addFailedRequestWithException(new Request('GET', 'http://www.foo.com'), new \Exception('foo'));
        $ce = CommandTransferException::fromMultiTransferException($e);
        $this->assertEquals(2, count($ce));
    }
}
<?php

namespace Guzzle\Tests\Service\Exception;

use Guzzle\Service\Exception\InconsistentClientTransferException;

class InconsistentClientTransferExceptionTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testStoresCommands()
    {
        $items = array('foo', 'bar');
        $e = new InconsistentClientTransferException($items);
        $this->assertEquals($items, $e->getCommands());
    }
}
<?php

namespace Guzzle\Tests\Service;

use Guzzle\Inflection\Inflector;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Client;
use Guzzle\Service\Exception\CommandTransferException;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Tests\Service\Mock\Command\MockCommand;
use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Service\Command\AbstractCommand;

/**
 * @group server
 * @covers Guzzle\Service\Client
 */
class ClientTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected $service;
    protected $serviceTest;

    public function setUp()
    {
        $this->serviceTest = new ServiceDescription(array(
            'test_command' => new Operation(array(
                'doc' => 'documentationForCommand',
                'method' => 'DELETE',
                'class' => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand',
                'args' => array(
                    'bucket' => array(
                        'required' => true
                    ),
                    'key' => array(
                        'required' => true
                    )
                )
            ))
        ));

        $this->service = ServiceDescription::factory(__DIR__ . '/../TestData/test_service.json');
    }

    public function testAllowsCustomClientParameters()
    {
        $client = new Mock\MockClient(null, array(
            Client::COMMAND_PARAMS => array(AbstractCommand::RESPONSE_PROCESSING => 'foo')
        ));
        $command = $client->getCommand('mock_command');
        $this->assertEquals('foo', $command->get(AbstractCommand::RESPONSE_PROCESSING));
    }

    public function testFactoryCreatesClient()
    {
        $client = Client::factory(array(
            'base_url' => 'http://www.test.com/',
            'test' => '123'
        ));

        $this->assertEquals('http://www.test.com/', $client->getBaseUrl());
        $this->assertEquals('123', $client->getConfig('test'));
    }

    public function testFactoryDoesNotRequireBaseUrl()
    {
        $client = Client::factory();
    }

    public function testDescribesEvents()
    {
        $this->assertInternalType('array', Client::getAllEvents());
    }

    public function testExecutesCommands()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");

        $client = new Client($this->getServer()->getUrl());
        $cmd = new MockCommand();
        $client->execute($cmd);

        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $cmd->getResponse());
        $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $cmd->getResult());
        $this->assertEquals(1, count($this->getServer()->getReceivedRequests(false)));
    }

    public function testExecutesCommandsWithArray()
    {
        $client = new Client('http://www.test.com/');
        $client->getEventDispatcher()->addSubscriber(new MockPlugin(array(
            new Response(200),
            new Response(200)
        )));

        // Create a command set and a command
        $set = array(new MockCommand(), new MockCommand());
        $client->execute($set);

        // Make sure it sent
        $this->assertTrue($set[0]->isExecuted());
        $this->assertTrue($set[1]->isExecuted());
    }

    /**
     * @expectedException Guzzle\Common\Exception\InvalidArgumentException
     */
    public function testThrowsExceptionWhenInvalidCommandIsExecuted()
    {
        $client = new Client();
        $client->execute(new \stdClass());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testThrowsExceptionWhenMissingCommand()
    {
        $client = new Client();

        $mock = $this->getMock('Guzzle\\Service\\Command\\Factory\\FactoryInterface');
        $mock->expects($this->any())
             ->method('factory')
             ->with($this->equalTo('test'))
             ->will($this->returnValue(null));

        $client->setCommandFactory($mock);
        $client->getCommand('test');
    }

    public function testCreatesCommandsUsingCommandFactory()
    {
        $mockCommand = new MockCommand();

        $client = new Mock\MockClient();
        $mock = $this->getMock('Guzzle\\Service\\Command\\Factory\\FactoryInterface');
        $mock->expects($this->any())
             ->method('factory')
             ->with($this->equalTo('foo'))
             ->will($this->returnValue($mockCommand));

        $client->setCommandFactory($mock);

        $command = $client->getCommand('foo', array('acl' => '123'));
        $this->assertSame($mockCommand, $command);
        $command = $client->getCommand('foo', array('acl' => '123'));
        $this->assertSame($mockCommand, $command);
        $this->assertSame($client, $command->getClient());
    }

    public function testOwnsServiceDescription()
    {
        $client = new Mock\MockClient();
        $this->assertNull($client->getDescription());

        $description = $this->getMock('Guzzle\\Service\\Description\\ServiceDescription');
        $this->assertSame($client, $client->setDescription($description));
        $this->assertSame($description, $client->getDescription());
    }

    public function testOwnsResourceIteratorFactory()
    {
        $client = new Mock\MockClient();

        $method = new \ReflectionMethod($client, 'getResourceIteratorFactory');
        $method->setAccessible(TRUE);
        $rf1 = $method->invoke($client);

        $rf = $this->readAttribute($client, 'resourceIteratorFactory');
        $this->assertInstanceOf('Guzzle\\Service\\Resource\\ResourceIteratorClassFactory', $rf);
        $this->assertSame($rf1, $rf);

        $rf = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock');
        $client->setResourceIteratorFactory($rf);
        $this->assertNotSame($rf1, $rf);
    }

    public function testClientResetsRequestsBeforeExecutingCommands()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nHi",
            "HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nI"
        ));

        $client = new Mock\MockClient($this->getServer()->getUrl());

        $command = $client->getCommand('mock_command');
        $client->execute($command);
        $client->execute($command);
        $this->assertEquals('I', $command->getResponse()->getBody(true));
    }

    public function testClientCreatesIterators()
    {
        $client = new Mock\MockClient();

        $iterator = $client->getIterator('mock_command', array(
            'foo' => 'bar'
        ), array(
            'limit' => 10
        ));

        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
        $this->assertEquals(10, $this->readAttribute($iterator, 'limit'));

        $command = $this->readAttribute($iterator, 'originalCommand');
        $this->assertEquals('bar', $command->get('foo'));
    }

    public function testClientCreatesIteratorsWithNoOptions()
    {
        $client = new Mock\MockClient();
        $iterator = $client->getIterator('mock_command');
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
    }

    public function testClientCreatesIteratorsWithCommands()
    {
        $client = new Mock\MockClient();
        $command = new MockCommand();
        $iterator = $client->getIterator($command);
        $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator);
        $iteratorCommand = $this->readAttribute($iterator, 'originalCommand');
        $this->assertSame($command, $iteratorCommand);
    }

    public function testClientHoldsInflector()
    {
        $client = new Mock\MockClient();
        $this->assertInstanceOf('Guzzle\Inflection\MemoizingInflector', $client->getInflector());

        $inflector = new Inflector();
        $client->setInflector($inflector);
        $this->assertSame($inflector, $client->getInflector());
    }

    public function testClientAddsGlobalCommandOptions()
    {
        $client = new Mock\MockClient('http://www.foo.com', array(
            Client::COMMAND_PARAMS => array(
                'mesa' => 'bar'
            )
        ));
        $command = $client->getCommand('mock_command');
        $this->assertEquals('bar', $command->get('mesa'));
    }

    public function testSupportsServiceDescriptionBaseUrls()
    {
        $description = new ServiceDescription(array('baseUrl' => 'http://foo.com'));
        $client = new Client();
        $client->setDescription($description);
        $this->assertEquals('http://foo.com', $client->getBaseUrl());
    }

    public function testMergesDefaultCommandParamsCorrectly()
    {
        $client = new Mock\MockClient('http://www.foo.com', array(
            Client::COMMAND_PARAMS => array(
                'mesa' => 'bar',
                'jar'  => 'jar'
            )
        ));
        $command = $client->getCommand('mock_command', array('jar' => 'test'));
        $this->assertEquals('bar', $command->get('mesa'));
        $this->assertEquals('test', $command->get('jar'));
    }

    /**
     * @expectedException \Guzzle\Http\Exception\BadResponseException
     */
    public function testWrapsSingleCommandExceptions()
    {
        $client = new Mock\MockClient('http://foobaz.com');
        $mock = new MockPlugin(array(new Response(401)));
        $client->addSubscriber($mock);
        $client->execute(new MockCommand());
    }

    public function testWrapsMultipleCommandExceptions()
    {
        $client = new Mock\MockClient('http://foobaz.com');
        $mock = new MockPlugin(array(new Response(200), new Response(200), new Response(404), new Response(500)));
        $client->addSubscriber($mock);

        $cmds = array(new MockCommand(), new MockCommand(), new MockCommand(), new MockCommand());
        try {
            $client->execute($cmds);
        } catch (CommandTransferException $e) {
            $this->assertEquals(2, count($e->getFailedRequests()));
            $this->assertEquals(2, count($e->getSuccessfulRequests()));
            $this->assertEquals(2, count($e->getFailedCommands()));
            $this->assertEquals(2, count($e->getSuccessfulCommands()));

            foreach ($e->getSuccessfulCommands() as $c) {
                $this->assertTrue($c->getResponse()->isSuccessful());
            }

            foreach ($e->getFailedCommands() as $c) {
                $this->assertFalse($c->getRequest()->getResponse()->isSuccessful());
            }
        }
    }

    public function testGetCommandAfterTwoSetDescriptions()
    {
        $service1 = ServiceDescription::factory(__DIR__ . '/../TestData/test_service.json');
        $service2 = ServiceDescription::factory(__DIR__ . '/../TestData/test_service_3.json');

        $client = new Mock\MockClient();

        $client->setDescription($service1);
        $client->getCommand('foo_bar');
        $client->setDescription($service2);
        $client->getCommand('baz_qux');
    }
}
<?php

namespace Guzzle\Tests\Service;

use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Service\CachingConfigLoader;
use Doctrine\Common\Cache\ArrayCache;

/**
 * @covers Guzzle\Service\CachingConfigLoader
 */
class CachingConfigLoaderTest extends \Guzzle\Tests\GuzzleTestCase
{
    public function testLoadsPhpFileIncludes()
    {
        $cache = new DoctrineCacheAdapter(new ArrayCache());
        $loader = $this->getMockBuilder('Guzzle\Service\ConfigLoaderInterface')
            ->setMethods(array('load'))
            ->getMockForAbstractClass();
        $data = array('foo' => 'bar');
        $loader->expects($this->once())
            ->method('load')
            ->will($this->returnValue($data));
        $cache = new CachingConfigLoader($loader, $cache);
        $this->assertEquals($data, $cache->load('foo'));
        $this->assertEquals($data, $cache->load('foo'));
    }

    public function testDoesNotCacheArrays()
    {
        $cache = new DoctrineCacheAdapter(new ArrayCache());
        $loader = $this->getMockBuilder('Guzzle\Service\ConfigLoaderInterface')
            ->setMethods(array('load'))
            ->getMockForAbstractClass();
        $data = array('foo' => 'bar');
        $loader->expects($this->exactly(2))
            ->method('load')
            ->will($this->returnValue($data));
        $cache = new CachingConfigLoader($loader, $cache);
        $this->assertEquals($data, $cache->load(array()));
        $this->assertEquals($data, $cache->load(array()));
    }
}
=======================
Using a service builder
=======================

The best way to instantiate Guzzle web service clients is to let Guzzle handle building the clients for you using a
ServiceBuilder. A ServiceBuilder is responsible for creating concrete client objects based on configuration settings
and helps to manage credentials for different environments.

You don't have to use a service builder, but they help to decouple your application from concrete classes and help to
share configuration data across multiple clients. Consider the following example. Here we are creating two clients that
require the same API public key and secret key. The clients are created using their ``factory()`` methods.

.. code-block:: php

    use MyService\FooClient;
    use MyService\BarClient;

    $foo = FooClient::factory(array(
        'key'    => 'abc',
        'secret' => '123',
        'custom' => 'and above all'
    ));

    $bar = BarClient::factory(array(
        'key'    => 'abc',
        'secret' => '123',
        'custom' => 'listen to me'
    ));

The redundant specification of the API keys can be removed using a service builder.

.. code-block:: php

    use Guzzle\Service\Builder\ServiceBuilder;

    $builder = ServiceBuilder::factory(array(
        'services' => array(
            'abstract_client' => array(
                'params' => array(
                    'key'    => 'abc',
                    'secret' => '123'
                )
            ),
            'foo' => array(
                'extends' => 'abstract_client',
                'class'   => 'MyService\FooClient',
                'params'  => array(
                    'custom' => 'and above all'
                )
            ),
            'bar' => array(
                'extends' => 'abstract_client',
                'class'   => 'MyService\FooClient',
                'params'  => array(
                    'custom' => 'listen to me'
                )
            )
        )
    ));

    $foo = $builder->get('foo');
    $bar = $builder->get('bar');

You can make managing your API keys even easier by saving the service builder configuration in a JSON format in a
.json file.

Creating a service builder
--------------------------

A ServiceBuilder can source information from an array, an PHP include file that returns an array, or a JSON file.

.. code-block:: php

    use Guzzle\Service\Builder\ServiceBuilder;

    // Source service definitions from a JSON file
    $builder = ServiceBuilder::factory('services.json');

Sourcing data from an array
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Data can be source from a PHP array. The array must contain an associative ``services`` array that maps the name of a
client to the configuration information used by the service builder to create the client. Clients are given names
which are used to identify how a client is retrieved from a service builder. This can be useful for using multiple
accounts for the same service or creating development clients vs. production clients.

.. code-block:: php

    $services = array(
        'includes' => array(
            '/path/to/other/services.json',
            '/path/to/other/php_services.php'
        ),
        'services' => array(
            'abstract.foo' => array(
                'params' => array(
                    'username' => 'foo',
                    'password' => 'bar'
                )
            ),
            'bar' => array(
                'extends' => 'abstract.foo',
                'class'   => 'MyClientClass',
                'params'  => array(
                    'other' => 'abc'
                )
            )
        )
    );

A service builder configuration array contains two top-level array keys:

+------------+---------------------------------------------------------------------------------------------------------+
| Key        | Description                                                                                             |
+============+=========================================================================================================+
| includes   | Array of paths to JSON or PHP include files to include in the configuration.                            |
+------------+---------------------------------------------------------------------------------------------------------+
| services   | Associative array of defined services that can be created by the service builder. Each service can      |
|            | contain the following keys:                                                                             |
|            |                                                                                                         |
|            | +------------+----------------------------------------------------------------------------------------+ |
|            | | Key        | Description                                                                            | |
|            | +============+========================================================================================+ |
|            | | class      | The concrete class to instantiate that implements the                                  | |
|            | |            | ``Guzzle\Common\FromConfigInterface``.                                                 | |
|            | +------------+----------------------------------------------------------------------------------------+ |
|            | | extends    | The name of a previously defined service to extend from                                | |
|            | +------------+----------------------------------------------------------------------------------------+ |
|            | | params     | Associative array of parameters to pass to the factory method of the service it is     | |
|            | |            | instantiated                                                                           | |
|            | +------------+----------------------------------------------------------------------------------------+ |
|            | | alias      | An alias that can be used in addition to the array key for retrieving a client from    | |
|            | |            | the service builder.                                                                   | |
|            | +------------+----------------------------------------------------------------------------------------+ |
+------------+---------------------------------------------------------------------------------------------------------+

The first client defined, ``abstract.foo``, is used as a placeholder of shared configuration values. Any service
extending abstract.foo will inherit its params. As an example, this can be useful when clients share the same username
and password.

The next client, ``bar``, extends from ``abstract.foo`` using the ``extends`` attribute referencing the client from
which to extend. Additional parameters can be merged into the original service definition when extending a parent
service.

.. important::

    Each client that you intend to instantiate must specify a ``class`` attribute that references the full class name
    of the client being created. The class referenced in the ``class`` parameter must implement a static ``factory()``
    method that accepts an array or ``Guzzle\Common\Collection`` object and returns an instantiated object.

Sourcing from a PHP include
~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can create service builder configurations using a PHP include file. This can be useful if you wish to take
advantage of an opcode cache like APC to speed up the process of loading and processing the configuration. The PHP
include file is the same format as an array, but you simply create a PHP script that returns an array and save the
file with the .php file extension.

.. code-block:: php

    <?php return array('services' => '...');
    // Saved as config.php

This configuration file can then be used with a service builder.

.. code-block:: php

    $builder = ServiceBuilder::factory('/path/to/config.php');

Sourcing from a JSON document
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can use JSON documents to serialize your service descriptions. The JSON format uses the exact same structure as
the PHP array syntax, but it's just serialized using JSON.

.. code-block:: javascript

    {
        "includes": ["/path/to/other/services.json", "/path/to/other/php_services.php"],
        "services": {
            "abstract.foo": {
                "params": {
                    "username": "foo",
                    "password": "bar"
                }
            },
            "bar": {
                "extends": "abstract.foo",
                "class": "MyClientClass",
                "params": {
                    "other": "abc"
                }
            }
        }
    }

Referencing other clients in parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If one of your clients depends on another client as one of its parameters, you can reference that client by name by
enclosing the client's reference key in ``{}``.

.. code-block:: javascript

    {
        "services": {
            "token": {
                "class": "My\Token\TokenFactory",
                "params": {
                    "access_key": "xyz"
                }
            },
            "client": {
                "class": "My\Client",
                "params": {
                    "token_client": "{token}",
                    "version": "1.0"
                }
            }
        }
    }

When ``client`` is constructed by the service builder, the service builder will first create the ``token`` service
and then inject the token service into ``client``'s factory method in the ``token_client`` parameter.

Retrieving clients from a service builder
-----------------------------------------

Clients are referenced using a customizable name you provide in your service definition. The ServiceBuilder is a sort
of multiton object-- it will only instantiate a client once and return that client for subsequent retrievals. Clients
are retrieved by name (the array key used in the configuration) or by the ``alias`` setting of a service.

Here's an example of retrieving a client from your ServiceBuilder:

.. code-block:: php

    $client = $builder->get('foo');

    // You can also use the ServiceBuilder object as an array
    $client = $builder['foo'];

Creating throwaway clients
~~~~~~~~~~~~~~~~~~~~~~~~~~

You can get a "throwaway" client (a client that is not persisted by the ServiceBuilder) by passing ``true`` in the
second argument of ``ServiceBuilder::get()``. This allows you to create a client that will not be returned by other
parts of your code that use the service builder. Instead of passing ``true``, you can pass an array of configuration
settings that will override the configuration settings specified in the service builder.

.. code-block:: php

    // Get a throwaway client and overwrite the "custom" setting of the client
    $foo = $builder->get('foo', array(
        'custom' => 'in this world there are rules'
    ));

Getting raw configuration settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can get the raw configuration settings provided to the service builder for a specific service using the
``getData($name)`` method of a service builder. This method will null if the service was not found in the service
builder or an array of configuration settings if the service was found.

.. code-block:: php

    $data = $builder->getData('foo');
    echo $data['key'] . "\n";
    echo $data['secret'] . "\n";
    echo $data['custom'] . "\n";

Adding a plugin to all clients
------------------------------

You can add a plugin to all clients created by a service builder using the ``addGlobalPlugin($plugin)`` method of a
service builder and passing a ``Symfony\Component\EventDispatcher\EventSubscriberInterface`` object. The service builder
will then attach each global plugin to every client as it is created. This allows you to, for example, add a LogPlugin
to every request created by a service builder for easy debugging.

.. code-block:: php

    use Guzzle\Plugin\Log\LogPlugin;

    // Add a debug log plugin to every client as it is created
    $builder->addGlobalPlugin(LogPlugin::getDebugPlugin());

    $foo = $builder->get('foo');
    $foo->get('/')->send();
    // Should output all of the data sent over the wire

.. _service-builder-events:

Events emitted from a service builder
-------------------------------------

A ``Guzzle\Service\Builder\ServiceBuilder`` object emits the following events:

+-------------------------------+--------------------------------------------+-----------------------------------------+
| Event name                    | Description                                | Event data                              |
+===============================+============================================+=========================================+
| service_builder.create_client | Called when a client is created            | * client: The created client object     |
+-------------------------------+--------------------------------------------+-----------------------------------------+

.. code-block:: php

    use Guzzle\Common\Event;
    use Guzzle\Service\Builder\ServiceBuilder;

    $builder = ServiceBuilder::factory('/path/to/config.json');

    // Add an event listener to print out each client client as it is created
    $builder->getEventDispatcher()->addListener('service_builder.create_client', function (Event $e) {
        echo 'Client created: ' . get_class($e['client']) . "\n";
    });

    $foo = $builder->get('foo');
    // Should output the class used for the "foo" client
===========================
Guzzle service descriptions
===========================

Guzzle allows you to serialize HTTP requests and parse HTTP responses using a DSL called a service descriptions.
Service descriptions define web service APIs by documenting each operation, the operation's parameters, validation
options for each parameter, an operation's response, how the response is parsed, and any errors that can be raised for
an operation. Writing a service description for a web service allows you to more quickly consume a web service than
writing concrete commands for each web service operation.

Guzzle service descriptions can be representing using a PHP array or JSON document. Guzzle's service descriptions are
heavily inspired by `Swagger <http://swagger.wordnik.com/>`_.

Service description schema
==========================

A Guzzle Service description must match the following JSON schema document. This document can also serve as a guide when
implementing a Guzzle service description.

Download the schema here: :download:`Guzzle JSON schema document </_downloads/guzzle-schema-1.0.json>`

.. class:: overflow-height-500px

    .. literalinclude:: ../_downloads/guzzle-schema-1.0.json
        :language: json

Top-level attributes
--------------------

Service descriptions are comprised of the following top-level attributes:

.. code-block:: json

    {
        "name": "string",
        "apiVersion": "string|number",
        "baseUrl": "string",
        "description": "string",
        "operations": {},
        "models": {},
        "includes": ["string.php", "string.json"]
    }

+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| Property Name                           | Value                   | Description                                                                                                           |
+=========================================+=========================+=======================================================================================================================+
| name                                    | string                  | Name of the web service                                                                                               |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| apiVersion                              | string|number           | Version identifier that the service description is compatible with                                                    |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| baseUrl or basePath                     | string                  | Base URL of the web service. Any relative URI specified in an operation will be merged with the baseUrl using the     |
|                                         |                         | process defined in RFC 2396. Some clients require custom logic to determine the baseUrl. In those cases, it is best   |
|                                         |                         | to not include a baseUrl in the service description, but rather allow the factory method of the client to configure   |
|                                         |                         | the client’s baseUrl.                                                                                                 |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| description                             | string                  | Short summary of the web service                                                                                      |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| operations                              | object containing       | Operations of the service. The key is the name of the operation and value is the attributes of the operation.         |
|                                         | :ref:`operation-schema` |                                                                                                                       |
|                                         |                         |                                                                                                                       |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| models                                  | object containing       | Schema models that can be referenced throughout the service description. Models can be used to define how an HTTP     |
|                                         | :ref:`model-schema`     | response is parsed into a ``Guzzle\Service\Resource\Model`` object when an operation uses a ``model`` ``responseType``|
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| includes                                | array of .js,           | Service description files to include and extend from (can be a .json, .js, or .php file)                              |
|                                         | .json, or .php          |                                                                                                                       |
|                                         | files.                  |                                                                                                                       |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+
| (any additional properties)             | mixed                   | Any additional properties specified as top-level attributes are allowed and will be treated as arbitrary data         |
+-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+

.. _operation-schema:

Operations
----------

Operations are the actions that can be taken on a service. Each operation is given a unique name and has a distinct
endpoint and HTTP method. If an API has a ``DELETE /users/:id`` operation, a satisfactory operation name might be
``DeleteUser`` with a parameter of ``id`` that is inserted into the URI.

.. class:: overflow-height-250px

    .. code-block:: json

        {
            "operations": {
                "operationName": {
                    "extends": "string",
                    "httpMethod": "GET|POST|PUT|DELETE|PATCH|string",
                    "uri": "string",
                    "summary": "string",
                    "class": "string",
                    "responseClass": "string",
                    "responseNotes": "string",
                    "type": "string",
                    "description": "string",
                    "responseType": "primitive|class|(model by name)|documentation|(string)",
                    "deprecated": false,
                    "errorResponses": [
                        {
                            "code": 500,
                            "reason": "Unexpected Error",
                            "class": "string"
                        }
                    ],
                    "data": {
                        "foo": "bar",
                        "baz": "bam"
                    },
                    "parameters": {}
                }
            }
        }

.. csv-table::
   :header: "Property Name", "Value", "Description"
   :widths: 20, 15, 65

    "extends", "string", "Extend from another operation by name. The parent operation must be defined before the child."
    "httpMethod", "string", "HTTP method used with the operation (e.g. GET, POST, PUT, DELETE, PATCH, etc)"
    "uri", "string", "URI of the operation. The uri attribute can contain URI templates. The variables of the URI template are parameters of the operation with a location value of uri"
    "summary", "string", "Short summary of what the operation does"
    "class", "string", "Custom class to instantiate instead of the default Guzzle\\Service\\Command\\OperationCommand. Using this attribute allows you to define an operation using a service description, but allows more customized logic to be implemented in user-land code."
    "responseClass", "string", "Defined what is returned from the method. Can be a primitive, class name, or model name. You can specify the name of a class to return a more customized result from the operation (for example, a domain model object). When using the name of a PHP class, the class must implement ``Guzzle\Service\Command\ResponseClassInterface``."
    "responseNotes", "string", "A description of the response returned by the operation"
    "responseType", "string", "The type of response that the operation creates: one of primitive, class, model, or documentation. If not specified, this value will be automatically inferred based on whether or not there is a model matching the name, if a matching class name is found, or set to 'primitive' by default."
    "deprecated", "boolean", "Whether or not the operation is deprecated"
    "errorResponses", "array", "Errors that could occur while executing the operation. Each item of the array is an object that can contain a 'code' (HTTP response status code of the error), 'reason' (reason phrase or description of the error), and 'class' (an exception class that will be raised when this error is encountered)"
    "data", "object", "Any arbitrary data to associate with the operation"
    "parameters", "object containing :ref:`parameter-schema` objects", "Parameters of the operation. Parameters are used to define how input data is serialized into a HTTP request."
    "additionalParameters", "A single :ref:`parameter-schema` object", "Validation and serialization rules for any parameter supplied to the operation that was not explicitly defined."

additionalParameters
~~~~~~~~~~~~~~~~~~~~

When a webservice offers a large number of parameters that all are set in the same location (for example the query
string or a JSON document), defining each parameter individually can require a lot of time and repetition. Furthermore,
some web services allow for completely arbitrary parameters to be supplied for an operation. The
``additionalParameters`` attribute can be used to solve both of these issues.

As an example, we can define a Twitter API operation quite easily using ``additionalParameters``. The
GetMentions operation accepts a large number of query string parameters. Defining each of these parameters
is ideal because it provide much more introspection for the client and opens the possibility to use the description with
other tools (e.g. a documentation generator). However, you can very quickly provide a "catch-all" serialization rule
that will place any custom parameters supplied to an operation the generated request's query string parameters.

.. class:: overflow-height-250px

    .. code-block:: json

        {
            "name": "Twitter",
            "apiVersion": "1.1",
            "baseUrl": "https://api.twitter.com/1.1",
            "operations": {
                "GetMentions": {
                    "httpMethod": "GET",
                    "uri": "statuses/mentions_timeline.json",
                    "responseClass": "GetMentionsOutput",
                    "additionalParameters": {
                        "location": "query"
                    }
                }
            },
            "models": {
                "GetMentionsOutput": {
                    "type": "object",
                    "additionalProperties": {
                        "location": "json"
                    }
                }
            }
        }

responseClass
~~~~~~~~~~~~~

The ``responseClass`` attribute is used to define the return value of an operation (what is returned by calling the
``getResult()`` method of a command object). The value set in the responseClass attribute can be one of "primitive"
(meaning the result with be primitive type like a string), a class name meaning the result will be an instance of a
specific user-land class, or a model name meaning the result will be a ``Guzzle\Service\Resource\Model`` object that
uses a :ref:`model schema <model-schema>` to define how the HTTP response is parsed.

.. note::

    Using a class name with a ``responseClass`` will only work if it is supported by the ``class`` that is instantiated
    for the operation. Keep this in mind when specifying a custom ``class`` attribute that points to a custom
    ``Guzzle\Service\Command\CommandInterface`` class. The default ``class``,
    ``Guzzle\Service\Command\OperationCommand``, does support setting custom ``class`` attributes.

You can specify the name of a class to return a more customized result from the operation (for example, a domain model
object). When using the name of a PHP class, the class must implement ``Guzzle\Service\Command\ResponseClassInterface``.
Here's a very simple example of implementing a custom responseClass object.

.. code-block:: json

    {
        "operations": {
            "test": {
                "responseClass": "MyApplication\\User"
            }
        }
    }

.. code-block:: php

    namespace MyApplication;

    use Guzzle\Service\Command\ResponseClassInterface;
    use Guzzle\Service\Command\OperationCommand;

    class User implements ResponseClassInterface
    {
        protected $name;

        public static function fromCommand(OperationCommand $command)
        {
            $response = $command->getResponse();
            $xml = $response->xml();

            return new self((string) $xml->name);
        }

        public function __construct($name)
        {
            $this->name = $name;
        }
    }

errorResponses
~~~~~~~~~~~~~~

``errorResponses`` is an array containing objects that define the errors that could occur while executing the
operation. Each item of the array is an object that can contain a 'code' (HTTP response status code of the error),
'reason' (reason phrase or description of the error), and 'class' (an exception class that will be raised when this
error is encountered).

ErrorResponsePlugin
^^^^^^^^^^^^^^^^^^^

Error responses are by default only used for documentation. If you don't need very complex exception logic for your web
service errors, then you can use the ``Guzzle\Plugin\ErrorResponse\ErrorResponsePlugin`` to automatically throw defined
exceptions when one of the ``errorResponse`` rules are matched. The error response plugin will listen for the
``request.complete`` event of a request created by a command object. Every response (including a successful response) is
checked against the list of error responses for an exact match using the following order of checks:

1. Does the errorResponse have a defined ``class``?
2. Is the errorResponse ``code`` equal to the status code of the response?
3. Is the errorResponse ``reason`` equal to the reason phrase of the response?
4. Throw the exception stored in the ``class`` attribute of the errorResponse.

The ``class`` attribute must point to a class that implements
``Guzzle\Plugin\ErrorResponse\ErrorResponseExceptionInterface``. This interface requires that an error response class
implements ``public static function fromCommand(CommandInterface $command, Response $response)``. This method must
return an object that extends from ``\Exception``. After an exception is returned, it is thrown by the plugin.

.. _parameter-schema:

Parameter schema
----------------

Parameters in both operations and models are represented using the
`JSON schema <http://tools.ietf.org/id/draft-zyp-json-schema-04.html>`_ syntax.

.. csv-table::
   :header: "Property Name", "Value", "Description"
   :widths: 20, 15, 65

    "name", "string", "Unique name of the parameter"
    "type", "string|array", "Type of variable (string, number, integer, boolean, object, array, numeric, null, any). Types are using for validation and determining the structure of a parameter. You can use a union type by providing an array of simple types. If one of the union types matches the provided value, then the value is valid."
    "instanceOf", "string", "When the type is an object, you can specify the class that the object must implement"
    "required", "boolean", "Whether or not the parameter is required"
    "default", "mixed", "Default value to use if no value is supplied"
    "static", "boolean", "Set to true to specify that the parameter value cannot be changed from the default setting"
    "description", "string", "Documentation of the parameter"
    "location", "string", "The location of a request used to apply a parameter. Custom locations can be registered with a command, but the defaults are uri, query, statusCode, reasonPhrase, header, body, json, xml, postField, postFile, responseBody"
    "sentAs", "string", "Specifies how the data being modeled is sent over the wire. For example, you may wish to include certain headers in a response model that have a normalized casing of FooBar, but the actual header is x-foo-bar. In this case, sentAs would be set to x-foo-bar."
    "filters", "array", "Array of functions to to run a parameter value through."

filters
~~~~~~~

Each value in the array must be a string containing the full class path to a static method or an array of complex
filter information. You can specify static methods of classes using the full namespace class name followed by
"::" (e.g. ``FooBar::baz()``). Some filters require arguments in order to properly filter a value. For complex filters,
use an object containing a ``method`` attribute pointing to a function, and an ``args`` attribute containing an
array of positional arguments to pass to the function. Arguments can contain keywords that are replaced when filtering
a value: ``@value`` is replaced with the value being filtered, and ``@api`` is replaced with the actual Parameter
object.

.. code-block:: json

    {
        "filters": [
            "strtolower",
            {
                "method": "MyClass::convertString",
                "args": [ "test", "@value", "@api" ]
            }
        ]
    }

The above example will filter a parameter using ``strtolower``. It will then call the ``convertString`` static method
of ``MyClass``, passing in "test", the actual value of the parameter, and a ``Guzzle\Service\Description\Parameter``
object.

Operation parameter location attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The location field of top-level parameters control how a parameter is serialized when generating a request.

uri location
^^^^^^^^^^^^

Parameters are injected into the ``uri`` attribute of the operation using
`URI-template expansion <http://tools.ietf.org/html/rfc6570>`_.

.. code-block:: json

    {
        "operations": {
            "uriTest": {
                "uri": "/test/{testValue}",
                "parameters": {
                    "testValue": {
                        "location": "uri"
                    }
                }
            }
        }
    }

query location
^^^^^^^^^^^^^^

Parameters are injected into the query string of a request. Query values can be nested, which would result in a PHP
style nested query string. The name of a parameter is the default name of the query string parameter added to the
request. You can override this behavior by specifying the ``sentAs`` attribute on the parameter.

.. code-block:: json

    {
        "operations": {
            "queryTest": {
                "parameters": {
                    "testValue": {
                        "location": "query",
                        "sentAs": "test_value"
                    }
                }
            }
        }
    }

header location
^^^^^^^^^^^^^^^

Parameters are injected as headers on an HTTP request. The name of the parameter is used as the name of the header by
default. You can change the name of the header created by the parameter using the ``sentAs`` attribute.

Headers that are of type ``object`` will be added as multiple headers to a request using the key of the input array as
the header key. Setting a ``sentAs`` attribute along with a type ``object`` will use the value of ``sentAs`` as a
prefix for each header key.

body location
^^^^^^^^^^^^^

Parameters are injected as the body of a request. The input of these parameters may be anything that can be cast to a
string or a ``Guzzle\Http\EntityBodyInterface`` object.

postField location
^^^^^^^^^^^^^^^^^^

Parameters are inserted as POST fields in a request. Nested values may be supplied and will be represented using
PHP style nested query strings. The POST field name is the same as the parameter name by default. You can use the
``sentAs`` parameter to override the POST field name.

postFile location
^^^^^^^^^^^^^^^^^

Parameters are added as POST files. A postFile value may be a string pointing to a local filename or a
``Guzzle\Http\Message\PostFileInterface`` object. The name of the POST file will be the name of the parameter by
default. You can use a custom POST file name by using the ``sentAs`` attribute.

Supports "string" and "array" types.

json location
^^^^^^^^^^^^^

Parameters are added to the body of a request as top level keys of a JSON document. Nested values may be specified,
with any number of nested ``Guzzle\Common\ToArrayInterface`` objects. When JSON parameters are specified, the
``Content-Type`` of the request will change to ``application/json`` if a ``Content-Type`` has not already been specified
on the request.

xml location
^^^^^^^^^^^^

Parameters are added to the body of a request as top level nodes of an XML document. Nested values may be specified,
with any number of nested ``Guzzle\Common\ToArrayInterface`` objects. When XML parameters are specified, the
``Content-Type`` of the request will change to ``application/xml`` if a ``Content-Type`` has not already been specified
on the request.

responseBody location
^^^^^^^^^^^^^^^^^^^^^

Specifies the EntityBody of a response. This can be used to download the response body to a file or a custom Guzzle
EntityBody object.

No location
^^^^^^^^^^^

If a parameter has no location attribute, then the parameter is simply used as a data value.

Other locations
^^^^^^^^^^^^^^^

Custom locations can be registered as new locations or override default locations if needed.

.. _model-schema:

Model Schema
------------

Models are used in service descriptions to provide generic JSON schema definitions that can be extended from or used in
``$ref`` attributes. Models can also be referenced in a ``responseClass`` attribute to provide valuable output to an
operation. Models are JSON schema documents and use the exact syntax and attributes used in parameters.

Response Models
~~~~~~~~~~~~~~~

Response models describe how a response is parsed into a ``Guzzle\Service\Resource\Model`` object. Response models are
always modeled as JSON schema objects. When an HTTP response is parsed using a response model, the rules specified on
each property of a response model will translate 1:1 as keys in a PHP associative array. When a ``sentAs`` attribute is
found in response model parameters, the value retrieved from the HTTP response is retrieved using the ``sentAs``
parameter but stored in the response model using the name of the parameter.

The location field of top-level parameters in a response model tell response parsers how data is retrieved from a
response.

statusCode location
^^^^^^^^^^^^^^^^^^^

Retrieves the status code of the response.

reasonPhrase location
^^^^^^^^^^^^^^^^^^^^^

Retrieves the reason phrase of the response.

header location
^^^^^^^^^^^^^^^

Retrieves a header from the HTTP response.

body location
^^^^^^^^^^^^^

Retrieves the body of an HTTP response.

json location
^^^^^^^^^^^^^

Retrieves a top-level parameter from a JSON document contained in an HTTP response.

You can use ``additionalProperties`` if the JSON document is wrapped in an outer array. This allows you to parse the
contents of each item in the array using the parsing rules defined in the ``additionalProperties`` schema.

xml location
^^^^^^^^^^^^

Retrieves a top-level node value from an XML document contained in an HTTP response.

Other locations
^^^^^^^^^^^^^^^

Custom locations can be registered as new locations or override default locations if needed.

Example service description
---------------------------

Let's say you're interacting with a web service called 'Foo' that allows for the following routes and methods::

    GET/POST   /users
    GET/DELETE /users/:id

The following JSON service description implements this simple web service:

.. class:: overflow-height-500px

    .. code-block:: json

        {
            "name": "Foo",
            "apiVersion": "2012-10-14",
            "baseUrl": "http://api.foo.com",
            "description": "Foo is an API that allows you to Baz Bar",
            "operations": {
                "GetUsers": {
                    "httpMethod": "GET",
                    "uri": "/users",
                    "summary": "Gets a list of users",
                    "responseClass": "GetUsersOutput"
                },
                "CreateUser": {
                    "httpMethod": "POST",
                    "uri": "/users",
                    "summary": "Creates a new user",
                    "responseClass": "CreateUserOutput",
                    "parameters": {
                        "name": {
                            "location": "json",
                            "type": "string"
                        },
                        "age": {
                            "location": "json",
                            "type": "integer"
                        }
                    }
                },
                "GetUser": {
                    "httpMethod": "GET",
                    "uri": "/users/{id}",
                    "summary": "Retrieves a single user",
                    "responseClass": "GetUserOutput",
                    "parameters": {
                        "id": {
                            "location": "uri",
                            "description": "User to retrieve by ID",
                            "required": true
                        }
                    }
                },
                "DeleteUser": {
                    "httpMethod": "DELETE",
                    "uri": "/users/{id}",
                    "summary": "Deletes a user",
                    "responseClass": "DeleteUserOutput",
                    "parameters": {
                        "id": {
                            "location": "uri",
                            "description": "User to delete by ID",
                            "required": true
                        }
                    }
                }
            },
            "models": {
                "GetUsersOutput": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {
                                "location": "json",
                                "type": "string"
                            },
                            "age": {
                                "location": "json",
                                "type": "integer"
                            }
                        }
                    }
                },
                "CreateUserOutput": {
                    "type": "object",
                    "properties": {
                        "id": {
                            "location": "json",
                            "type": "string"
                        },
                        "location": {
                            "location": "header",
                            "sentAs": "Location",
                            "type": "string"
                        }
                    }
                },
                "GetUserOutput": {
                    "type": "object",
                    "properties": {
                        "name": {
                            "location": "json",
                            "type": "string"
                        },
                        "age": {
                            "location": "json",
                            "type": "integer"
                        }
                    }
                },
                "DeleteUserOutput": {
                    "type": "object",
                    "properties": {
                        "status": {
                            "location": "statusCode",
                            "type": "integer"
                        }
                    }
                }
            }
        }

If you attach this service description to a client, you would completely configure the client to interact with the
Foo web service and provide valuable response models for each operation.

.. code-block:: php

    use Guzzle\Service\Description\ServiceDescription;

    $description = ServiceDescription::factory('/path/to/client.json');
    $client->setDescription($description);

    $command = $client->getCommand('DeleteUser', array('id' => 123));
    $responseModel = $client->execute($command);
    echo $responseModel['status'];

.. note::

    You can add the service description to your client's factory method or constructor.
======================
The web service client
======================

The ``Guzzle\Service`` namespace contains various abstractions that help to make it easier to interact with a web
service API, including commands, service descriptions, and resource iterators.

In this chapter, we'll build a simple `Twitter API client <https://dev.twitter.com/docs/api/1.1>`_.

Creating a client
=================

A class that extends from ``Guzzle\Service\Client`` or implements ``Guzzle\Service\ClientInterface`` must implement a
``factory()`` method in order to be used with a :doc:`service builder <using-the-service-builder>`.

Factory method
--------------

You can use the ``factory()`` method of a client directly if you do not need a service builder.

.. code-block:: php

    use mtdowling\TwitterClient;

    // Create a client and pass an array of configuration data
    $twitter = TwitterClient::factory(array(
        'consumer_key'    => '****',
        'consumer_secret' => '****',
        'token'           => '****',
        'token_secret'    => '****'
    ));

.. note::

    If you'd like to follow along, here's how to get your Twitter API credentials:

    1. Visit https://dev.twitter.com/apps
    2. Click on an application that you've created
    3. Click on the "OAuth tool" tab
    4. Copy all of the settings under "OAuth Settings"

Implementing a factory method
-----------------------------

Creating a client and its factory method is pretty simple. You just need to implement ``Guzzle\Service\ClientInterface``
or extend from ``Guzzle\Service\Client``.

.. code-block:: php

    namespace mtdowling;

    use Guzzle\Common\Collection;
    use Guzzle\Plugin\Oauth\OauthPlugin;
    use Guzzle\Service\Client;
    use Guzzle\Service\Description\ServiceDescription;

    /**
     * A simple Twitter API client
     */
    class TwitterClient extends Client
    {
        public static function factory($config = array())
        {
            // Provide a hash of default client configuration options
            $default = array('base_url' => 'https://api.twitter.com/1.1');

            // The following values are required when creating the client
            $required = array(
                'base_url',
                'consumer_key',
                'consumer_secret',
                'token',
                'token_secret'
            );

            // Merge in default settings and validate the config
            $config = Collection::fromConfig($config, $default, $required);

            // Create a new Twitter client
            $client = new self($config->get('base_url'), $config);

            // Ensure that the OauthPlugin is attached to the client
            $client->addSubscriber(new OauthPlugin($config->toArray()));

            return $client;
        }
    }

Service Builder
---------------

A service builder is used to easily create web service clients, provides a simple configuration driven approach to
creating clients, and allows you to share configuration settings across multiple clients. You can find out more about
Guzzle's service builder in :doc:`using-the-service-builder`.

.. code-block:: php

    use Guzzle\Service\Builder\ServiceBuilder;

    // Create a service builder and provide client configuration data
    $builder = ServiceBuilder::factory('/path/to/client_config.json');

    // Get the client from the service builder by name
    $twitter = $builder->get('twitter');

The above example assumes you have JSON data similar to the following stored in "/path/to/client_config.json":

.. code-block:: json

    {
        "services": {
            "twitter": {
                "class": "mtdowling\\TwitterClient",
                "params": {
                    "consumer_key": "****",
                    "consumer_secret": "****",
                    "token": "****",
                    "token_secret": "****"
                }
            }
        }
    }

.. note::

    A service builder becomes much more valuable when using multiple web service clients in a single application or
    if you need to utilize the same client with varying configuration settings (e.g. multiple accounts).

Commands
========

Commands are a concept in Guzzle that helps to hide the underlying implementation of an API by providing an easy to use
parameter driven object for each action of an API. A command is responsible for accepting an array of configuration
parameters, serializing an HTTP request, and parsing an HTTP response. Following the
`command pattern <http://en.wikipedia.org/wiki/Command_pattern>`_, commands in Guzzle offer a greater level of
flexibility when implementing and utilizing a web service client.

Executing commands
------------------

You must explicitly execute a command after creating a command using the ``getCommand()`` method. A command has an
``execute()`` method that may be called, or you can use the ``execute()`` method of a client object and pass in the
command object. Calling either of these execute methods will return the result value of the command. The result value is
the result of parsing the HTTP response with the ``process()`` method.

.. code-block:: php

    // Get a command from the client and pass an array of parameters
    $command = $twitter->getCommand('getMentions', array(
        'count' => 5
    ));

    // Other parameters can be set on the command after it is created
    $command['trim_user'] = false;

    // Execute the command using the command object.
    // The result value contains an array of JSON data from the response
    $result = $command->execute();

    // You can retrieve the result of the command later too
    $result = $command->getResult().

Command object also contains methods that allow you to inspect the HTTP request and response that was utilized with
the command.

.. code-block:: php

    $request = $command->getRequest();
    $response = $command->getResponse();

.. note::

    The format and notation used to retrieve commands from a client can be customized by injecting a custom command
    factory, ``Guzzle\Service\Command\Factory\FactoryInterface``, on the client using ``$client->setCommandFactory()``.

Executing with magic methods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When using method missing magic methods with a command, the command will be executed right away and the result of the
command is returned.

.. code-block:: php

    $jsonData = $twitter->getMentions(array(
        'count'     => 5,
        'trim_user' => true
    ));

Creating commands
-----------------

Commands are created using either the ``getCommand()`` method of a client or a magic missing method of a client. Using
the ``getCommand()`` method allows you to create a command without executing it, allowing for customization of the
command or the request serialized by the command.

When a client attempts to create a command, it uses the client's ``Guzzle\Service\Command\Factory\FactoryInterface``.
By default, Guzzle will utilize a command factory that first looks for a concrete class for a particular command
(concrete commands) followed by a command defined by a service description (operation commands). We'll learn more about
concrete commands and operation commands later in this chapter.

.. code-block:: php

    // Get a command from the twitter client.
    $command = $twitter->getCommand('getMentions');
    $result = $command->execute();

Unless you've skipped ahead, running the above code will throw an exception.

    PHP Fatal error:  Uncaught exception 'Guzzle\Common\Exception\InvalidArgumentException' with message
    'Command was not found matching getMentions'

This exception was thrown because the "getMentions" command has not yet been implemented. Let's implement one now.

Concrete commands
~~~~~~~~~~~~~~~~~

Commands can be created in one of two ways: create a concrete command class that extends
``Guzzle\Service\Command\AbstractCommand`` or
:doc:`create an OperationCommand based on a service description <guzzle-service-descriptions>`. The recommended
approach is to use a service description to define your web service, but you can use concrete commands when custom
logic must be implemented for marshaling or unmarshaling a HTTP message.

Commands are the method in which you abstract away the underlying format of the requests that need to be sent to take
action on a web service. Commands in Guzzle are meant to be built by executing a series of setter methods on a command
object. Commands are only validated right before they are executed. A ``Guzzle\Service\Client`` object is responsible
for executing commands. Commands created for your web service must implement
``Guzzle\Service\Command\CommandInterface``, but it's easier to extend the ``Guzzle\Service\Command\AbstractCommand``
class, implement the ``build()`` method, and optionally implement the ``process()`` method.

Serializing requests
^^^^^^^^^^^^^^^^^^^^

The ``build()`` method of a command is responsible for using the arguments of the command to build and serialize a
HTTP request and set the request on the ``$request`` property of the command object. This step is usually taken care of
for you when using a service description driven command that uses the default
``Guzzle\Service\Command\OperationCommand``. You may wish to implement the process method yourself when you aren't
using a service description or need to implement more complex request serialization.

.. important::::

    When implementing a custom ``build()`` method, be sure to set the class property of ``$this->request`` to an
    instantiated and ready to send request.

The following example shows how to implement the ``getMentions``
`Twitter API <https://dev.twitter.com/docs/api/1.1/get/statuses/mentions_timeline>`_ method using a concrete command.

.. code-block:: php

    namespace mtdowling\Twitter\Command;

    use Guzzle\Service\Command\AbstractCommand;

    class GetMentions extends AbstractCommand
    {
        protected function build()
        {
            // Create the request property of the command
            $this->request = $this->client->get('statuses/mentions_timeline.json');

            // Grab the query object of the request because we will use it for
            // serializing command parameters on the request
            $query = $this->request->getQuery();

            if ($this['count']) {
                $query->set('count', $this['count']);
            }

            if ($this['since_id']) {
                $query->set('since_id', $this['since_id']);
            }

            if ($this['max_id']) {
                $query->set('max_id', $this['max_id']);
            }

            if ($this['trim_user'] !== null) {
                $query->set('trim_user', $this['trim_user'] ? 'true' : 'false');
            }

            if ($this['contributor_details'] !== null) {
                $query->set('contributor_details', $this['contributor_details'] ? 'true' : 'false');
            }

            if ($this['include_entities'] !== null) {
                $query->set('include_entities', $this['include_entities'] ? 'true' : 'false');
            }
        }
    }

By default, a client will attempt to find concrete command classes under the ``Command`` namespace of a client. First
the client will attempt to find an exact match for the name of the command to the name of the command class. If an
exact match is not found, the client will calculate a class name using inflection. This is calculated based on the
folder hierarchy of a command and converting the CamelCased named commands into snake_case. Here are some examples on
how the command names are calculated:

#. ``Foo\Command\JarJar`` **->** jar_jar
#. ``Foo\Command\Test`` **->** test
#. ``Foo\Command\People\GetCurrentPerson`` **->** people.get_current_person

Notice how any sub-namespace beneath ``Command`` is converted from ``\`` to ``.`` (a period). CamelCasing is converted
to lowercased snake_casing (e.g. JarJar == jar_jar).

Parsing responses
^^^^^^^^^^^^^^^^^

The ``process()`` method of a command is responsible for converting an HTTP response into something more useful. For
example, a service description operation that has specified a model object in the ``responseClass`` attribute of the
operation will set a ``Guzzle\Service\Resource\Model`` object as the result of the command. This behavior can be
completely modified as needed-- even if you are using operations and responseClass models. Simply implement a custom
``process()`` method that sets the ``$this->result`` class property to whatever you choose. You can reuse parts of the
default Guzzle response parsing functionality or get inspiration from existing code by using
``Guzzle\Service\Command\OperationResponseParser`` and ``Guzzle\Service\Command\DefaultResponseParser`` classes.

If you do not implement a custom ``process()`` method and are not using a service description, then Guzzle will attempt
to guess how a response should be processed based on the Content-Type header of the response. Because the Twitter API
sets a ``Content-Type: application/json`` header on this response, we do not need to implement any custom response
parsing.

Operation commands
~~~~~~~~~~~~~~~~~~

Operation commands are commands in which the serialization of an HTTP request and the parsing of an HTTP response are
driven by a Guzzle service description. Because request serialization, validation, and response parsing are
described using a DSL, creating operation commands is a much faster process than writing concrete commands.

Creating operation commands for our Twitter client can remove a great deal of redundancy from the previous concrete
command, and allows for a deeper runtime introspection of the API. Here's an example service description we can use to
create the Twitter API client:

.. code-block:: json

    {
        "name": "Twitter",
        "apiVersion": "1.1",
        "baseUrl": "https://api.twitter.com/1.1",
        "description": "Twitter REST API client",
        "operations": {
            "GetMentions": {
                "httpMethod": "GET",
                "uri": "statuses/mentions_timeline.json",
                "summary": "Returns the 20 most recent mentions for the authenticating user.",
                "responseClass": "GetMentionsOutput",
                "parameters": {
                    "count": {
                        "description": "Specifies the number of tweets to try and retrieve",
                        "type": "integer",
                        "location": "query"
                    },
                    "since_id": {
                        "description": "Returns results with an ID greater than the specified ID",
                        "type": "integer",
                        "location": "query"
                    },
                    "max_id": {
                        "description": "Returns results with an ID less than or equal to the specified ID.",
                        "type": "integer",
                        "location": "query"
                    },
                    "trim_user": {
                        "description": "Limits the amount of data returned for each user",
                        "type": "boolean",
                        "location": "query"
                    },
                    "contributor_details": {
                        "description": "Adds more data to contributor elements",
                        "type": "boolean",
                        "location": "query"
                    },
                    "include_entities": {
                        "description": "The entities node will be disincluded when set to false.",
                        "type": "boolean",
                        "location": "query"
                    }
                }
            }
        },
        "models": {
            "GetMentionsOutput": {
                "type": "object",
                "additionalProperties": {
                    "location": "json"
                }
            }
        }
    }

If you're lazy, you can define the API in a less descriptive manner using ``additionalParameters``.
``additionalParameters`` define the serialization and validation rules of parameters that are not explicitly defined
in a service description.

.. code-block:: json

    {
        "name": "Twitter",
        "apiVersion": "1.1",
        "baseUrl": "https://api.twitter.com/1.1",
        "description": "Twitter REST API client",
        "operations": {
            "GetMentions": {
                "httpMethod": "GET",
                "uri": "statuses/mentions_timeline.json",
                "summary": "Returns the 20 most recent mentions for the authenticating user.",
                "responseClass": "GetMentionsOutput",
                "additionalParameters": {
                    "location": "query"
                }
            }
        },
        "models": {
            "GetMentionsOutput": {
                "type": "object",
                "additionalProperties": {
                    "location": "json"
                }
            }
        }
    }

You should attach the service description to the client at the end of the client's factory method:

.. code-block:: php

    // ...
    class TwitterClient extends Client
    {
        public static function factory($config = array())
        {
            // ... same code as before ...

            // Set the service description
            $client->setDescription(ServiceDescription::factory('path/to/twitter.json'));

            return $client;
        }
    }

The client can now use operations defined in the service description instead of requiring you to create concrete
command classes. Feel free to delete the concrete command class we created earlier.

.. code-block:: php

    $jsonData = $twitter->getMentions(array(
        'count'     => 5,
        'trim_user' => true
    ));

Executing commands in parallel
------------------------------

Much like HTTP requests, Guzzle allows you to send multiple commands in parallel. You can send commands in parallel by
passing an array of command objects to a client's ``execute()`` method. The client will serialize each request and
send them all in parallel. If an error is encountered during the transfer, then a
``Guzzle\Service\Exception\CommandTransferException`` is thrown, which allows you to retrieve a list of commands that
succeeded and a list of commands that failed.

.. code-block:: php

    use Guzzle\Service\Exception\CommandTransferException;

    $commands = array();
    $commands[] = $twitter->getCommand('getMentions');
    $commands[] = $twitter->getCommand('otherCommandName');
    // etc...

    try {
        $result = $client->execute($commands);
        foreach ($result as $command) {
            echo $command->getName() . ': ' . $command->getResponse()->getStatusCode() . "\n";
        }
    } catch (CommandTransferException $e) {
        // Get an array of the commands that succeeded
        foreach ($e->getSuccessfulCommands() as $command) {
            echo $command->getName() . " succeeded\n";
        }
        // Get an array of the commands that failed
        foreach ($e->getFailedCommands() as $command) {
            echo $command->getName() . " failed\n";
        }
    }

.. note::

    All commands executed from a client using an array must originate from the same client.

Special command options
-----------------------

Guzzle exposes several options that help to control how commands are validated, serialized, and parsed.
Command options can be specified when creating a command or in the ``command.params`` parameter in the
``Guzzle\Service\Client``.

=========================== ============================================================================================
command.request_options     Option used to add :ref:`Request options <request-options>` to the request created by a
                            command
command.hidden_params       An array of the names of parameters ignored by the ``additionalParameters`` parameter schema
command.disable_validation  Set to true to disable JSON schema validation of the command's input parameters
command.response_processing Determines how the default response parser will parse the command. One of "raw" no parsing,
                            "model" (the default method used to parse commands using response models defined in service
                            descriptions)
command.headers             (deprecated) Option used to specify custom headers.  Use ``command.request_options`` instead
command.on_complete         (deprecated) Option used to add an onComplete method to a command.  Use
                            ``command.after_send`` event instead
command.response_body       (deprecated) Option used to change the entity body used to store a response.
                            Use ``command.request_options`` instead
=========================== ============================================================================================

Advanced client configuration
=============================

Default command parameters
--------------------------

When creating a client object, you can specify default command parameters to pass into all commands. Any key value pair
present in the ``command.params`` settings of a client will be added as default parameters to any command created
by the client.

.. code-block:: php

    $client = new Guzzle\Service\Client(array(
        'command.params' => array(
            'default_1' => 'foo',
            'another'   => 'bar'
        )
    ));

Magic methods
-------------

Client objects will, by default, attempt to create and execute commands when a missing method is invoked on a client.
This powerful concept applies to both concrete commands and operation commands powered by a service description. This
makes it appear to the end user that you have defined actual methods on a client object, when in fact, the methods are
invoked using PHP's magic ``__call`` method.

The ``__call`` method uses the ``getCommand()`` method of a client, which uses the client's internal
``Guzzle\Service\Command\Factory\FactoryInterface`` object. The default command factory allows you to instantiate
operations defined in a client's service description. The method in which a client determines which command to
execute is defined as follows:

1. The client will first try to find a literal match for an operation in the service description.
2. If the literal match is not found, the client will try to uppercase the first character of the operation and find
   the match again.
3. If a match is still not found, the command factory will inflect the method name from CamelCase to snake_case and
   attempt to find a matching command.
4. If a command still does not match, an exception is thrown.

.. code-block:: php

    // Use the magic method
    $result = $twitter->getMentions();

    // This is exactly the same as:
    $result = $twitter->getCommand('getMentions')->execute();

You can disable magic methods on a client by passing ``false`` to the ``enableMagicMethod()`` method.

Custom command factory
----------------------

A client by default uses the ``Guzzle\Service\Command\Factory\CompositeFactory`` which allows multiple command
factories to attempt to create a command by a certain name. The default CompositeFactory uses a ``ConcreteClassFactory``
and a ``ServiceDescriptionFactory`` if a service description is specified on a client. You can specify a custom
command factory if your client requires custom command creation logic using the ``setCommandFactory()`` method of
a client.

Custom resource Iterator factory
--------------------------------

Resource iterators can be retrieved from a client using the ``getIterator($name)`` method of a client. This method uses
a client's internal ``Guzzle\Service\Resource\ResourceIteratorFactoryInterface`` object. A client by default uses a
``Guzzle\Service\Resource\ResourceIteratorClassFactory`` to attempt to find concrete classes that implement resource
iterators. The default factory will first look for matching iterators in the ``Iterator`` subdirectory of the client
followed by the ``Model`` subdirectory of a client. Use the ``setResourceIteratorFactory()`` method of a client to
specify a custom resource iterator factory.

Plugins and events
==================

``Guzzle\Service\Client`` exposes various events that allow you to hook in custom logic. A client object owns a
``Symfony\Component\EventDispatcher\EventDispatcher`` object that can be accessed by calling
``$client->getEventDispatcher()``. You can use the event dispatcher to add listeners (a simple callback function) or
event subscribers (classes that listen to specific events of a dispatcher).

.. _service-client-events:

Events emitted from a Service Client
------------------------------------

A ``Guzzle\Service\Client`` object emits the following events:

+------------------------------+--------------------------------------------+------------------------------------------+
| Event name                   | Description                                | Event data                               |
+==============================+============================================+==========================================+
| client.command.create        | The client created a command object        | * client: Client object                  |
|                              |                                            | * command: Command object                |
+------------------------------+--------------------------------------------+------------------------------------------+
| command.before_prepare       | Before a command is validated and built.   | * command: Command being prepared        |
|                              | This is also before a request is created.  |                                          |
+------------------------------+--------------------------------------------+------------------------------------------+
| command.after_prepare        | After a command instantiates and           | * command: Command that was prepared     |
|                              | configures its request object.             |                                          |
+------------------------------+--------------------------------------------+------------------------------------------+
| command.before_send          | The client is about to execute a prepared  | * command: Command to execute            |
|                              | command                                    |                                          |
+------------------------------+--------------------------------------------+------------------------------------------+
| command.after_send           | The client successfully completed          | * command: The command that was executed |
|                              | executing a command                        |                                          |
+------------------------------+--------------------------------------------+------------------------------------------+
| command.parse_response       | Called when ``responseType`` is ``class``  | * command: The command with a response   |
|                              | and the response is about to be parsed.    |   about to be parsed.                    |
+------------------------------+--------------------------------------------+------------------------------------------+

.. code-block:: php

    use Guzzle\Common\Event;
    use Guzzle\Service\Client;

    $client = new Client();

    // create an event listener that operates on request objects
    $client->getEventDispatcher()->addListener('command.after_prepare', function (Event $event) {
        $command = $event['command'];
        $request = $command->getRequest();

        // do something with request
    });

.. code-block:: php

    use Guzzle\Common\Event;
    use Guzzle\Common\Client;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    class EventSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return array(
                'client.command.create' => 'onCommandCreate',
                'command.parse_response' => 'onParseResponse'
            );
        }

        public function onCommandCreate(Event $event)
        {
            $client = $event['client'];
            $command = $event['command'];
            // operate on client and command
        }

        public function onParseResponse(Event $event)
        {
            $command = $event['command'];
            // operate on the command
        }
    }

    $client = new Client();

    $client->addSubscriber(new EventSubscriber());
.. title:: Guzzle | PHP HTTP client and framework for consuming RESTful web services
.. toctree::
    :hidden:

    docs.rst
{
    "additionalProperties": true,
    "name": {
        "type": "string",
        "description": "Name of the web service"
    },
    "apiVersion": {
        "type": ["string", "number"],
        "description": "Version identifier that the service description is compatible with"
    },
    "baseUrl": {
        "type": "string",
        "description": "Base URL of the web service. Any relative URI specified in an operation will be merged with the baseUrl using the process defined in RFC 2396"
    },
    "basePath": {
        "type": "string",
        "description": "Alias of baseUrl"
    },
    "_description": {
        "type": "string",
        "description": "Short summary of the web service. This is actually called 'description' but this JSON schema wont validate using just description."
    },
    "operations": {
        "description": "Operations of the web service",
        "type": "object",
        "properties": {
            "extends": {
                "type": "string",
                "description": "Extend from another operation by name. The parent operation must be defined before the child."
            },
            "httpMethod": {
                "type": "string",
                "description": "HTTP method used with the operation (e.g. GET, POST, PUT, DELETE, PATCH, etc)"
            },
            "uri": {
                "type": "string",
                "description": "URI of the operation. The uri attribute can contain URI templates. The variables of the URI template are parameters of the operation with a location value of uri"
            },
            "summary": {
                "type": "string",
                "description": "Short summary of what the operation does"
            },
            "class": {
                "type": "string",
                "description": "Custom class to instantiate instead of the default Guzzle\\Service\\Command\\OperationCommand"
            },
            "responseClass": {
                "type": "string",
                "description": "This is what is returned from the method. Can be a primitive, class name, or model name."
            },
            "responseNotes": {
                "type": "string",
                "description": "A description of the response returned by the operation"
            },
            "responseType": {
                "type": "string",
                "description": "The type of response that the operation creates. If not specified, this value will be automatically inferred based on whether or not there is a model matching the name, if a matching class name is found, or set to 'primitive' by default.",
                "enum": [ "primitive", "class", "model", "documentation" ]
            },
            "deprecated": {
                "type": "boolean",
                "description": "Whether or not the operation is deprecated"
            },
            "errorResponses": {
                "description": "Errors that could occur while executing the operation",
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "code": {
                            "type": "number",
                            "description": "HTTP response status code of the error"
                        },
                        "reason": {
                            "type": "string",
                            "description": "Response reason phrase or description of the error"
                        },
                        "class": {
                            "type": "string",
                            "description": "A custom exception class that would be thrown if the error is encountered"
                        }
                    }
                }
            },
            "data": {
                "type": "object",
                "additionalProperties": "true"
            },
            "parameters": {
                "$ref": "parameters",
                "description": "Parameters of the operation. Parameters are used to define how input data is serialized into a HTTP request."
            },
            "additionalParameters": {
              "$ref": "parameters",
              "description": "Validation and serialization rules for any parameter supplied to the operation that was not explicitly defined."
            }
        }
    },
    "models": {
        "description": "Schema models that can be referenced throughout the service description. Models can be used to define how an HTTP response is parsed into a Guzzle\\Service\\Resource\\Model object.",
        "type": "object",
        "properties": {
            "$ref": "parameters",
            "description": "Parameters of the model. When a model is referenced in a responseClass attribute of an operation, parameters define how a HTTP response message is parsed into a Guzzle\\Service\\Resource\\Model."
        }
    },
    "includes": {
        "description": "Service description files to include and extend from (can be a .json, .js, or .php file)",
        "type": "array",
        "items": {
            "type": "string",
            "pattern": ".+\\.(js|json|php)$"
        }
    },
    "definitions": {
        "parameters": {
            "extends": "http://json-schema.org/schema",
            "id": "parameters",
            "name": {
                "type": "string",
                "description": "Unique name of the parameter"
            },
            "type": {
                "type": ["string", "array"],
                "description": "Type of variable (string, number, integer, boolean, object, array, numeric, null, any). Types are using for validation and determining the structure of a parameter. You can use a union type by providing an array of simple types. If one of the union types matches the provided value, then the value is valid."
            },
            "instanceOf": {
                "type": "string",
                "description": "When the type is an object, you can specify the class that the object must implement"
            },
            "required": {
                "type": "boolean",
                "description": "Whether or not the parameter is required"
            },
            "default": {
                "description": "Default value to use if no value is supplied"
            },
            "static": {
                "type": "bool",
                "description": "Set to true to specify that the parameter value cannot be changed from the default setting"
            },
            "description": {
                "type": "string",
                "description": "Documentation of the parameter"
            },
            "location": {
                "type": "string",
                "description": "The location of a request used to apply a parameter. Custom locations can be registered with a command, but the defaults are uri, query, statusCode, reasonPhrase, header, body, json, xml, postField, postFile, responseBody"
            },
            "sentAs": {
                "type": "string",
                "description": "Specifies how the data being modeled is sent over the wire. For example, you may wish to include certain headers in a response model that have a normalized casing of FooBar, but the actual header is x-foo-bar. In this case, sentAs would be set to x-foo-bar."
            },
            "filters": {
                "type": "array",
                "description": "Array of static method names to to run a parameter value through. Each value in the array must be a string containing the full class path to a static method or an array of complex filter information. You can specify static methods of classes using the full namespace class name followed by ‘::’ (e.g. FooBar::baz()). Some filters require arguments in order to properly filter a value. For complex filters, use a hash containing a ‘method’ key pointing to a static method, and an ‘args’ key containing an array of positional arguments to pass to the method. Arguments can contain keywords that are replaced when filtering a value: '@value‘ is replaced with the value being validated, '@api‘ is replaced with the Parameter object.",
                "items": {
                    "type": ["string", {
                        "object": {
                            "properties": {
                                "method": {
                                    "type": "string",
                                    "description": "PHP function to call",
                                    "required": true
                                },
                                "args": {
                                    "type": "array"
                                }
                            }
                        }
                    }]
                }
            }
        }
    }
}
Sphinx>=1.2b1
guzzle_sphinx_theme>=0.5.0
==========================
cURL authentication plugin
==========================

.. warning::

    The CurlAuthPlugin is deprecated. You should use the `auth` parameter of a client to add authorization headers to
    every request created by a client.

    .. code-block:: php

        $client->setDefaultOption('auth', array('username', 'password', 'Basic|Digest|NTLM|Any'));

If your web service client requires basic authorization, then you can use the CurlAuthPlugin to easily add an
Authorization header to each request sent by the client.

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\CurlAuth\CurlAuthPlugin;

    $client = new Client('http://www.test.com/');

    // Add the auth plugin to the client object
    $authPlugin = new CurlAuthPlugin('username', 'password');
    $client->addSubscriber($authPlugin);

    $response = $client->get('projects/1/people')->send();
    $xml = new SimpleXMLElement($response->getBody(true));
    foreach ($xml->person as $person) {
        echo $person->email . "\n";
    }
======================
Plugin system overview
======================

The workflow of sending a request and parsing a response is driven by Guzzle's event system, which is powered by the
`Symfony2 Event Dispatcher component <http://symfony.com/doc/current/components/event_dispatcher/introduction.html>`_.

Any object in Guzzle that emits events will implement the ``Guzzle\Common\HasEventDispatcher`` interface. You can add
event subscribers directly to these objects using the ``addSubscriber()`` method, or you can grab the
``Symfony\Component\EventDispatcher\EventDispatcher`` object owned by the object using ``getEventDispatcher()`` and
add a listener or event subscriber.

Adding event subscribers to clients
-----------------------------------

Any event subscriber or event listener attached to the EventDispatcher of a ``Guzzle\Http\Client`` or
``Guzzle\Service\Client`` object will automatically be attached to all request objects created by the client. This
allows you to attach, for example, a HistoryPlugin to a client object, and from that point on, every request sent
through that client will utilize the HistoryPlugin.

.. code-block:: php

    use Guzzle\Plugin\History\HistoryPlugin;
    use Guzzle\Service\Client;

    $client = new Client();

    // Create a history plugin and attach it to the client
    $history = new HistoryPlugin();
    $client->addSubscriber($history);

    // Create and send a request. This request will also utilize the HistoryPlugin
    $client->get('http://httpbin.org')->send();

    // Echo out the last sent request by the client
    echo $history->getLastRequest();

.. tip::

    :doc:`Create event subscribers <creating-plugins>`, or *plugins*, to implement reusable logic that can be
    shared across clients. Event subscribers are also easier to test than anonymous functions.

Pre-Built plugins
-----------------

Guzzle provides easy to use request plugins that add behavior to requests based on signal slot event notifications
powered by the Symfony2 Event Dispatcher component.

* :doc:`async-plugin`
* :doc:`backoff-plugin`
* :doc:`cache-plugin`
* :doc:`cookie-plugin`
* :doc:`curl-auth-plugin`
* :doc:`history-plugin`
* :doc:`log-plugin`
* :doc:`md5-validator-plugin`
* :doc:`mock-plugin`
* :doc:`oauth-plugin`

============
OAuth plugin
============

Guzzle ships with an OAuth 1.0 plugin that can sign requests using a consumer key, consumer secret, OAuth token,
and OAuth secret. Here's an example showing how to send an authenticated request to the Twitter REST API:

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Oauth\OauthPlugin;

    $client = new Client('http://api.twitter.com/1');
    $oauth = new OauthPlugin(array(
        'consumer_key'    => 'my_key',
        'consumer_secret' => 'my_secret',
        'token'           => 'my_token',
        'token_secret'    => 'my_token_secret'
    ));
    $client->addSubscriber($oauth);

    $response = $client->get('statuses/public_timeline.json')->send();

If you need to use a custom signing method, you can pass a ``signature_method`` configuration option in the
constructor of the OAuth plugin. The ``signature_method`` option must be a callable variable that accepts a string to
sign and signing key and returns a signed string.

.. note::

    You can omit the ``token`` and ``token_secret`` options to use two-legged OAuth.
==============
History plugin
==============

The history plugin tracks all of the requests and responses sent through a request or client. This plugin can be
useful for crawling or unit testing. By default, the history plugin stores up to 10 requests and responses.

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\History\HistoryPlugin;

    $client = new Client('http://www.test.com/');

    // Add the history plugin to the client object
    $history = new HistoryPlugin();
    $history->setLimit(5);
    $client->addSubscriber($history);

    $client->get('http://www.yahoo.com/')->send();

    echo $history->getLastRequest();
    echo $history->getLastResponse();
    echo count($history);
====================
MD5 validator plugin
====================

Entity bodies can sometimes be modified over the wire due to a faulty TCP transport or misbehaving proxy. If an HTTP
response contains a Content-MD5 header, then a MD5 hash of the entity body of a response can be compared against the
Content-MD5 header of the response to determine if the response was delivered intact. The
``Guzzle\Plugin\Md5\Md5ValidatorPlugin`` will throw an ``UnexpectedValueException`` if the calculated MD5 hash does
not match the Content-MD5 header value:

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Md5\Md5ValidatorPlugin;

    $client = new Client('http://www.test.com/');

    $md5Plugin = new Md5ValidatorPlugin();

    // Add the md5 plugin to the client object
    $client->addSubscriber($md5Plugin);

    $request = $client->get('http://www.yahoo.com/');
    $request->send();

Calculating the MD5 hash of a large entity body or an entity body that was transferred using a Content-Encoding is an
expensive operation. When working in high performance applications, you might consider skipping the MD5 hash
validation for entity bodies bigger than a certain size or Content-Encoded entity bodies
(see ``Guzzle\Plugin\Md5\Md5ValidatorPlugin`` for more information).
=============
Cookie plugin
=============

Some web services require a Cookie in order to maintain a session. The ``Guzzle\Plugin\Cookie\CookiePlugin`` will add
cookies to requests and parse cookies from responses using a CookieJar object:

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Cookie\CookiePlugin;
    use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

    $cookiePlugin = new CookiePlugin(new ArrayCookieJar());

    // Add the cookie plugin to a client
    $client = new Client('http://www.test.com/');
    $client->addSubscriber($cookiePlugin);

    // Send the request with no cookies and parse the returned cookies
    $client->get('http://www.yahoo.com/')->send();

    // Send the request again, noticing that cookies are being sent
    $request = $client->get('http://www.yahoo.com/');
    $request->send();

    echo $request;

You can disable cookies per-request by setting the ``cookies.disable`` value to true on a request's params object.

.. code-block:: php

    $request->getParams()->set('cookies.disable', true);
* :doc:`/plugins/async-plugin`
* :doc:`/plugins/backoff-plugin`
* :doc:`/plugins/cache-plugin`
* :doc:`/plugins/cookie-plugin`
* :doc:`/plugins/history-plugin`
* :doc:`/plugins/log-plugin`
* :doc:`/plugins/md5-validator-plugin`
* :doc:`/plugins/mock-plugin`
* :doc:`/plugins/oauth-plugin`
===========
Mock plugin
===========

The mock plugin is useful for testing Guzzle clients. The mock plugin allows you to queue an array of responses that
will satisfy requests sent from a client by consuming the request queue in FIFO order.

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Mock\MockPlugin;
    use Guzzle\Http\Message\Response;

    $client = new Client('http://www.test.com/');

    $mock = new MockPlugin();
    $mock->addResponse(new Response(200))
         ->addResponse(new Response(404));

    // Add the mock plugin to the client object
    $client->addSubscriber($mock);

    // The following request will receive a 200 response from the plugin
    $client->get('http://www.example.com/')->send();

    // The following request will receive a 404 response from the plugin
    $client->get('http://www.test.com/')->send();
============
Async plugin
============

The AsyncPlugin allows you to send requests that do not wait on a response. This is handled through cURL by utilizing
the progress event. When a request has sent all of its data to the remote server, Guzzle adds a 1ms timeout on the
request and instructs cURL to not download the body of the response. The async plugin then catches the exception and
adds a mock response to the request, along with an X-Guzzle-Async header to let you know that the response was not
fully downloaded.

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Async\AsyncPlugin;

    $client = new Client('http://www.example.com');
    $client->addSubscriber(new AsyncPlugin());
    $response = $client->get()->send();
================
Creating plugins
================

.. highlight:: php

Guzzle is extremely extensible because of the behavioral modifications that can be added to requests, clients, and
commands using an event system. Before and after the majority of actions are taken in the library, an event is emitted
with the name of the event and context surrounding the event. Observers can subscribe to a subject and modify the
subject based on the events received. Guzzle's event system utilizes the Symfony2 EventDispatcher and is the backbone
of its plugin architecture.

Overview
--------

Plugins must implement the ``Symfony\Component\EventDispatcher\EventSubscriberInterface`` interface. The
``EventSubscriberInterface`` requires that your class implements a static method, ``getSubscribedEvents()``, that
returns an associative array mapping events to methods on the object. See the
`Symfony2 documentation <http://symfony.com/doc/2.0/book/internals.html#the-event-dispatcher>`_ for more information.

Plugins can be attached to any subject, or object in Guzzle that implements that
``Guzzle\Common\HasDispatcherInterface``.

Subscribing to a subject
~~~~~~~~~~~~~~~~~~~~~~~~

You can subscribe an instantiated observer to an event by calling ``addSubscriber`` on a subject.

.. code-block:: php

    $testPlugin = new TestPlugin();
    $client->addSubscriber($testPlugin);

You can also subscribe to only specific events using a closure::

    $client->getEventDispatcher()->addListener('request.create', function(Event $event) {
        echo $event->getName();
        echo $event['request'];
    });

``Guzzle\Common\Event`` objects are passed to notified functions. The Event object has a ``getName()`` method which
return the name of the emitted event and may contain contextual information that can be accessed like an array.

Knowing what events to listen to
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Any class that implements the ``Guzzle\Common\HasDispatcherInterface`` must implement a static method,
``getAllEvents()``, that returns an array of the events that are emitted from the object.  You can browse the source
to see each event, or you can call the static method directly in your code to get a list of available events.

Event hooks
-----------

* :ref:`client-events`
* :ref:`service-client-events`
* :ref:`request-events`
* ``Guzzle\Http\Curl\CurlMulti``:
* :ref:`service-builder-events`

Examples of the event system
----------------------------

Simple Echo plugin
~~~~~~~~~~~~~~~~~~

This simple plugin prints a string containing the request that is about to be sent by listening to the
``request.before_send`` event::

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    class EchoPlugin implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return array('request.before_send' => 'onBeforeSend');
        }

        public function onBeforeSend(Guzzle\Common\Event $event)
        {
            echo 'About to send a request: ' . $event['request'] . "\n";
        }
    }

    $client = new Guzzle\Service\Client('http://www.test.com/');

    // Create the plugin and add it as an event subscriber
    $plugin = new EchoPlugin();
    $client->addSubscriber($plugin);

    // Send a request and notice that the request is printed to the screen
    $client->get('/')->send();

Running the above code will print a string containing the HTTP request that is about to be sent.
=================
HTTP Cache plugin
=================

Guzzle can leverage HTTP's caching specifications using the ``Guzzle\Plugin\Cache\CachePlugin``. The CachePlugin
provides a private transparent proxy cache that caches HTTP responses. The caching logic, based on
`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html>`_, uses HTTP headers to control caching behavior,
cache lifetime, and supports Vary, ETag, and Last-Modified based revalidation:

.. code-block:: php

    use Guzzle\Http\Client;
    use Doctrine\Common\Cache\FilesystemCache;
    use Guzzle\Cache\DoctrineCacheAdapter;
    use Guzzle\Plugin\Cache\CachePlugin;
    use Guzzle\Plugin\Cache\DefaultCacheStorage;

    $client = new Client('http://www.test.com/');

    $cachePlugin = new CachePlugin(array(
        'storage' => new DefaultCacheStorage(
            new DoctrineCacheAdapter(
                new FilesystemCache('/path/to/cache/files')
            )
        )
    ));

    // Add the cache plugin to the client object
    $client->addSubscriber($cachePlugin);
    $client->get('http://www.wikipedia.org/')->send();

    // The next request will revalidate against the origin server to see if it
    // has been modified. If a 304 response is received the response will be
    // served from cache
    $client->get('http://www.wikipedia.org/')->send();

The cache plugin intercepts GET and HEAD requests before they are actually transferred to the origin server. The cache
plugin then generates a hash key based on the request method and URL, and checks to see if a response exists in the cache. If
a response exists in the cache, the cache adapter then checks to make sure that the caching rules associated with the response
satisfy the request, and ensures that response still fresh. If the response is acceptable for the request any required
revalidation, then the cached response is served instead of contacting the origin server.

Vary
----

Cache keys are derived from a request method and a request URL. Multiple responses can map to the same cache key and
stored in Guzzle's underlying cache storage object. You should use the ``Vary`` HTTP header to tell the cache storage
object that the cache response must have been cached for a request that matches the headers specified in the Vary header
of the request. This allows you to have specific cache entries for the same request URL but variations in a request's
headers determine which cache entry is served. Please see the http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
for more information.

Cache options
-------------

There are several options you can add to requests or clients to modify the behavior of the cache plugin.

Override cache TTL
~~~~~~~~~~~~~~~~~~

You can override the number of seconds a cacheable response is stored in the cache by setting the
``cache.override_ttl`` parameter on the params object of a request:

.. code-block:: php

    // If the response to the request is cacheable, then the response will be cached for 100 seconds
    $request->getParams()->set('cache.override_ttl', 100);

If a response doesn't specify any freshness policy, it will be kept in cache for 3600 seconds by default.

Custom caching decision
~~~~~~~~~~~~~~~~~~~~~~~

If the service you are interacting with does not return caching headers or returns responses that are normally
something that would not be cached, you can set a custom ``can_cache`` object on the constructor of the CachePlugin
and provide a ``Guzzle\Plugin\Cache\CanCacheInterface`` object. You can use the
``Guzzle\Plugin\Cache\CallbackCanCacheStrategy`` to easily make a caching decision based on an HTTP request and
response.

Revalidation options
~~~~~~~~~~~~~~~~~~~~

You can change the revalidation behavior of a request using the ``cache.revalidate`` parameter. Setting this
parameter to ``never`` will ensure that a revalidation request is never sent, and the response is always served from
the origin server. Setting this parameter to ``skip`` will never revalidate and uses the response stored in the cache.

Normalizing requests for caching
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use the ``cache.key_filter`` parameter if you wish to strip certain query string parameters from your
request before creating a unique hash for the request. This parameter can be useful if your requests have query
string values that cause each request URL to be unique (thus preventing a cache hit). The ``cache.key_filter``
format is simply a comma separated list of query string values to remove from the URL when creating a cache key.
For example, here we are saying that the ``a`` and ``q`` query string variables should be ignored when generating a
cache key for the request:

.. code-block:: php

    $request->getParams()->set('cache.key_filter', 'a, q');

Other options
~~~~~~~~~~~~~

There are many other options available to the CachePlugin that can meet almost any caching requirement, including
custom revalidation implementations, custom cache key generators, custom caching decision strategies, and custom
cache storage objects. Take a look the constructor of ``Guzzle\Plugin\Cache\CachePlugin`` for more information.

Setting Client-wide cache settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can specify cache settings for every request created by a client by adding cache settings to the configuration
options of a client.

.. code-block:: php

    $client = new Guzzle\Http\Client('http://www.test.com', array(
        'request.params' => array(
            'cache.override_ttl' => 3600,
            'params.cache.revalidate' => 'never'
        )
    ));

    echo $client->get('/')->getParams()->get('cache.override_ttl');
    // >>> 3600

    echo $client->get('/')->getParams()->get('cache.revalidate');
    // >>> never

Cache revalidation
------------------

If the cache plugin determines that a response to a GET request needs revalidation, a conditional GET is transferred
to the origin server. If the origin server returns a 304 response, then a response containing the merged headers of
the cached response with the new response and the entity body of the cached response is returned. Custom revalidation
strategies can be injected into a CachePlugin if needed.

Cache adapters
--------------

Guzzle doesn't try to reinvent the wheel when it comes to caching or logging. Plenty of other frameworks have
excellent solutions in place that you are probably already using in your applications. Guzzle uses adapters for
caching and logging. The cache plugin requires a cache adapter so that is can store responses in a cache. Guzzle
currently supports cache adapters for `Doctrine 2.0 <http://www.doctrine-project.org/>`_ and the
`Zend Framework <http://framework.zend.com>`_.

Doctrine cache adapter
~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: php

    use Doctrine\Common\Cache\ArrayCache;
    use Guzzle\Cache\DoctrineCacheAdapter;
    use Guzzle\Plugin\Cache\CachePlugin;

    $backend = new ArrayCache();
    $adapter = new DoctrineCacheAdapter($backend);
    $cache = new CachePlugin($adapter);

Zend Framework cache adapter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: php

    use Guzzle\Cache\ZendCacheAdapter;
    use Zend\Cache\Backend\TestBackend;

    $backend = new TestBackend();
    $adapter = new ZendCacheAdapter($backend);
    $cache = new CachePlugin($adapter);
====================
Backoff retry plugin
====================

The ``Guzzle\Plugin\Backoff\BackoffPlugin`` automatically retries failed HTTP requests using custom backoff strategies:

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Plugin\Backoff\BackoffPlugin;

    $client = new Client('http://www.test.com/');
    // Use a static factory method to get a backoff plugin using the exponential backoff strategy
    $backoffPlugin = BackoffPlugin::getExponentialBackoff();

    // Add the backoff plugin to the client object
    $client->addSubscriber($backoffPlugin);

The BackoffPlugin's constructor accepts a ``Guzzle\Plugin\Backoff\BackoffStrategyInterface`` object that is used to
determine when a retry should be issued and how long to delay between retries. The above code example shows how to
attach a BackoffPlugin to a client that is pre-configured to retry failed 500 and 503 responses using truncated
exponential backoff (emulating the behavior of Guzzle 2's ExponentialBackoffPlugin).
==========
Log plugin
==========

Use the ``Guzzle\Plugin\Log\LogPlugin`` to view all data sent over the wire, including entity bodies and redirects.

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Log\Zf1LogAdapter;
    use Guzzle\Plugin\Log\LogPlugin;
    use Guzzle\Log\MessageFormatter;

    $client = new Client('http://www.test.com/');

    $adapter = new Zf1LogAdapter(
        new \Zend_Log(new \Zend_Log_Writer_Stream('php://output'))
    );
    $logPlugin = new LogPlugin($adapter, MessageFormatter::DEBUG_FORMAT);

    // Attach the plugin to the client, which will in turn be attached to all
    // requests generated by the client
    $client->addSubscriber($logPlugin);

    $response = $client->get('http://google.com')->send();

The code sample above wraps a ``Zend_Log`` object using a ``Guzzle\Log\Zf1LogAdapter``. After attaching the plugin to
the client, all data sent over the wire will be logged to stdout.

The first argument of the LogPlugin's constructor accepts a ``Guzzle\Log\LogAdapterInterface`` object. This object is
an adapter that allows you to use the logging capabilities of your favorite log implementation. The second argument of
the constructor accepts a ``Guzzle\Log\MessageFormatter`` or a log messaged format string. The format string uses
variable substitution and allows you to define the log data that is important to your application. The different
variables that can be injected are as follows:

================== ====================================================================================
Variable           Substitution
================== ====================================================================================
{request}          Full HTTP request message
{response}         Full HTTP response message
{ts}               Timestamp
{host}             Host of the request
{method}           Method of the request
{url}              URL of the request
{host}             Host of the request
{protocol}         Request protocol
{version}          Protocol version
{resource}         Resource of the request (path + query + fragment)
{port}             Port of the request
{hostname}         Hostname of the machine that sent the request
{code}             Status code of the response (if available)
{phrase}           Reason phrase of the response  (if available)
{curl_error}       Curl error message (if available)
{curl_code}        Curl error code (if available)
{curl_stderr}      Curl standard error (if available)
{connect_time}     Time in seconds it took to establish the connection (if available)
{total_time}       Total transaction time in seconds for last transfer (if available)
{req_header_*}     Replace `*` with the lowercased name of a request header to add to the message
{res_header_*}     Replace `*` with the lowercased name of a response header to add to the message
{req_body}         Request body
{res_body}         Response body
================== ====================================================================================

The LogPlugin has a helper method that can be used when debugging that will output the full HTTP request and
response of a transaction:

.. code-block:: php

    $client->addSubscriber(LogPlugin::getDebugPlugin());
<script type="text/javascript" src="{{ pathto('_static/prettify.js', 1) }}"></script>
<link rel="stylesheet" type="text/css" href="{{ pathto('_static/prettify.css', 1) }}" />
<link rel="stylesheet" type="text/css" href="{{ pathto('_static/homepage.css', 1) }}" />

<div class="jumbotron masthead">
  <div class="container">
    <img src="{{ pathto('_static/logo.png', 1) }}" alt="guzzle" width="199" height="260" />
    <h1>Guzzle</h1>
    <p>Guzzle is a PHP HTTP client<br />&amp; framework for building RESTful web service clients.</p>
    <p>
      <a class="btn btn-primary btn-lg" href="https://github.com/guzzle/guzzle">View Guzzle on GitHub</a>
      <a class="btn btn-default btn-lg" href="{{ pathto('docs') }}">Read the docs</a>
    </p>
    </div>
</div>

<div class="social">
  <ul class="social-buttons">
    <li>
      <iframe src="http://ghbtns.com/github-btn.html?user=guzzle&repo=guzzle&type=watch&count=true"
          allowtransparency="true" frameborder="0" scrolling="0" width="110" height="20"></iframe>
    </li>
    <li>
      <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://guzzlephp.org" data-text="Guzzle, PHP HTTP client &amp; framework for building RESTful web service clients" data-via="mtdowling">Tweet</a>
      <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
    </li>
    <li>
      <a href="https://twitter.com/mtdowling" class="twitter-follow-button" data-show-count="false">Follow @mtdowling</a>
      <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
    </li>
  </ul>
</div>

<div class="container">

  <h1>Introducing Guzzle</h1>

  <p>Guzzle takes the pain out of sending HTTP requests and the redundancy out of creating web service clients. It's
    a framework that includes the tools needed to create a robust web service client, including:
    Service descriptions for defining the inputs and outputs of an API, resource iterators for traversing
    paginated resources, batching for sending a large number of requests as efficiently as possible.</p>

  <ul>
    <li>All the power of cURL with a simple interface.</li>
    <li>Persistent connections and parallel requests.</li>
    <li>Streams request and response bodies</li>
    <li><a href="{{ pathto('webservice-client/guzzle-service-descriptions') }}">Service descriptions</a> for quickly building clients.</li>
    <li>Powered by the Symfony2 EventDispatcher.</li>
    <li>Use all of the code or only <a href="https://packagist.org/packages/guzzle/">specific components</a>.</li>
    <li><a href="{{ pathto('plugins/plugins-overview') }}">Plugins</a> for caching, logging, OAuth, mocks, and more</li>
    <li>Includes a custom node.js webserver to <a href="{{ pathto('testing/unit-testing') }}">test your clients</a>.</li>
  </ul>

  <div class="center-announcement">
    Guzzle is now part of Drupal 8 core and powers the official <a href="https://github.com/aws/aws-sdk-php">AWS SDK for PHP</a>
  </div>

  <h2>GitHub Example</h2>

  <pre class="prettyprint">&lt;?php
require_once 'vendor/autoload.php';
use Guzzle\Http\Client;

// Create a client and provide a base URL
$client = new Client('https://api.github.com');
// Create a request with basic Auth
$request = $client->get('/user')->setAuth('user', 'pass');
// Send the request and get the response
$response = $request->send();
echo $response->getBody();
// >>> {"type":"User", ...
echo $response->getHeader('Content-Length');
// >>> 792
</pre>

    <h2>Twitter Example</h2>
    <pre class="prettyprint">&lt;?php
// Create a client to work with the Twitter API
$client = new Client('https://api.twitter.com/{version}', array(
    'version' => '1.1'
));

// Sign all requests with the OauthPlugin
$client->addSubscriber(new Guzzle\Plugin\Oauth\OauthPlugin(array(
    'consumer_key'  => '***',
    'consumer_secret' => '***',
    'token'       => '***',
    'token_secret'  => '***'
)));

echo $client->get('statuses/user_timeline.json')->send()->getBody();
// >>> {"public_gists":6,"type":"User" ...

// Create a tweet using POST
$request = $client->post('statuses/update.json', null, array(
    'status' => 'Tweeted with Guzzle, http://guzzlephp.org'
));

// Send the request and parse the JSON response into an array
$data = $request->send()->json();
echo $data['text'];
// >>> Tweeted with Guzzle, http://t.co/kngJMfRk
</pre>
</div>

<script type="text/javascript">prettyPrint();</script>
<li><a href="{{ pathto('docs') }}">Docs</a></li>
<li><a href="http://guzzlephp.org/api/index.html">API</a></li>
<li><a href="https://github.com/guzzle/guzzle">GitHub</a></li>
<li><a href="https://groups.google.com/forum/?hl=en#!forum/guzzle">Forum</a></li>
<li><a href="irc:irc.freenode.com/#guzzlephp">IRC</a></li>
# Makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = _build

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  text       to make text files"
	@echo "  man        to make manual pages"
	@echo "  texinfo    to make Texinfo files"
	@echo "  info       to make Texinfo files and run them through makeinfo"
	@echo "  gettext    to make PO message catalogs"
	@echo "  changes    to make an overview of all changed/added/deprecated items"
	@echo "  linkcheck  to check all external links for integrity"
	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"

clean:
	-rm -rf $(BUILDDIR)/*

html:
	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
	@echo
	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Guzzle.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Guzzle.qhc"

devhelp:
	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
	@echo
	@echo "Build finished."
	@echo "To view the help file:"
	@echo "# mkdir -p $$HOME/.local/share/devhelp/Guzzle"
	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Guzzle"
	@echo "# devhelp"

epub:
	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make' in that directory to run these through (pdf)latex" \
	      "(use \`make latexpdf' here to do that automatically)."

latexpdf:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through pdflatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
	@echo
	@echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
	@echo
	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo
	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
	@echo "Run \`make' in that directory to run these through makeinfo" \
	      "(use \`make info' here to do that automatically)."

info:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo "Running Texinfo files through makeinfo..."
	make -C $(BUILDDIR)/texinfo info
	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
	@echo
	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."
import sys, os
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer

lexers['php'] = PhpLexer(startinline=True, linenos=1)
lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)
primary_domain = 'php'

# -- General configuration -----------------------------------------------------

extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'

project = u'Guzzle'
copyright = u'2012, Michael Dowling'
version = '3.0.0'
release = '3.0.0'

exclude_patterns = ['_build']

# -- Options for HTML output ---------------------------------------------------

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = "Guzzle documentation"
html_short_title = "Guzzle"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Custom sidebar templates, maps document names to template names.
html_sidebars = {
    '**':       ['localtoc.html', 'leftbar.html', 'searchbox.html']
}

# Output file base name for HTML help builder.
htmlhelp_basename = 'Guzzledoc'

# -- Guzzle Sphinx theme setup ------------------------------------------------

sys.path.insert(0, '/Users/dowling/projects/guzzle_sphinx_theme')

import guzzle_sphinx_theme
html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = 'guzzle_sphinx_theme'

# Guzzle theme options (see theme.conf for more information)
html_theme_options = {
    "index_template": "index.html",
    "project_nav_name": "Guzzle",
    "github_user": "guzzle",
    "github_repo": "guzzle",
    "disqus_comments_shortname": "guzzle",
    "google_analytics_account": "UA-22752917-1"
}

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'Guzzle.tex', u'Guzzle Documentation',
   u'Michael Dowling', 'manual'),
]

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'guzzle', u'Guzzle Documentation',
     [u'Michael Dowling'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'Guzzle', u'Guzzle Documentation',
   u'Michael Dowling', 'Guzzle', 'One line description of project.',
   'Miscellaneous'),
]
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
/* Hero unit on homepage */

.hero-unit h1 {
  font-size: 49px;
  margin-bottom: 12px;
}

.hero-unit {
  padding: 40px;
}

.hero-unit p {
  font-size: 17px;
}

.masthead img {
  float: left;
  margin-right: 17px;
}

.hero-unit ul li {
  margin-left: 220px;
}

.hero-unit .buttons {
  text-align: center;
}

.jumbotron {
  position: relative;
  padding: 40px 0;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075);
  background: #00312F;
  background: -moz-linear-gradient(45deg, #002F31 0%, #335A6D 100%);
  background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#00312D), color-stop(100%,#33566D));
  background: -webkit-linear-gradient(45deg, #020031 0%,#334F6D 100%);
  background: -o-linear-gradient(45deg, #002D31 0%,#334D6D 100%);
  background: -ms-linear-gradient(45deg, #002F31 0%,#33516D 100%);
  background: linear-gradient(45deg, #020031 0%,#33516D 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 );
  -webkit-box-shadow: inset 0 3px 7px rgba(0, 0, 0, .2), inset 0 -3px 7px rgba(0, 0, 0, .2);
  -moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
  box-shadow: inset 0 3px 7px rgba(0, 0, 0, .2), inset 0 -3px 7px rgba(0, 0, 0, .2);
}

.jumbotron h1 {
  font-size: 80px;
  font-weight: bold;
  letter-spacing: -1px;
  line-height: 1;
}

.jumbotron p {
  font-size: 24px;
  font-weight: 300;
  line-height: 1.25;
  margin-bottom: 30px;
}

.masthead {
  padding: 40px 0 30px;
  margin-bottom: 0;
  color: #fff;
  margin-top: -19px;
}

.masthead h1 {
  display: none;
}

.masthead p {
  font-size: 40px;
  font-weight: 200;
  line-height: 1.25;
  margin: 12px 0 0 0;
}

.masthead .btn {
  padding: 19px 24px;
  font-size: 24px;
  font-weight: 200;
  border: 0;
}

/* Social bar on homepage */

.social {
  padding: 2px 0;
  text-align: center;
  background-color: #f5f5f5;
  border-top: 1px solid #fff;
  border-bottom: 1px solid #ddd;
  margin: 0 0 20px 0;
}

.social ul {
  margin-top: 0;
}

.social-buttons {
  margin-left: 0;
  margin-bottom: 0;
  padding-left: 0;
  list-style: none;
}

.social-buttons li {
  display: inline-block;
  padding: 5px 8px;
  line-height: 1;
  *display: inline;
  *zoom: 1;
}

.center-announcement {
  padding: 10px;
  background-color: rgb(238, 243, 255);
  border-radius: 8px;
  text-align: center;
  margin: 24px 0;
}
.com {
  color: #93A1A1;
}
.lit {
  color: #195F91;
}
.pun, .opn, .clo {
  color: #93A1A1;
}
.fun {
  color: #DC322F;
}
.str, .atv {
  color: #DD1144;
}
.kwd, .linenums .tag {
  color: #1E347B;
}
.typ, .atn, .dec, .var {
  color: teal;
}
.pln {
  color: #48484C;
}
.prettyprint {
  background-color: #F7F7F9;
  border: 1px solid #E1E1E8;
  padding: 8px;
}
.prettyprint.linenums {
  box-shadow: 40px 0 0 #FBFBFC inset, 41px 0 0 #ECECF0 inset;
}
ol.linenums {
  margin: 0 0 0 33px;
}
ol.linenums li {
  color: #BEBEC5;
  line-height: 18px;
  padding-left: 12px;
  text-shadow: 0 1px 0 #FFFFFF;
}
�PNG


IHDR_�d`�	pHYsg��R@IDATx��]U�7��>�2s��$�ɤM
		�@ʄ�Œ��O,iև��=}���C�'
�P$**���F����;����If���#$A��p�{�.뜻��k��oQ�9�y	�%��@^�W��v��-/����K��@^�柃���K�H �|π��]�%��@^y���K /�3 ���=B�w��@^y	�o��K /��΀��=�e^y	�%�W��g /���8�+�3 �|�y	�%��@^�柁���K�H �|π��]�%��@^y���K /�3 ���=B�w��@^y	����l��to߾]�;.ɟ��@^y	�T�J�*�`6�3#G�<�Ҟ����h�,��N�ܞo"JC�oki�t_�UL����Q>�4O���M���MM�)h�m5��uCth����r�y��������:r�[���K�Y����LSlz�Я�����B5I�K$���u���\dR��W�S���kSJ�Vb��n�ϪG�SW�X1򽣬�=P� N�9a�r��z��`S���6U�Bg��4��dN����7G���!�Y���2�cU�NW�*��b�=m���5m�9����UE����Ο�"�,\��	���dž��t&�U�����8��j��˒��jz�������q�aA�r"S.*�@�%o:ʙ�ffM:�6�ץ	���;獳����ǖ��n��ʦ�"��ZNm��H��M��ye
����bj#���M6��A�(ߕ+W
��]]�'葈�).�H-�뮾��B�&A�a.K���"��q��w˒ۥ����Dh��E��Y%u���ױb'��*��P(K��ĥNĢ�pe�@�
G�R‹��J%��a]�ө���IQ��V�
cS2�j�GH�{���P�Nt�6��\�m����+j���Q<I�DR�s!��4n����^E�����|��uN�B��N��&R�K�S� �[���ݻ[?:kְ��>D��lj���YX�M9�<L���b�?�P(�V��v�vl���S� �U_���8x�(_�Jxʯ5�m��9�����7�(��s�NB:�]���2�L�(�Ȱ~X����$ϑM>�ۼ�=���x-&�$&�1�m+\���kl�)�s�bs3��Y&��1s��-�f�6������\����eŃ�T���b�('0.�,N"�S�]��͉�xL�KE�T�I"�1�g�3g��*%����2����u�9#�+3Υܶ_�0��E��Y��t�] ���ަ��<�n���=-��<�=���'Gڠ\m%T*�lK�DA$�Mjm���ԩS]�Z�N�h��,3L�%2[ i�(�.:Ɍ3��YB�]��AݰZ�(���x!��g\i���7=��=~�T_W���k�U81ek���udj�������x7J�]�|���6%��7�[ � ���=`K-�lJ!֥M�_�Au1>��xz#n��٧�ښ�
��s�i��c�$)u��r�-Ͷ�8��(2�*�v\�v�΅@JPE����Zfߺ��e˖YJ�6uV����B��-�������Q;.�D�>9���B?@/��
���{D�
��'@�J��_�]�$7� ,H����_�粒
	��#�c�y.X�h,vŬf(�
��3wߣ��+��{��Ju�莥�(���J�X��;6��X����޼���H�-�\�ž=�EM�n[��
r��3i_R��	�wZ���I��RTJc%;$j*�ӣJj3�}�*�!��r˪��d̽���.�[��U�9UHRB_2MF
j\&qK��@�KQ�+�Qiޒ:[͝�rOr�;tCu��%�̧*XT�����3v'����إ55���_�x�I�ݣ|_(k�M�qKRд�j[�,�ܫH�P�N��ᔘs���ĭE�I'z|��X_]�X��^�M���ߘ�"uU\�!r)E���m#�)+�޳9&�4��l�����t�r�J45�X�B�K�
+�R�yP�&��;G2�X�j�����$c[�h�t?l��I�3{',u(|r/4}z�'��<uUmi?:b�[����ͱ���pb��¼,6^��=
����->(h��I��bu�,h�a���^l�����i2�wI:��
��HL�mQ).�Ĥ��f��A��EBɍ�?u��+O���Z?p�y�82��G?MŴ�8�����@��A�7�N��e��ݽ��,�Eâ���Z&��g�ӹe��*M
i|�nq��xu��mh%��W�a��Mئ!�}ѭ�H 2�;aDӱ��rZ֋nO�;�����&	@/�U��x`Oa;>���aQ��T"�(#��KF��0�'dEz��D�g+�
3�I��~���&��$���t�ղ�W{��+�.��L
fW�/�Za�ߒ"� &���hj�L�=�$}����
N�
7�hsrt�rX����0:�"�>ؤ��i��֏-;����ߛ6]
oC.�|{B��pm�em�
�;�BTG��+JK�.��Q�&����'ki+��,.�B�i���̏x�C&�w�w6��}��m�
Y9�hBqR�͍D�X����%m��/w���M�#r�[H��2%���O4�gf�����b���{H��M\5#�(��m�󑞀�u>�!�m� ��z7�"J���Ո�^sI�z�xv�m���$��n�A�?wՎ��9��ī���X�y	��8�hG�:�eRKH��'`�.�On���ё�X!�M\�гᖲC��G"�|�c*�&��n�M�p���~��{)q�h݊4���,�š̊ܦTB�Q
�$��JIKtn=^����n�NM�/�~��K���_*�
X-��0B�HS(�΂R�q�a_�]��`~a�����ロ_u0)	z�v.���ZW,,�w#ȋc�<��X,��S���ؕh���–V,�?d��4�k�p=*Q�_.Y��
�^%�z$v0����FSV~%g�bQ�5�[�wIq���`���x\�9���	s�?ᠯ��K,��P��7S����]W5G�y%ϣ��S�_�������:�&�%�0z���4얧[��%gg��2[�f\$�P}K�'�z�����1-2>��f�9"�e�s���@��ȬYPY�;a�?�%p�I�LZ	�K#k;��}B����Rا�� ���26il�#uu���ٱ;^����q���~בs��T��MȦ�d��+T��Z|�g�2{Sv���^���""�%�J��}!�&���|�`Sl]mm��,[z��!��&\�9�#���E���2��6w't*�!X�|��n%T�"�0����k���=7g%m�k��a��X��ͪ�F�������G��3���Q�l�ֶJ��Kn�Șz�A�!F܊�q��6�{c����8�M�p��$Ҍ��E�|֬}��G�
%�gal��C1^0������
{C�I��{9QD���/����ǜ봗S�z\R"f�>'��ݱ����'����9�quuQ^z��M���2 
� �um�������>���}D	3Zn�?�+V8w sd��fd���z���ww?�l6I��"�����(�ӭ|���^�*x*���姖B�=/��Cܶ;�ndSM�3.�庺cp�#���7�o���|��:߶�M����N?�~B��0��=��{��`'Ԅ�Y¥ԢSs^mx��SO1luσօ�����D@ǣʧ�<�y�;�]�[�bwAۅ�`�R��O�m��|�7f�����W��V.1�L�#�P��^���u�@������]|	��]f�4`6.�GC����>���(/<x_U���f
���g��`ƳT��aǸi�sJ
ʪ,Ӿ	Xʩ�M���Xr��zG�>���C�e�U�&B|�Ol�+�[|p]W�
���HǗ>z�ſ7���iM���*��v�w�\^��i�2����j�����N�qL[{�\5�Ý��1���N�o�8%p:����3Y#�J��*�e2wұ�D�gG�����6�:]x?����x|2�hF
?�m�O�rB2R='�r
�
ԃ�a��B�AX��m�'D&oв�>�g�=�� \N(CI���2�ȗ�1�(Nd�f&�r��g{;�(j	I֖׌y��0mq�F�G�s^�&;��
�\DmJ��GBYX���蟂�Y@q�3��:�-;��P�\܊7�u[t�To6�B����m�fy���WM�C�M�f�ܚ���:����t���Y��X�tb@�vY&��2K�&͗/�!'E<���0��m2[i'5����4,f�D���s�h��$���y{�O���K�*���{wd~.�r�������,\���Cn�)�nǧLJJ�N#�>/��Z��2@`TY�䉳-S��	�tk�P	�%�ޛl��'n��
��1?�& lw�R���U�����LvN��/�jD�%��؋M&-����О0����v�w��2yM��F蹰xˡ��e��3�YT]�Y�R5��L����6��ߖ�gC��q��l�t�h�J��]*�D��j�+�=�h�&M:�=�V��̥œ�SN}�e%Y�s�O��SE?׬e
NTu]uO4�]/�JO��V�O<��S
��BI��z���p倫�j
/}��1��b�bS����X���v�#��F��I��W���źMe�Θ𑐇����ˆ�W�zhBI��(���){P0c�-	�m����]�uf�5?���ع�^;��"�گd�=�gw��jX_���x����n�6�[:�֜SRr҅m���k^g�N��u���!Y�Hܲy4�j��ˇ�?�����P�q#��cl��`ފ@�#W�(�k�@��<^h~�ho6>�`�*a(�oS�=0��r�Z�s��C�v���Hɚ
�B,�����q�1�͇͝�֦݋�Ս—:4#�ķY"��H�����t�
�|e�����vݤ]1%[86��d@SNF��2��0�md��@:���D�	�m�3:�x�UX\R7PU gC�S��3Xv%j�n�����E>���%fVz��g���������7"�S,�=P�u��c�s���}����0I��N�ZS��u�y��(�|���mϮ�����oG�R�ľ��Qn�wz����+Q�l���2%56�6��
疗�Z�Ǐu䳓TR9�6�V��V%z	�p�f!�����W�\���Fv�y����K�l��x:Ti��B��U��n��M��}FC�6��z2UOjeQQv���"�ʮv�4�s
6��Sզ�O-*��M3�l-Ų�9T�#r��3v�����md� |���a��h��Ԭe�(�n���ϸ�r��e�+��M����\x��qӲ���a!�2ێ!Y�U�iS�m�_���vC��62�}��zr��]^-	��{��BZ����
+^4�+d��E�-U�\���}�esk�Ж��dآ���B).����c7X�>�	�`����&�^f�)*
�_�BH��0A��^�b�L/��
�NJ�M�
���^I�,��4�0�$U��ܹ��y�=V����=N��(?�dr zt�d05wKa�&Ajq0�vӆ�X�"�坥��p���a�tm{�\�K�Kg�r$a
zAH�ʁ�ns�¯����z����y��/�r�=��f��rUEA�p�?�8k%pƠf�f	&�	��~P��[PU͒��ɢ����J\]�l��3�=��H�4�j-����o}�	\9���i�1��o‡F��6�{T��1?��Ĺ^I|n�qN�z���ot��֛��IX��j�,?LB�y�A׷
����y]�"�t/b�M�h	�uBmP��i�Z�CIQ�Y}���e�3�D���$��]\ �1=��ܲ��׃σbj�Z�lF�0��<��.f��߯i�] 9�sAXXF?�����h��02��1sv&�X����ݫ$.�U��ܣ}P%�]�5��'�2�k��f�.���QYyF��k(�����ekO��&����h|<R�Aj�%"9&'�*vꎱ~ݵ]C_�m�uf���k�+B�"]��.&}��W)3���`ߊ�oc?�5e����}+�Xo��E\��!�},�>S��>]������٣�t�i)L�Y��*�0�v�?�8�$��������g��Z�t{�L�J&F�Ҫ��tQ����;)�a�x��ܜP��گSH~�	�&��	I�r݇w��.M���
���x)�Ms�־؅��ӷ�a���]H� '�
w�r��p�f���Rv�N�ǐ��%��~$��N�Z�T䡉Ζ��1��
����2@��?�4�W���w\U�����d�=�X
��H"Q�Μ4왰o[�ec��s�;��hJ�	��5!]����l.|'�	���6�W��^B�f���2���TxN�k��y�{tn������J����m@�HQ�(�	IB�#s^ߕ��$�‚�R�����{����Q�?l�µ�'I�Y ��6��[?>�_:�c��E~�!��X!Y���j��f�Kp�M�M��/�2���^$�d=����V<2��k^g�N�`ޑq:�G#?.���5k��L�6�1�ZՏ��Z�1NJ#.��6:���"�@a8���?�2j�e4�8�θ�&G,)�ý�a��e��4� ��v{�=0��`��s�=�nY�r�v���/*��/.+��������ϳ����_@6[�'��M�5*#��*��a�	�4���9�.snRKb�)Q k5���Pw�Ʈ���熃;6,�^n_���g
㜏�b�s�>�Z_��XzYQ�1-��<���Љ�{*c���}!�
HI#ߤ��=@�CO�͉_s��46“<|/Ձ[A�M\p����7n�͒����[�7��&�A?�DD5.md�~׬�L��sk�z%�!��[��_�M|}]�6�e`�+"�@�W���"�e,�nn��}d&2�Y.���>�G�{n�aji��
����%���$|���C;�f���*�r>a1vƒ?�88-�w],W�M�u���-��f���8�0���a=���R�W�� &��m�W�B
QS��wK[b�[d�#(�4�؟�Y��v�3%�c�m �'�GJ�l�wY?B"Pp����|�t٭��ڞ͖�\y����ή�W��Ӱ_�Pa�A3c�P�5:��ǒ3a�!/
(8>�a_�֓��ց��FB�L�����&]�lra��%4"�J�X�%�[oCGi�Ñ����0�@B�xo2y��ݽ�4>�ͧB�~���2ւʒ�@<
��<`����y�>�mA��m��_Z��U��®v�2s�闣C_]ߙ��A�;�������ǐ��X.7�)�w��W�T�"�6c_7��W��ŖL	8v��[+�Du�����l�}p�wN_5�X�-�<�ӴNW��3n�IϖU�V��ā� 0���ѹs�g���~�-RD�6
�t�m����������S���J�V�8�xǕ��`��uH8,3�"�&LmhN( `i|!�-�M�2��h4�fҀ�{��hI[�jS��m퉚W{7��|~WC��M(PY�wy	����=p1B��Aq#��~����$�0���ә��WVv|��U�n}�G̔q_�̮��m_�?�����[�UJ�
넨>{U�:��WX�~�
���G8���%�X�w�׃�k��3�7���c��-p9�3��_�lq�Y@�;�S�Fۗa��⏥q�nHMi��B����p���v�mh�̯ ����9c�*,ɟ#(���H]u�U��ԏ��,	9��-w���
�Ua#�����	��T.�߰�/Š^���d����>S��A�ѤȊ�E�@�S�����>�Ľ��T��u~E]�g�IP��,����s?�r����l����	���Us�G�]2j�	g�@����
C�����' $�����!�浘W^s�O�N��NU�[c�*5M�ʐ�K;""ٟ����;Ԋ�G�k�����%ԴU}T���&���03٥K�A��2P4V�&��!�B�!��Y9�����>�Z�K��ݸ��M����m:�P�[��/}�����C��\���b��y�諃����F�	�4.�h�����y�An8�8�����ņ�L8“7���DF�j#�� ��n��ƼV}+�B�5�ʨ�8����p|n�SM�M&L<��9+�뻤���$�5A����+���L	:u�,�����ͦ߆{B����O��Kw�r�P�����!�����wX_��{Vv֊�ز;���1;���{���٠�;�խ;�0X�Ŋu�N*�lg��4��	�l��T�tq@�vv�t48�r~�웰�� �_0��eE��?�e��6B��ܰ��X��Q�s_���~cWUD��f��*Ş�Um	��.�ms*�?$�Foeu�n��i���[<��ʃ��߰���}�������K��;�|���*$ދ����9�y=p����n�ʖw��a�S�aL����xfp{���tNQe�@_w�8�iP~(�JXj�m�*��Mee f���Yr�MY�`��}v�C�v��(�"�j��Ux�	c�H��:[⥾���<�.lr����+�P�v�E��������-�K����̴�B!M�%�5�%<�;��7�����FƳߦ\����}4eť��rա�Z}�̇;Vb]I�l��f�\U����^l���EP�N{F�t�(�`�~=�+�X��=�D�m^��o5la�d��"�}�8~�ɦ����/w��8&�n�)�i�����c/Xe�Yx��#�@�����ц*���%��R)��R����ުY,nv,�#�Q�a���hl��������Y3�fT��j�*aB�?h��C����w�v�<��Pu�}���e�p��l�3���7���܂�����'���[�"�$�K�:���kY�ٛ��@v'��{�nn�d�y9�	-��/�H?�%�.G�_}ܕ��gdAe2�r
��n���1]c�9�N���r�ZY*Z���%K�e��|[�
Ȕ�
��|�Le�5O^���i�7A����f��1�-���T�FP��dW}G4���m���������M���+[
۝-�ȹ�ek�Hr�p�2�9�J��;�(Lv���B1x{�����1��"+{��:�?7�l����que���M2��''1��W�qV4k��*���--/������@"�o�n���
���Z�M�\���Oå�_��w�D6�)�">��%C	~�XɝX82S��[���%���������@OgV-�T6�gơ�����Ȯ7��z�oad\c_�w�ޓ����T.a/����d�[<�ԏ��S5dxJ�D>�q]�{��z�@q�NVْ����=�'r�#�k7-#����ge��H��7/��O��Ow�_6�f����T�[����ȿ�K���)�|_<��#.D~x�ޔlP��m$�[xX���_��vg�.���Ϙ�VV�����|�m��gu=W +���e�"LJ�j$��c�ȼ�?���x�(������Y���x;�U�&S�m��-�榦�ϯ���������80���� �������n�Q�DA🏀�5��.(���<�s}��|�s�w�il�([dI�0�5Z����֎�J�!(�c{&�x���]�*+�������f�p���:��Ae�fz��r4��k:Nt�V�أcA*�3���C��*�'�����w~a�f��3������}�G�0_�L1��3��
����=

�Ǘ.՜65-�����j�J�F�$T��ײ�����};c���b�v�C �y�*u�{��x=�b+��q�H�z�����~��u�WrbŐh�{.�����5V�5��`��(��0�/��G�?bi�;t䉣�����D�O�1Y���G�]&��q��@��:�WSفO��1�o�?y	�}8e�W��b��r9��U� "y�%�U5�/�{�ٲ:5�z��� �dYYL�o7�'������Ɩ���m7×�<hmJ�����5!���fE��ej�1z=TS
�˾�z��'�����I�R#J�	�bp�E�B�/�Q0D�?���7l�A;/J�a{L@/�%[`ݠ�l�q���R��D�vzS�B��Ss�S,U��&)5������$���g55�K��|��;��4	��D��[�/,�:)��p�Ƌ�Lq��#ֶ�ԡh��ָ�E~�O�쾔6P�Y���[���j�8!46��Q���&��e�}~�H@��ђ���=�7}z#_�b�h��P��ukI@��}�Q���=XXÈ<�j]C�'�ѶtuX�ܜ�Z��@��=}{Moq�=�}�Ů�2<���������Qd�	��-$G*ˏ,�j���â�BG{O\�հ�H���8�3hh�e}�ps\��o�
��fT�ĸlow�\�}��Q�H�
����8�=�;�g�v�Y�z�<ը:UW� �|�X�N�~ol��y	��K�km�5�~ݴ[�n6� &�����Ά�d���Ir���YD�̌��*�-��ԁM�rFV[�}�J��#c_����;V�>���-�Qp@��g��hH�e��in#Xl�V�ݫ^;}�{
˺Q��AbnӴ�x�9��r�@#v0b���M��!c�@oP���oyG�"ؼX�W-V.�S*%+�1��$�.��A/SN�-삽=�<�i���T2WT[���������BT�hB��$`��,�K�;�L&�҂qA��͓]޾�����d��g�Z
&/Q�|��a���߄$!�2�E��w���p���j��F�;��º�λ�"f�����"Q�� �A�Z9�Sx�%��)|��QKY��C,��r��i��h07Tf����G�F'O�u�����}�t����Q�K���
��m���}V���p5@�?��)��5�[��{z0�ޒ��b�$��k�/�d��P�HT��q�	!W	@����Ҵ̙�,�\����`��y��yK�o�xg$p�,��pZ�r>+�t]��$ndz9��XEo6|�*�nj]¸<.�
�	�	������(Ԍ��e`9�m�K����O؎��1Ԉ�ԗn���1T�'�o���+��&��N�}���@���
�HYn1-��D�Ǧ��\:��)#P)�,f՚�vm��y0���X*�Ax@/E�GR7�'�S��"D15L\C�T���e���%��D�0^�PD�p�0��ҹ�,������sI�X���9M�� h��p��x��UBR���(2�^�-��i�Lcw�D�Mgnp��Վ���g'������R=��y�"�E5[2��� �[�%���Y\�+-�*�DS�2�ƃi��à*��L�O��.�HFMf�Y�6����i�e^��*�����ܱ#�f�~�y瀺b�o4���k}�Er���ë�^/_�bX�:uC��T�|�Wy����K!���n)�9)�#�y=�tҌ
'�\v��y	�L�X��p���Y� ���q$�9rٻ������]3�@G%p�,ߑW�N�,�����C8~��m��n���fC�%�Ml3���?lA�itḠ����U��{z~�5N�A�_y[m��-�+��_�/���'�O%`,Gc������2�D�=�tE��X��|B�=�W��ƛ%x����^7�H���hU!�:)�v$x4�XA����.Ӛ	�m#�b�")��d*��P����j���~X�Xc�5ruaS�ѭ����(:Ӷ�W<̎����s���1&�H_G��J���ӭ�џ����}ߜғ�\��1�]TTD����7�/!��,jJ�H"Q[F}9f�J#�B"�(
\��غ�����z$���Q6�sU�ɋ�$1�^m��B�et�������>��A��5�87�L�wc�X4�ȗ�8W�j��ȗZ���=��6oz:W���}��C(�ȏ����S'�G�X�<,r���2��

�y�s��%~�����pa�\6���Į���\���I��q{s��lw~,�J�+_���Ѹ��r�|���楶؅��j�ݰ���-_�\����? I��*�s�R3���a���˝��v�wQ�	Y���j��233�?kY?t��M�F�q�����f�5���WȆd���`hɊ����:eVCc�/�ó��U�+�Sɡ�S���3;�%�J+�jgIOd��J�g��T禕È���3�?4uU��Iܵ=���9tFY0������9V�I��
"�����l�?J�Eo7�w���䱥����{��o"�`Dh��Ik�Jڕ
!qCQ,5�Kq�Y�����}S<�Xv]��`(#���^��'
�jܺ��z�I�v�ñ@�ž�{~<Y�i�gM�gH�ڎ��%y7U����o�!9v�zǼ2��K�mqi�|��<�nR`[�ɨ��j%�au��g{�>Gc��J�+_gU�o�y�Q��R���L(�;F,���I���rO�@�P�:`�k��K�T[�rq�H�Gt�eVr�e��d�{��8���t"ӭVd�rm�:)/��]��"�7-šE`h��N�'ոfaTq�/��V@�`���(��߅hN�<ﻏ�{W��QLGd@��2y��r*�u�X���ROHu��:��yta�������1�w֣�鿥�=I.���>g�iχU��V����H��5��P�����Ʈ�[=U�5o��8p�TZ���׊�e�.�Tu����w‘���A
�8�5-�-;,r��ŕEx��]�Fd�=;%pʕ��XU��-1�{=~n��Mk�I�"`3	_-ĶxM*�����e�$:[�3�2}J�<k�}R�>}|��՞�U0|
a�D%��K)�˥r�`$hʽw��)����J�V;���`1V���[��q�O�.HZf�o�WM�?��yC�8��3&]�}�,
�*��N�.JB����S��E��Kbߝ��R��+���T�]�m�n�
Lrc�t��6B����ni:\�J�H*3'E�B�֏�-�mcϏ�D	��J�	c���݂)/t�(�k@�^�A�E2��E�!줊�ך@`دזB�ME���^UK��l�8T]]=���M)ݔ��e�=���r�84>�I���:��`�u��yWH�:D�^3�
��a�M�l>x�Q��s��?�z|�aLftW�O\��i�CR�L�e3(��N
3d�rk���v�ĝ�Dc�4�*�Qa;��ͽ^��(U���o?�����*m�ug�c�:��NuIn�b� c\���i8b�`��������J�%N}2���/��g�νuߧ\�d1cZw�`��{�s�{���:VE9[�j?f�;F���9��u��M�M	x!_[8k�1����p�U���󭧙��� �J�F����(P�=V���/ e�cR��w?��7o^�^���bݝC(��?˯X�ć����H��
0��A�wp��x��r�h����\�%y�l�CPE��t����T2�y7j�i99\�����"���9���/<�VN��ff	�>[���;�w�+~_�`K�?=��u�]wUe��_�,�\��VT'�}sw�#�L�/�8�n�M�6�����6����iy>8nAJnɞT��?��Vڎ�_�͝C�aRPL���`,ӻ5�Jx�F����;�!�ԩx�EdLr��ke+!� a*ص�	+�+E���@z�`%�F��_UH����W�x���Uc�|�۳��׊�6՝�]]Z:���Y� u�g�����q�b7�`W�o�.
nfZ9�xVz�Pk�����ð9���
w��;���N�����<ȟ\PtbE���鬛�)W��_9�W�$z�S��������`'6�4�XL�yY.ǣ�e��mH^�la1��LSɠn��Қk��u��������C�QƦ>XD�+���CũnYS}��Ej��+�҈5�C�`����(@[��r}��Uh��[���'Ǫ�"��7kd1��;�I>}��7R�����Y �D?���3��pw=�,@ɖ�B05�{��w:����F���{�[�*�Av�w�yV��~�VQ�4�:!�9����3  �N�ј�蠖�(t���o�%�
�
��t]wy����k�_��;g4 ���3C��;���&�<i��`���[|WI�*���'
&P��dS�^��&����	��|���~�-�˦𫜬>p[O�L��@?hr��3�_~���w�.L,�Fp�9l��8gf,uQq���9�&a"��(����,ܛm������-d�%~���mP&��m}}D�:�}j�^�0�$�nՊ�ֹe�r&z^@����A՟�)�{�xG�/8Pc�2�os(�(L�m�J۶P#�ޠq�Up4|S��Oi��g��>ؘH[r�C��J��2E�}�ږt	��+�q#������s�t�E���	��AV�.#�����7Z�l��'�5�t\^��Ge'�mn8��D�`	S�KP3�A�y��PЁ�m�.�5�zXѥ2���ںw���t��	�9zD��DQ��!��UȺ�<�s��s��ld+V0Ś��/^>k�1}5�E�"�uѫ�]��MX`J���.�!�s �����5�|?[�J�
N���U�(J��_em���}Ͳ����q<�fA�X�-Q`��P��S���^����u'v�3��܊��ġ��A{*�3��%@뫉�e|�.����+Wa��F��O���9��>�2/����0\^^
��Aj�"%i9���>���o��?\�ףV�I�/�o�T~��/�Q�;+ni�̶��^����5�⊽���Aj�1�����J�;J�!�Q�/UX������ݼ��	}[�/"��OZ���N�\�m�}x����헃�/7)�ҵEM��O���������u:5v؆R*0},���\Ȃ<�1"ٯ��97���
�/�2d��wМ�f��B��V�]QY?�A��O���O�S�l�gNiiH���[�$̌+nFt���"�v�z��C�8�3Sru˜�<f��+�|���i��F��M=����x�E��{���_,/�~2ꎹ�4}��\P�]u"�vj��9�)J�3��	�	kt[�ʁ]Ka�;ry�]w�K��
�̞JM�#��KH���2��FJ�3�ǿ��@�������;t�<)��|���[w�-�&EqJ�-D�bD���K����:[����ې���S�`}�xC����V��:8�C9�
aLc�:�druF����2��=����3w�S}NE��l�dbU#�@�	�6׹��	+
�(�W�5��w�P�U�3�%:B���U��=N����Nv��s��>�7!�v�q����-hSu�UA2�P}e��^��N��{ׄ�!��Yne3ɗꊎ�߸���غt'"�%�nI:�7YD����RL�ﺬ<d�����5Ѽ��_�+EK^h͔��y��I�;9�޶�2h����`O	��Y.{����%%�;�v�5���PRr�����:����G�@�i��˄d���y��˜RAY;����C�=r�I'���?�v��z]����j纾+��@�V]��ۻ��s��A��}MT���S�uy����59�`c�=
�)i}��}�/�����2T3��X"��OW�.��g�u�wZ�5��e�o/�vB"s����ܥ�|.h��TT[���u��UF�=26�R�O�j�le��:y�`�A	�{(s��[��4<�P^�=�3�U哸K9�ʃ��0��ψ���9?���~2��$P ֺeb/ȥ��`���������ͤ��	$�/
�9��W��w|�Nj\�H�A�����W5�?{��9���t	�*)1%k�{Ф6�u��\�0�z���;rؗ"�/d՟g�o~��Q���ױfE*�^<�-@IDAT�UD�(¾���:
gʕ����p�$��i���.����G�7#���W�Dh.�4;��C��y�[3Qi�l��4w�e��y�����fk�nPZ�hJd~l��-y�q���0'ɨ͒$��&�2�6Gk��[	R��5�|?�J�m+_�9�/yy����]���x��M��.�wp����l��V��(�#i����M��p���ȐDo�O'��7JU$%���B�����<���k��e��,�D
����
z����1�i=8BR�]��WR'+r�X��6N�����_��N�±1T� T�Hݬ0�e��/�![%xF�����O�s�얢i������\j�us�f��C�
D�t�2�GY%W�_��4^WP���#���N|�+�x��璩���o#�hJ��SA�T.zq
|t��tK�(6��N]���8$2å'��+��)�.�Q���0W���A٠�d����u���cV�Տ>��0{�F��W��{zeg'�I�6	8�J����E��z�Mv���Ͷ��X��#/W����r��J��w�T��$By1�!�?���O�V�|aY����O��o_|�8b�s�	���&�mM��œ+{�"9p4g��J����_m�0�L}'�-��a��PV���Ξ�:� ���
-�>�tWW�>���\��H��`X�V@��ͱ���{�n9�-���75�]D,�ow�(�S����8�SY�(�r��w\�ٽqCZUע�̴2)p��u�(�$N&;�X�-:��;v�y��-?�� ��--=H5復��ɖ��<�y��Uy?��(��iOE�떡����"��n�zxq�w��t0���*^g� Fȃ���\��zv���>�
(ή��ɀ�����U?�xJй҈�dH�_���(�����q ��TdS܆��y7�>�G���j}MɄ,�̨��{�
��K?��R\���9�;
��V�(��eU��q�O4+�mV4��{wٲ��v$QA�We$0m„�Rw�t�I�a���t�-�c�X���F���̈́�&W!0p��4�&����S@�c��ni<4��-.�~\��Q��9o!��
�C)u,��}2��rG�mʺ�~�M�I�v
�5\PSӇ6���5�q��KҊގ��u6J��t�ud��%Խ�ԋ�l#�r��hR_[��д�d4�>_P�o�x<�3�E�bW�)��G��6���J!+>���B����@ˡ��
��k�"���L㟠�����D�m�J7�D�6�-QX�X�L��@޻�#~=��.C-��3a��"�A�Ӳ�o�)�\1�O��)@�"�i�� GiRl����܏���@G��Z���+6o��?�SF#�
���LV~�g�9C�Jfː�E�&��.�����$��u�Қp���`4���HŖ�KZ��I+f�d���;�ѩ�L�%qi8��Փ���[�a�@G�?�K�5�e���@�iɮ�hIIf�����K�2{U��{m�Y��x3I�.08��=��;��wPD�QA�����S��^I!��v���v��j$p�v��m���u��E���$	�0��?Q&rw�r�)��X7{C/����Rf"㍋��%i���kQ4�_d��ML ��Ԁx?P(����(_gE>����k��w�oi��>o�d,E�b$�?6(�%iK�����z|"�d1Yx�H�!fٿ�cs�%Uݘ��N˱��3Ο/ٶ"�&���C(5�����3s8	JN�N^��^�DS@c��"EӑD�Q�>v@
���i$��N�#H	�?���tS�(�rYV�K~��d(�_d��Y-��7��G����^�{�"+M�LW�Ύ�y4��ȩ���b	�m>_�������ݹ���s.�Z��pbG��7��Ea2���:����w�P�9���īQ�}��ގ�B�Uу$�)e��h;Dі)�B���x:������)~��檫�ͬKND}r߼�g�j;�j��hI$�����3�w��&{���~�.ڲ(�>�m�d.�,8b���9e���am�:��A�;vn�F:�t��b'�f���C���|n%����]h����>��N�@J�Nd�����+�߳5���O��r�����ۓ%O>�=����"㴱�ٕ
H��`:����3��;���S'����=:�!�с]��a����d�v���u\���x{�V�2�{�^6��a�P�X;�os�|9f�!�I�(]�
r��H�}}
��O��-����]��gIp�H�Vy�x��UŇ--�Q!�����#\���Ie��Ώ9w�-ǖH6���jJd;�]��<x<Tk�3��iVrݲ��ܮ�����o�H౗��������F��� �l�*�����Je;�Z]]Y1��X�VB�_��=�G�Ҝ�o;�q	���p�߸�kf�;�Cc����m�|�
jG,]2������Z��_)��`^�]Dl឴m1���!�ъ��"il���������v@��hb��݉����?�����kk*�Խ�����եm�����yư�v��tOmG)y&�QpεN����c���϶Ù�ڽ}�P��
���=}�8�H,�vd�
�0&�O.<x/��ۦ�/atyHV~����(,�W�ؾ�ҥK�sGo��p���N��ѿ�|�=58f�{�MR��r�j„f-Ӛ2��n��{���9
!��2�RY�Rv�[�Yz�^����N���&�W%_*P��wtk�vǙ���%E((ӹ�}�2T��P8��&r����������k�=���7�BS�	bA,AЊSk��=�jm���j�}������u��m}���Z���*���2�A�B27�ә��R�I߃��S�ͽ眻�����Z��I���P�	�̄4D%��]�vn��Ңڍ.sia�O��~�s!��G��S1)��x�ˆ���l'�ݪZ�>���ayR�Y9sɦ�x�m����{W���О7(��c��J`D�oP�����
�y��sgG�Pk1�.g�V�z�R9`������ WI]��M����h�5ԟ��>䮫N��*�s�Mc��w� hF�`�=��N�HU�_�n[,��e˧�������Yr��=�K^EE�๧�k?詀H���_ޟ��YzR�T�Rij~�,�ϯ��x��A���ݺq�S��x�=�?��)��㰚��܌Q�`6Ix6�Z3�{fMEA���V�k�?1�[�Zm?�~槩��3N�۰t���%Ce�{����-�³����&�q"���&�`>�A�mM��/�,�m<��F�zr�:^�b��rV_��-���$p�wkL���~8��SV��|��N�O�������O�ԇY�b1ZPij���&]�`´/7-ҟN[�v%�%��9�����Oj[�P���]���A�u޸�4wÜ��bD�����m�p߶�H��;g���4ܻ�<r��]��IV4,M��$`}��]���[�|�a;����,��kr�����}#<
��G�x�}������xՀ��
e#��u�`w��k�����2��U&�3jko�����kD��=��v��U����8�}��?�� VY6"�D�b}	no���Cy���S����������%��W2�U����Y�0v�L$��Tלk�LL�ݝ��g�j�wԟ�����m�Hv
��5�����6����s8�M�yA��>���x��ꕘ�D��<p#y�:T,ȴ��lO����>�1�9Ty'�\�d���uJ���Q!��2>}��E7��d-[�i�/;v[[<��@��=v�[�������fޑ��f��X'�`Ɣ�dӸ�4$����eg�bQ�֢`�X��ν�P'i��t����_�B}��o��Z]^�֋$&8��)�����k��P1��u����7�ܞ�f�Zi[�^�����9Ub�'�ý_�={���{����=p���!���}�^�>	���+�0����V9vw�H��)�u�e"Vjە>b�X#[N_1ȣ��K=H=�[#�mmqlk=��a����������Ug����
������ˉ���$�& �$���G���a����?(�.�X�y�%��E��
�|
Rlofԋsf���0,)��m�]Es���.uMųl�(��qU��4T��CK�m��W
s���a%�v�9�9���[�I�q�=��E����P<I��k�[n����%�晝�~`��I}l�x~����q�L�f�jP
_��3x���������0 �,Af�P�GQYZ��G�LуBA����UP�wx�vˌ�����67(���g�r����>�fO�O�s�"���%�ҀR!O�Ƥ�$��.
]B`��8�=��L+�E��LEU�<�
�K��T�H���3
�(j�i7��b�l�-�)ߤp��M
p5�Ö �sZ�8�J��O���%S�9��S����z��{�N���pT�s�K$=����}) 7
����i9���c�f�f�Y&���p{���˄ˈ���|a��gm�R���O4�I$��-������h[^Ue�J�Nvs�g/��>T!����@�Hd��Hp&odz�1�����O�����wt\`S#��]�a�um���_G��@�'*R<���y�m�r��۔�)�)�A9�ʟx5co��I�n�O��P(��}�g��
�u�K/~�P��^,D,��b���5�˳���
�?/�-�+��e~�}?UT�T����V���V8��aMa�AU�|�B��B	;�Ar�Ϡ�D���؃���/���5�|j�UW�9h��iLG�����|��MV���=y��LO��e�n��B_PJ�>�>g��#����M��Ld��p�qo))����=��n�a�E㊄��%��g�@WB<�H��R�j�x�uqI�-	�9<n�R��cz"%'�-�}�=�/���P[ �R��Cʡ&�*��G&�������>���g�*g��Xo<�b~N89s����$H([�>Ԝ�Z����sk������줺���.���Ǚ`��/5���z�K��Hw�z�$a`���\�����K?���wc�_���)_�tW<*\�����ز�G��}~�=��p�g�mI���*B5ww�,��.�8 L�ZIq��t#!�W`"���b����'cg�Z	AM?�T:>��[D�$+4��2"�8�Z�El��^p��gu���LJ:ս+�%J�{?�O�Vz������o񰙋Ϡ���OB�!��_j��G���\���I�֌�wf�V>�����U�V��{��Q��%b�&'�,�>�v�|p!Y�YT?��'�UI��{�,�tǹg:<5��H����%��o|>bn�GsY1J��Y�p���l��j�m6�AϕY�P�
����b�����V�:��p�G��w^z?�A��k�?y�1'���T8=C,ꄲ4(M��
%r�H�	�Sk���L�~�e���U��&c�ex �|�?É��"+S̖�3@ީM���	���o�K.���Uԣ3x�r�ƒ�c��¨��AHڿL.k=B�6�Gs7�%��\�^���F�'?�
|Ѷ��{m{�P��M���-[2)�b�������v����Sn{�0'f1�)��$l�U���Wh���&g�q�-tUV�������ՊPvCXQf��m�K���
Ԗo D
+�*��0�`bŪaQ�Sn��
�(	8����Wi��
��,��ߩ5�y�f��p�������Ʊ#}]]̰m02��5�Ev騳؄\��OV�y$�����ӓ�Ż)ڻ���U���r�/2�خ{Q��8_WQ��d��g[����u���sTB/��w?��{��,��^�)����}��c~�=�'�avs|���w�N�S|7b���6�ƊTg���{-��V����H��H?��8�UU�m�W�D���a���*K�Fi������}���w�.�̙2@��֙��G�BFU����{R�?ޏ�u���wyR�),����,���^P�z*������k����W3��8����P�璊�s”�@��ܬor���Y�|n6��6��+�c�6��[�5!���κ��U^o[他����x��:Rz��W
{�JɃ)B��������t��>T�8aYKI�[\-g���<b�f���'�k*�
���dI��][�d�������֬2�:�<8lc�Q� ����u��$i?>��du��ޔEv$���͐IFq�/�f�gN	�'C[7��
��CL�P��d��z���Q��l�RI�����"y�#���ǐi�$T�q�v��3"��4��5Cl����^%��K�M���d�C{�/X� ��$d�6���@�'+7�gƙdJJGA�֑�%k�ƞ)q��*{��6k%.N����҂��@ejK���"�s����[�m|��mÑ�n7���F��oڙ�\�r<�`R/ػl\Q�۟��<�c�k�W�;�3��º�Ϲ8�q��H�l�3P�x����M��ƌ�~��q��6���e�Mr}Y��-�{_O��+���O�S����=�O����>M�����͛c���&���_���P�^���@-bh�v���l�6"A��a|����܂���'儲��tm~���wd��]��7o�H���ɾ��A��<ts
.�>;�H�6f�d���vȜ4��$1��l��:�>�x��l1�{ܯ�~��L�h��U��D:䂖
��p�K���~h_��8��#��޻��E�H}5��A�X�`\���얋f$}J�;cg�F	8���2~%&k1�R��:����5��O�N�H�kD�l�+���(NZ�|�
\�vM�1]nV�U�e��ݞX4x�h�]
jթ4�I�����~;�Fѿ�[A�e�U9�bs��=�~��B�xΣ�%�K3Ͻ�C�;>v8��y��x�Z������e��듼W��Ck_��M���sI]y&�
2��s=v��F�� ~���2��im4�=�q�"�Jw-!�i��j�-�N����CPȊ&�|V���%Z޾Y�$5��k���ST䵴����J���߱Wc_�	��W�]�2���V�#e��PZ����3_V���e��ns+�(�Z*��]N>@-V;-߷�"�W9��
���?h��8���p�n�8uX�Q#<td}WW0�&v��ڼ���vtuM�=�~��<�t�`���X��v3�^�S.A!��SIY۹e� �wP&wշd:\��hj��P">�#-�����h��R�\)��~�wcϘ�4(������+nm�C	˴P�VTT�9�j�2�B�SR������gv�t�n(h��y\��3Hr�bu#9�P���d횜���'������+c��F	|k��f#��:{e7gwII�Q4ϧ��]z+�ߒ$~}Q~@d��3
I2�	���:��
Ba%%Q���B���ۭ����bN@��~��|
w�Ͽ�sP�π2��32�8_�-L
�tI4�RI:�5Jk~ii��\2��.��rb���}������T(Y�*?a!�<i�?��5���G�]:�Q#�?Z�L�*؋mK#+&4�Ί��(�^��υ\*���x���EJWo��B���k_y��NO��x��5�pYqC���q6I ��J��L6�i:"���Ҝ� eZ+��v���'���\�!.�y9��6����X��)��[�n���/,��uu;)�vn
���w:*�P󀮶��ou���\j�ߔ	�8�(Y�3A0(�__�ŏa����uaMڛ ��iܪ�N1��M2"��]޲Ex��?{�]��GT�"�Q��K�y�r%����n�p�f��y��}
�]&�y��	H�ط�uD��`��4!
�|��Cvv����
�
��)׃������G����Bm�f�e��n9�3�07����uB�M��m))���&�{��tvʐvp���<�	�'��>UQ���Κ�. v ����v5uw���g���&��&��x��VŲ6���'$B��Y�@�B���hk�������p/���w$���jO⾙��D;�YTY�R���C���#y<�Fw������mΝ<�=��i�.�s�X`Lf�B2y�)�L��F��d<-COE�w�UC���������B��d{��uzK�;�*�0�f�z�{�8j��a�%����։�G���9���xڡ��I��T��6�í�
��9��9���B����q�`u8,�˟ǫ��*���x�����Z�(	,��w�粇�|�L�NU|�y��3�<�%�����ᖴ�j,x��:��*�:v�q�H�%�UI��ӥ3��ek�t]��%_��ƳB���#�|�*�"ٵȫ����[��yײ��Gʰtnsew( wnn6P�OX&��E��&S�����3Tx��2��n0@�����	�S�eDG�ׇu}<��F�IdS⤉G-8lX�0м�����if/�0P�z���Zmf.����	e+.����Ӄ���G�>q��K��A6���6���;�2�˱ۣ��>��:�_�8�,ź�w�+�|��������5.)Z�d���B��D��8.�1�h�8��s|_�.ox��z#jD�b�TT>�Lk�L$�U:�=ꓞ��};�ɖ�I��x�}��fX�T��؄����x��L�lV9��U��{�l
�,��a�N�x&�9�݆�>ۥI��!�L�X��Щ>L�\|?��*˥9�$�u>�Mu���}b�*�޺6�1��L�q�>܏0����X��9_�U�_ OoKQd�6��y�3�����/m����B8oٴw/�]��XQ��d��1ϱ�~-�{�X�]	�����F��0��E�9
��p��F���%s�ON
V?��ۧx�g��"#�3�+P6����+f�"s�5Y斜�N�d���w��Db[��-c�2��T6�ݵ�+(�x۲��)	�t�����ufJ@�"���v��3g/�K�Q���-�
���KTV�
�f�]��؟�C������?v��]�*6�o�3����\�Pz�+V��ü0�5�;3<�_��]�>rC��p9��vL�.p�qM_����ߢ�.��M�=/��O����E��M}z9�
}=��>�re<��mmiq�t"篼��i�����ՠ�9��S�|�VN�L�fQCmD�%
�TW�	��_q��Wښ���E�g�-a�
v}d�myI)Ǖ3gڪ�_W��%&5����mu޺�ػ�(����C�ޟ����Ϗ�)��='?�szn�ՙ�m�#��Fˁ���ؓ��������'����v�2�E�v�nj�Z���w���(l:HC(��\�i��H��h���������|�����_���G�	���y�NT�@r�*�E�Q���W?�]S�~OINK2-����י9p� �����6��Cu��F�����#{dmow�6��%�mo�c������֬Y���:NU��]�Xt}�D�"%��SĀ�M1���]��W8))��<�ɞWT�$
�@k�U8�b%_\`(L6]˚�:�)�q�*\�����5Dgwo�z��h�hAi��8<Xqnuu�Y��硸��.�ZR˺�* ��@¥�	_εE�˜��2��dʹn�E1Φ�{��Uq��I��G��ee��v�:^�H���p��+JoN�x���Be��	E��9U�Ur+b7��u�s�2��Vד!F��rYq�\Uv�[�wY��
� iF����=�YH���x�Q9�|g�����kH�*����*s���Z��\x�|�ӳV����41u�*�Tj�Eڹ�u&��-X��Gn+�5�x�@�j���Ǒ��M��޵�.^*�����{?z%0��8ݖ��E W�����5��O}��	 e .��R�D�^O
�b�J�ʛ��h�����e�€�nw]�����i��#�������;-��p8�Ԋ&��=��:E���M!_�Sx���PU�/���{A۞ԝ�J���O�VR��{-\����e��E%5�ij?g��Ϋ�����p��a�l(q�kIm��.���=������hwVeVfr�m�U"\���[�~}fp���$��!�ti��i�FӦs����<�L㎭-JÇj��5u�K����,��(?�j��z��o��Yu����C��-�.���Wt˛M�" ���)�����w��r���;oѥ����}#�����!bv�'��ʊt�6��ǢYͽ������eT�ب����?�rR<�K�(�ZP�`/E�y�8),X�9%3��?�h�9X9�����Yˣ��MH���Ev!����Ogh)�d8}?���/���'��Ċ	E��(
��ߘZ29
��$�HA*;��ܘ�Z<����Z�Ķ��qV��C����T��+ư��{�3;ե�++*2�=���1��:�D��(ω��N�(2@������cp2���Ҥ�rS��:��剟��m��>@g{�Ҫ�T����^O�SnX.�L2���4���I��-M�Y���g��>�|��[o�</�ى5�,�f���f�6�^7E:��y�ڦ�`<��g���@��G���"���O}*�����5_rL�6�:un�]Eb��3fS�K���,,bO֦�)c�|u���W��;�O�/��<e��
Z�ci\~��~�-��϶L�SV�R�l�őh��u�#���� أ��N[����[����P�+���j���[�i�-
6��<�94a<.��}������{;
%@Q�y|)** �s��?zn"3�Dwlx!=�N�%��^���)�-MX����X��'s@�Qˢa�Tӝ e_-��5�����]Sdg�	�f檸n4WM��4u��T�4�y�{�?g�o�=�)����
�׶���Z#J�	ūM�{!���)��|�LX���^��_rA��:��dS�Y.3��$�ƭD�x��/�P-��7=��<�y�iLNY�Ƽ��PfY�YƂj\jj>3OX���
>\�Xi�ж�%��W�D�7`���&���?.X1���t�~y��A)K-.���o͑TT�F�fF�mif��:+�}���?��G�&�]���>ᗤ��~�1��6�46fv\	�T���&^ݽ��M�iﲋ4�ʊ�6͆����2��h�����rl﹟l[= �(=�@GG $eiH>~?�nS�t!1��T�>x؀𫇪�\�H5��K�x6����~mڂ�DJsb����뻰@:��~)���_�z�r^�)�T''YHD��\ޕ.�4�Ό6��q8�΅i�IEq��Y:n�v��g�)����hI�cJ)H��9 ���PG}O��+�'
�;(�iӦi���\?xS�(Bԧ��{�������0���V�~��|(qB��A�ä�1���iߓY��δ�
Ja�t<8r地n#�C����?W���oa~$v��XY�Gv�|�^���Β��emS�'hW|�3QY��9���C��(=D?�����yL$f�LXt�l���Ėb&e�eF���mC�R�gjp�L�Ʒ*\R�j�3����� ��H����{��w��X܀e��:Nri2�����[y[� ࢣT	��B��TX�u��;oZii&�"`	�O���n��2��sq������ҥp�-{6����>^������Y�k��1[��Sw�e<x����+���f� s��3�R��=v�n����}�˗/7J��g�:N�� )�98"���ғ3V�gZ�_h��B��Y	�����$��CP!cU��h|\���sժ!+���)�sی��eЍ�u��!��@���R2�{�dX��φ��Җ�
-/k
'���B_—��|h��]�����l��.�Tx�mx��}��ܑ�V�V�R��$�Kf�qn(gC��4e$��/�����|j‰��h�SV��֬������mmT��TG���qW&L������/�.�m�'�dH	%���=B,뷊fo�]'��)a53!u&�&�n�
T�h��X�e4H}���
t�t�0I�� �?�`N�!٤�mY�*�))����U2Q�5Q�U����6�X�[����@�O"��<�!�Sy�y�fɳ�sT�H��գ^���&�k���t����Z=�G�,��t��m�洑~tᄂ����Aƣ��!eoBaF�n8�S�U�6���;����g�����`K&��S 6kD���|�
��c%X�P�I������$vx�;������R2wy�q����y�r�y�=M��{���UNu�r�ӎnS��-�ql]&ٜ�T�z� 2!N�֔A�*E6�\í�d�ԸyG��2df�
�T�Λ����`��^�J�իu�7߁I�0��Y����M!���`�` VXG}�t.6Iy�#�v�
�X�%��1فŅ�
l�����X`�,�צ\�3eO��\q����6��B~�)>)|�U�=�tM�:�<ҧjc�	nʡ�PxCϤ��9�F��)q���K��|	�?Wng���(^�vT{�,0�bL�Y��e�EM]��˞ӻ�����MSU�����C���4s^>�t"�>��r,�����ǎ�1lJF�1�c=�nyp��j�
�������W�Dϲ��R/��q�Or��Gz?������P�P��D�y��A7��Y=��'4=s�;��
���D�(�)�S�3��;V�0_�J<�d��8ޝ���m
�/6��:y��P�/n|�%�L1�ida���~9QU�qUȔ�)\]H�I!T3��\J:V�_`��!J��L�A_=����g�4�j���C�l<o甼�r���6nJh$�TmVV�{̋��,��P���Fb���0�C��K��hq�'yWb'{�]X޾�-�������ܯ;�Tۛ����]QS%�;Ԙl��Ҥ�'+O�lrf�,�my9���Ppz���Ά�߭��w]7�pd��h?V�ĸn��k8���e��JC��u���ۯ�R�jL誓6[%Ic������U�e�)v�`~�WXԛ���a�k�<��M�vt9�
��i-����VO�U���ף}>^Y���7��x��+����3x ��݄��|XLO�y���%$%(N5U-s�����SC��D V�pxC��K�#�����W��+*F7{��Q7̼D:��/�}�g�g���wÚ�+�y�>��h-�T5!�ކO�V����^�p5T)"�]	���p�/w����D��Z��~.Υҿ�r1��ҡ\�齻k��<v�O��������ؿ_O�N��:�7x%~4�弔�˅S�N���ޒ���7����L}�ڈ�����I�PsLb_�c���\����{_݀^ሔ�dB�g@���Uf�Y%�u����xz��C<)��n}�_$�4��ޏ�p�%�/��e;�]x���%@����Pe�R�����7$�����Y���S#�h���-�m�5˧��z"�sQy�k�m.,
���%�*Iki՗�QL���g˲�a_�j����^,K�g�Te-0��K^���*	�����_G��-/���/���#	�\�l�݊��K
��`y䳜��a1+��y(��c!���ʔ��aC��+VTg��/������f�����*�I��5)�n�L�6�����|���>�m��XP:��Km<>?e�,�!6��/��ݿ�$�Mմ_��9��'%��]\>gi@�'��Y�K&��Z�XA��1���ȳ����y�j8�<�捽�a�
�>��帿����|�&��5�\���r�0�C�?ˮ��T���Ō�����齞��"A��Y�K�҇�]g*����Z�J��׹�^}������\���¥<%�K��p2��:m�V�ү8�����Z��JlNr�s�}-�?�Ao/c��.K5��:��KQ��p��`{h����!0ލ��.�T�+.3�>�4�(��'$`aq����P��w��7�&MO[\��L�\�S�d!
?�A;e�wV.�f�ͼ�vvT������M���(�}{�
:ѹ��D�s�R��Ȣ�ы֎�'-go��[E�|��u���̗}���UT:>�<������KÜ��L������-����~=�����^YC���k�{��{��n��'嫇64��seT17pLw䰢0ӱ�s�o}i|����Gc4T竾h��ߑ�:`#��9�)�T���gSB�І�MO�^u�UH<�E�t1���;b�
�k}yV����y�� غ0���D�2��%�{�"ʗ�ͺ�\�bt��j���b��>���M������|ŖX���SU�/���Y{��H)½R �zjg�cp�����J&���9��dzw��m~"��r�ՠ&�&�����#>�R��%�߽{�k�M���y�Ö������i�ܹ��~��IE�ܙ(ر6�c$����!���S&9a�b�dVaa��u]S��4ё�������-�j�W�'�(Ix�N	��/�ˉ�M��[
|���c
��lJ��W�hW>,�Yu��-=������]H@���ދ,����;��Wfw�Z{"�U���v���me�2W������/\���U��	x
/`�7�L�)��N�>�A�.�"v��oa�������T��G�f�0H���/#�k��ղ�w��W���L:N�퐒$+a[Y��A�n�3�u\
V37��:��� ��5,�1�^TP~
�5��(kR��BEɹQQ�{�Qx�	0�3I�cm��H@,�SB��7�ȏ��i�s
�*N�xEP�|ۺ�H���W|�Q)I�_�`�,�+���~.���wh��sG�!��¥�ٹ�-���<����pLu[Ǹ�2�5�z�ô��O�K����M�BIO��m{���oe����Ȁc�f�B
�u5�v]0������z�PF��I�����]��~�S^h�)Y�2��rTĂbn��@�r�O�j(s"��ǿ�J֗��Yx���-���.��Lz=e�$�489��ﶟ��Ă�(�2h��t������ �X��A;)�e�R�G*h-g�\�㲬�Y��7�C��玽�I�$������Ti�K&��Ot#X,}�r�I(����Z�]��:�����F��W�T�(Rx�;q޻�G�;���M�K���Rk�U*3ɀ2�њ�9S	�q�Z��U�;~���da�&���QĠ���}�m?�$
O�X�E��t�R�_���3��i���������	��V�_�t�E=�#^�z�I����!0l�D���V��Gj�Ũyx��B�A�MPX G~���oWk��Bd�ى�K��-[�e�~ng�^vQ��ew�v������{
Jy�i��]6-+�~�FED�L��s�?��ߋ6�-�𶗃w�\�ZU�[q�P���PTXy���
Y0s��^Ҙ��Œ^��Z-7T���8��+̊p�Ls]sV��s2I+�z٤P�ʚ�n��/���W���P弨�4w����Fd�ʹLçIY�y�s���l�p�Z<מ��ٳp_|4`�U[�.Be\Ew����#��PX�T�赖���_X��
�迾�()��ЗWetĚ_��X���ϴu�0�M�@�0m�$=o[��C�AoNY��S�a����@>�1W���م�/�>�0��G����RAh�����G�}=M=v����Ng�,*RE�xp�{=;% 0�W�rK�z�����[ZP5�P�a����̨�-��]��x�Z����M|@IDATU�+y����z�M+�|�O�f8��� z�ؽ����S~N�����F
Y�J,�����)�r_}n�5�W!�f���,(��er^D�kJ|$I��	b.T��y(\bq�_jG���'�y/��7�f8��}�l��v&��Uj������{�5�㞧���
�`����Yc�e��˶ݟ�)|e^@��s�WAk��++���)O��46�)��0=�%��Q��/VC��>L/B�7���RK�͜�ʳ��A�H�3�$@Wn�[�֦�7�}�*Yׯo�-�y������E"����,�]6���BϒޕҢ+�k�g�+���-M�-�bp�����\�?��2��>�G?b�
�{S�m�SU���č^��u�
��2��h�@LT�|��*q�Tdn���o�}!��	�'�W���*��'6��!�� ���J����NZ�f\B�
�ؙ�/(��|t&�"@���iP�G�Z�w%�s�f[�Xy��E��h�E�㽆�!ȸ�-�G��q��� י@���49c��(�ғI�<�ǿ�XW��-
7�8�L;NY��
@������re/[��N��CP�B&9|��,L�*l1��@�{��`T"��Å��M/�L��G��&���6c�0g����ޏ~	xq8m}2H���JE)����?4��[�:�ۛ�EqM-�C�\�M��X�?�Y�cY�Z��
q�2�cCU0���HX�_���������&�f���K%����VȥC\���^i�޹�{���A��+'tj����K��	"��,.U$P @ރ�\7�ݺj[���x&4!]��sD��Z�Z��e�n&�>
v��'$2�c����B��K'L�U(��2�	\?k��_m�Y�bC{ޖ�tIe{�ǧ\t��A�V�i�m��7�+�*��=NY�
��k[**E��F�R$�UQ� ���g;W�f�~��K�n�u�M�r:I�/�y�E�9��i����ê��ێU�n�� g���Z��H@ˑ�
Q6k�y�����Zk�µ�]2�rO�ٙ�Q*m�#�
`�7�O�bMZ�1˲7ò:��i�I@�f���ǔ 	YU3u�w��r}Cm�q�������@•x��V=�`���=S5M���d��\�/\;���z�UL���6�W�Zv��qzT�h�K�r ��mw���U�j6
dʹ��v�o(ۙk��^^^paObG\j��EV�j��/��G4�̓�/���k��}�����-��bŐ5\fąE��H�.�]�Dm����SV�b{z9�}5
}O���+�k��)g�������6�����3/f��	8�p�H�\�*��|x7����Z]���*\}p"�d�(���f��?ݽ��M����[U��fy�=v���E��d�#ϭ�W g87��xP�R/�]ڏ9�M��b�M�d��+@�ۍ6�:��6�SGO�.�:s�ic��o��F�h��R��x����V�J\rc/%�@��B���/���\�5u���3
3�^�}pd�>��N��ĺGv9�����t">4�E����J�H�2\��� �7�k<���4���٦�e�;d�
��&`w{<�*�]��<�k�~xEu��ׄp�s��j��>m�<e��"�"��
�}��~x=|~�j�0�}/�����曑��/�yM��Bi�J�� =�J�3��0\�TQ��NC�m�.������5m��R=�~�r��<��gUT�Z���U�r�Jk�JR��d���p�7f>1�����"�>W������C���p��|&`��q�~kkG?a�P���Bq����HX�)�ܵl7�d�¸�\K
��a�QG��E2�Io�;�¥��= #RB����
�'˱���e���ߟ0E�T�z
u�����TG�vU��Q���k�+=�3D�=��jPA��x�=pk��E="!�/�����(���RmP֦G`��kN��G�լ#aEQ��ҶH�r�v0�U
�RT�%a�g�_�c��lq�1���‡�RAC�4)�Z�R��=Ϊi�W���#7Ƈ�{:n�
�x	Է��)Y��+"J�a�~�P�ڊ���ΛS�_�=B����G�<��P�{r[y��hO�&��P��NK��͝:_\�?��`�v�jJ'�m�S��u6�3����|מWܵ=n(ZV>}�N~<�kT���J�[����|4
&M���ti��{��N��g�Ro�]r?{���y��Q���={5�
Ze2�Q�7��4���:�k�����]�4�*$Q�wm�v�Ү�]:m�+���2�O��N�K�D��c��u[;+**��*'i��G#b�Z`�D�B���1�K�k��%�Z\o9�g�]:v �%�0Džn��k������31up�Oc���7L����u���8��C7{�pw�d�h�
.��x������/N�,�M݇��TU��v[�wd��&p�B`��tׅ	g�O���W:q�	�Y��(䪁��s�r#7ٔ�~Ɵ1���P���	׻2�+�x8��]jඹ6m��q��q�P����}W�,�<��;tfmUIK̠����[7?�*ʪ�!M����s'�k:�?_����@:����/,��o����zk�e�U�E����ߟ���C�?
�Z�l[���1��l�!�z���;�K�~�W�#�����S:�,��7�ҶE1�Kt�-L�Ս�N&ij�3#{퉥+�� �l�n$S;�4G�<6UV�*{dh
�Y�t�1w�{����D))@������<,�C׊[$H@"��g�E�Vl������v���v#m��.�e��g��.�M��r�WWW��p�`���)%��S���x>��<��Ll[�n��ڢP��r#�5�E7͌h��#�w���ʾ�9�ky���_�
�ۗ�u4�Q�kKK�\F'ʿ://Ѿn�^*�=�xN�̋�W(p�'�{:�="�W��\I��/B]%>���.립ݡ�(��똲k�>AVQ�Vn�\r)���N��0u#b{�$�Dt;�(*�w:	n�-�x	4�5$aY \2��e�-��F��m��~[�N m@K�I����CQ��
�"
xw �P"q� '�����$��)ҋ�KEm�5�P��߫��_x��*��\'�}o"��
N�}I@ʄ�0�M��ok��{����ܔb	��Ro
��Y�Z��rx"(?x��K$��"|���=��RB|/|�����n�<�;�t�4���+�c��={�/��d�����*-�k���75���>��CZ��c��Y՛;:�K�
��&��\9b��G�T���(�f�0I�H`@r�nt��߽ʞ�bk��$��Nn@�nNXN*�u�h-�n�J���,^���
��w�26��ޅ*�V�JJ-�H;ݤ�Ꮛ���F�nȦ�����tt�=P�75�L;	�0{6�$�߮*����h�0߬/�꺃�w>����n>�*cm��Ӈ�mp�p���{}�W�>~'q*2�C�ج/���_��E��w8D@Mk'���iN�YLC{��{Zn#���'G
���F����KL���s��Xu�8��Wbٶ��A��������X5\����0D���75%W<4B�x�Ǝ�I�H�M�T}�R�>��$O�>�_o�
�����[�}f�S���I`�`[��K��9p�q�g��bK��<M�p�T��/o=�Y�?1:��b���{���=��>x0�H��9�Y��մ��=���B�Dj�C�ڊ�&M�{��Je
��إC��H	��4�6.��HΔ5k�/����|\Vٹ�v%��{D�������d)���)m<}��|y2w
�ka��m
E�k���{Oc�S#sv��=���E����o�)	켬�F`53ǖ{�I3*=������^�dSc��&�=w��8w�
����F���������&u}4���@ǻ#�CY=��Z������ϼt��HYt���=�B�,�ˑ<����W�D7 `���5����CWL��)x��ᨮk�!A�sX��mx�tٯ|�w
����Q�m����?�rZY99gĞI�&���~�8,n��s�E���,[��|���^���wJ��l��
.	��m��OQ��p�����:����d�D$A�z%Ѵ���p�9�=	j�CH�أ���c�|pn~V}��e�|�Hv}�@� VB�É!��`��'�������ɈX�� �������^I�R�aP8L�3,�#��١�seͻ5�����8D�|b������B�0.x��EB�3#��ʦH�1�c����]���o�3�Y�������4 j ��AŶ�w�t�hg<%�<
t�]At�S�L�zKj��H$��I����}��ʳ+NX|�%ʿ�s�_K�P�rJ��K�F��]:}6"�WtՈ��gL*mi��o�����#��Z����Ԧ��	.~L����o�K��\y�m�0�8��VJ�T]ou)�� �ڷ�7���@O�E�m�)*�AǢy���Т�B�@�
�&�F��HY$��_S�i��q�]����'J*g���V~�Tv�E�w���Γ�s{ܮ��kG��a�VLnuT�!`=w�i{\2�����gx�Q�3��T�ρ�.[�X|�#�?��Qܔ�T����d-�t�G��H�������}n�7�j~o�Xj�P�/55e���r�}GDxp�"���w�Tj:l�8:H1p�?�R��?=��@eN霠�}
0��s[ �E�@{#Q�U������F��W��;/���1ٝ�lj�����|tI`F���AO��հ#d�L���9�N"��O��B^�|�x�8�n��h)�%C
[\�la�s1J��:�H$g"��t�
_���׍�P��������3`{�l�=�X�z����j��:Y��K��E�}�*7�``os>�r�|�^9	4�euu|ުUǹ��'PRu���$���=qku��?�J8��p�G��=����,�A;��e���"t��=N��Q���rק0��R�U���Ay�$�5�~�˖��7�QT���
���>c�!�?3�����	�4��>.�qaqF��P�t����t�?���/s��L;�ݰ��]�p�ЎJ缄y^ȡN��i�Dn����_V��pZہ�ەu
b;��c#׼L�q����q�?�c��ͅ�F�|�J�UI{,•�/�/��p���6�/W�O�M��k�VZɟ��ZT��s�u.kzM�o”i{�^�6�s`\����N�N�B�O̸|�[.)�ߕN�?�����ھ��&��'xP�8Xe$���6�bĔ/��,f����zm",��"2�� ߁�A���4+׻�厴��v�FS���T�'�km1�`�.7ZZLä�㼞$v��]�l��}�x�\�{_�s8�:�����/��Hʂ�V�>��]��Fa/TH��+��y�!F���$��Li�v~H�r9N �D�a^=M��9�4_2m�Y�̓Ų����q��?��]��# ���Կ����JQ��=3�}A��]ж��U�I��qb��fY�j�P�@|��I��?ܟ	�c�#<d"�;?Ҧ��^���v�{>)��!\��7W���*+�nD���J�oE]�_\�	1Ley�'�qڶO%�E<u�T������H?���wC#|nﮜ2���_��g,a��BY���g
��ώ�X)�,s���@��<�2�c�}�T�*��̲��rr����(�Y��؛B�0����_��D����@Ko=�����O����8o_He����%�kf�"���,��Eԯ�V�2���xx-$q��0t�(|s٧�E
ky��%�k�Y1KW��R��zR�M���dv��ZJ��o���f\8�q����������T��\}7��Mb1��9
���\�����.���e2n�}ٳ�����i�c�Kन��o�U���0�;� Dap�-����FE�W����;�1>}j�&5
��TAd���gz���ګ��m�ɀhL�T��u�{�=���|�ܿ��C�e(�C�oH����x��uA��"$-e�)>�NE
!3��N���8�����b�$Q�v��x*,K��EW��@<��7)���f�/甖���UU{NQ�y~ E9;�H��	=�v��n�.U�vw�ި�n^4/��vF��!�#�t�{ֲo�8�yh�u&�_9�LD��Cz�_Y��c0c
��@,��3x�?��2�"��{�x�
�t����
M�~Y��B���9'�2]]!�#X�X��~�(�#>����2�S&��4L�[�ݖ��R%�l�6K�=���fX*C�eyy�i����W�E��NŲ�K@���r�EfE��T�y�v�� P���Z瘲Pv�V|��W"Tه&4�׌|}t~XC����� 0�xë��L�lG �����N���̪MQ6!�̴�5��력���~&q90�3k
Dv�tt&ހU�^=r|1{���A~�N�&�RF1��kv� _M�
PN�-��Zņ���;���Q�8׾xs�-ӹ�|��sЮVh���qx�y��r_huc�}|ཟ��K[[3����eZ���Wյ��\?]8iRf��؃H~9J5�-ɨVb¹@��8}r��U�.���[�yU�&%��;�����r��?U��%\�u���BSz ��i��f#�F�H](�!��N�!q�T�;�Yn��
$7"n�N�
��!��c�LN�2��m��/�̟�%����DN�m~z���=���`����o�Sn���{� �r!�����nI�Dz#���#��{��Fu�)���p��=`-S'*�%�b�^P�s8�]��
S���(���=��I+;ίT�����L�~����ڶ����F�a� !�VJ��ާ5�.��b���'t������s��Y��}��[pYV����z?R���L)
�tǠ�ɼ��G~�`���'Xr�Rd7n�����{d�݁��S�_�㽺�"T�|k]�ik�7c��^��I���㐷�ug����ѥ�d������(1F҈m\.�2D�ִ�H�
ÖH�k`��/`�p崱�`Vǽ9i�k�D�3��'��#�/N|i�^�g�+UX�/s���pBY=�|�tX�7�6�d�t�%ɸb+(��P$�͉���"(��Y��v��6&a��G��R���3KB��1�v�y��)z8�^�5�1��aݩY�ee�ԓD�&@��\�d�z_w��%�(o^���55I�pK`�����>�
>p�W�n�f�Ƨ�o������Z�H��'!bn[U��qr-5k�;��C"|���ۗe�%E�m��L���U]�I,����J<O=��¤R�	&#�gX�g.�]�p�k�V���!���w�[�a�*��_ڰa`kq8uܑ��s{�-�
`���0놁8���R�I��?䎤�.s I�~��,��#<7���(��4�|��)|PZ�lƷ[�ã�G|uȞ�>��V��5���[q~!Q�v���ڳ��{Y��gJb2�f�$w����=�.bCْZ����(��!6�AQ������y?L�l�	��x�8���Wc�z���ʚY�	%���vlչ�Y�8���f��������b����*
�h)�ڴ!_){�H�=�R��=�z�~�`͙*�!h8_G��B{���E��:qN��B�a/0��q8�-�u,�9qؖ��:R�O�Zw�����Y*���8�@n0��ryA�%�㲬Ӝu��Qq<R�;��E����	=���h�~�Į�s>���xN��#z���;�c��s���P��.�����p7@�
��s�Y}�����b]v�‰��#�Bϰ	�n�m�0��rl~���R���M.(.X��7��r<�3D!~�j#��װ�pw�ޗ{[�����F<��V�N��gm�8�1s.��Pi0�|TP�C*��-{���2qw1&i7E�O�zQ�H��㫁t�����@2�B��n?k��((���1�)����Ȇ6���oB�J�N�ES�]��$���,��Gn����-�SA��;�s�����U0;�ηT�н��=�'������Ӵ茕����>�.e%���j�H�z2v��-����g�"*t>��7@�-*g�p�,�SaO�;��V�)XR��^�mݗ��*PO�V�U�d_8&c���ȂsJKJ���'S�߂���pCX!@�����W���AGw�L3qF�^</}2�T��IP�K!+$��?կ�e�'';�|�u�M��==ԡ8t�=�Y�e��!	��#
֐xzM�$���G��V �C�ͺkwڜX����7#lP'�ױ��u'#~ӓ�^7��\���y^�;���q���#%|�z��g�0���l�
����t��#�Qn�+�B���~�DފM�wf,�~�)Σ���|AE�Ѭ��O�v�xf���_��b�`�{�l����19�B��B�|1 �wy�^ߔ�&|��iùκl�̸{ٲ���(�42��a6���C�_<�w3��ׅ����l�?4K������}x��-L	����q�!߳�e;Er�5�y%�	���`|��|
��e�L�P�h�O --��!D����R���p�ö��N����>��n���z�@v$�-�-�85DZO><AӍ���M���br|
�3�* fVU�\���w��6x|1��"�|M`�/!��H�g8{��`]F�u\ˎ�����@�jy�	I̪.݌��9�)�$���g�c5�yW�6p���7j���d��S�	l�>13��Tzzm�����^��ڬ����^]=��
�ܗ��97��K��,�y7�I?�X�"�Ⳝ_))�%g!���</�~L�ZbJ_=b=�nV �jx8��|�iY�Q�h޷c�E�H�����<c�v�lL�yə��2�M�-?Y-��a�U�nNd֍��m��/<lժUYR]m:r0��0Dix�?���̹x���:E�U�d�c�s���w����;�+��I*�o��v��K9���� +�]٬���׼�:�v�~M�Ԩ�a�q���+�iơPHff�3v��ú~���d���\*�ʢ�c3c͠c��O��l=c$�hd?���#E�{���O�E)j1�puf�
B�4��?����?{�wD�o��Y���F�|L�#�:g�~Md��XN㈽dp�kl�p��ё��oCJ�2�aFٚ��d�RHd��X��}k�ԗ}�s��?�jߖX�x$6���R
k,!��v�m�O�����^���AFۂS�aSK_jn6Y�'H):q���9������H5��.!+��B�m%���v�ٟ~����Lp��d���
��U&�-�#��`��Z�Ŭ���d��C~A��C�k�e�{����S8�4Tr�c1?`y�ApPJ~x�~������$x.�
p+ӎ1�2�埞�x@��Nq����j�1�q�(�M
��m�i�@�������a^�X�����6���@O�,;�
��1���Ճ˞P1�f��Z�:�uw��z�;(�'��݆4R�h3�����x�HEŠ��Y���L�e2�D����A�:����Кһ��ˀ*� ����>��$d�:Ԣ' ���8��wI1<r���Qo�A"���w�E��.�8�	������U�rQ����&�sJ�vt�Ȃu�\�A�Ws�]EE�c"ٟ�ľ�7�9Y{]�yX�yJ����@{�,�l��=�+�B�E���T!�'����NfO�sI͙��;�1�I�x�I�
���2�*�,�F��lDaƗd���P����f��|��j����k�\��M*2�M�rw�6�GȀ]d�9Y[
��(/�5C+�dG���X��<$�JRM�DHF����|�hڢ���
>�f2ܥ����LX��噂��A��p/�A��Z�PFD�����
�{�l�{�Ig7�
�{v=x�B�J��ʜg���<n����/q� B�<0�;����uuM�!SQW_ *���S���@ax�(�/��@F|*�9LҔL�'��<�5��+?||�҉���m`��t�ܙ�d�{%��)�{��[4R���E �ͳ]�%g�[�U���D��6'�[vӚ�b)��	<Sl�NGo�YL9�\�?[��.��?Y2��>C]ΐߗۢ'��=!�t"�|~����b��`�cO����zCfB�[���ʡ�wH��'�đ����坝�!�n��R�g���`�z"2�g]FOf̟�S_�~�b�_;h�Ũ�a� fa��/{:RQ��d��}�6�ߍ�����-�"��v;Yu��{����[>A%}w���EQ����-�c���{Ţ�6O%7vᤡ����C�S���1��q�'����4&П�OѤ�϶D�4�h�%6qޞSQ�������k�F��ô;�T.K�?�d/V�"�^�΢F�)�(o[�V�26�>��#?~n{`<�;�/V"}+Z�3��i�M� ���M>����|@�8ؘ��X#�3õ͛,ǝH8��G8��l:����R��g�%�0�$�V��NZU�	WuT;�3��#/x�}f�9;:�/k�\��R�[���\o�pOiP�����?nǻ��O|ʮm��&;Ǒ�����U3�H0�C�ĄyZ}}�IZ0oE�e��f�O*d��>�����l���>�u���rA�E��9�%R�xLEM-k0�trm����mݛ��|��i'�:�#�8��"��k�/>��I�?���z��X��Jm'����MpF{� �o�H���"��/���5D� �f<ϺWd���v[�/��p���(�ou'<��>��;�L��y�
I=�J�g�cJ�;4b��ImRׇ1�_�"&�ƺ9<?�������P�
�:�/7��H�I�\��_l�x�+)�{AJ�����p~Qj�b��g��@�\��D��<|��8Tt}Ϯ��H-[��a)�F�=�s���
$���k8F���Mi�~Æ
k'fQ(36���)��U��}l:�1S���b��:�
q�"5P��
)�K���ֻ��xյ��t���mX��%&'*�!����.6����}[��Sjڿ�1T�}e�1ESǏG�ϛ�7i5CE5�z���ĺ���W�Oƺ3lp�u�1��6a'�7�9X�i��ȿ7��h�Pr��a�t�m�;.����`b�K����@јϜ
�o���H�J�![V�C����P#�l�����m���3b|�)O����ڑ*&�u�]�2�(��Ī�%ط�����b��Qϧ[�f��P��G]s��W4A�o��e��X��(R�4�$��c�F�a�a$���w��Dl��/F.Hf&���лS�|�ӷi�d�@��b�#0�`V��y�|b��5/,��6��/꘤s���E��l�i�L�լ�%�s$֭�	ܒdV�."5��c��;kn��,+��];v���]E�a��?��`�8ӵn�}�Z`Ho�jF���9.g&I�ߐ���˚�4�._��>��M�-�	�4�G�RX�F��PT�(ĽB���yȥ�]��R�e�#��~�w���8���I����'���\9XK�T�t�g팺�|����w��X��HPl�ʩ�-��X�%Ĵ.A�B�&��x��U�,�9���`��Wr�o�b�s�ε9�$@�m�il�Oc>����Wb��I��0�'pգ��w�N���;�|��|Pmyϔ��>N�WK[�$��xt��.�p�dM�!�q�Y�j�G*P�rvf=aq�n۰'�~�:K9y̸�Z�s���lIJ7�8r^�"��O�r���Ll=G��);��!���ǐ_')P��@���m�T5�׶���E�0�%SYF��xL��a�[�HfY��tO�������!�^��c}e���;�
dV`7��D�D�ӻcA�M9�#�?�=p���L�1��b�ٶ]7;�Y�cք����^6��f�;'z	PF�����>���;�� �.Z�V$�R�8�T��\�o����s�X��
j�%��/�:7#��*ȻK�i�(I7ϩۛ�xp��_�$	��}�o[?���/tb:i�⑯�GM�mPL�N�F=����=����Q3펈�҈:4E�-�xq��,�ZS�k�ǯ�V�),�ȁގs�wA}�7̕���l@9X���wC2��]��,�sa�7�kb�
{˨�����c�"�����s���]��p��Bʀ���ӧ����>��O�s�=��N���t�S��9�ފ��h@�T�?�FP��߸�S��
J���3Y��涭;LF'ך��8K���N�_y�)��ݙ�]�,t����s��u�&ΦB�A�M��W�ğ�A����k��X�-�����������.�?�Sk�a� �u\�3	l]�����u�;`[���0\{QI�8z����u˒v �H���t0�����Q�/ �୉�k���w�����c1�?R#���A�1|9y���ZjEBQ%N�-����A�[5|��j�����s���Z7����	Η6~EG�bV���G��1E/_j?�e��|
��}Y��ƪ�N�2�A��<3�����rZ3��"�;ng�X�%ֳ3g���x���L
S\2��%n�mv},kC��̚�3.\�������:P�/_�
�K�*��}.�3�<8v�~�Bi�ԩ<����C�G���^���-�WWʕt{�

P��̏��bE��e�<��}Ե���b-k�1�%����N{zgOIH�K_��JR7k�ϸ[�r��i1�U���OE��4V�#�}�ke[��Ϣ�ڱ�c]��4,�D;�s�"M
�;��DWw���xR��{+��`޼���G����
�V=��mp�OA�bwO�#��/���eX�X�a�%e����D~7K����d��Xw�OϨ
���]4nze��s�tˉc���5����6������鱃��5�	���'�Md9�h�b;Ů���4��s��RY�|��-���a9��,?)ɚ\�Xޥ���$<��;�(��eH4_�H��!:~'��"sqo�)7����p���A4�s+��)��7�78�i�R���{a�˦Mk�?��e��˫�ê��q3�0�6�c�fZa�ȏ�y��~x�ɗ~���VXhNC־��H*h�p����B��V�1�F5
�k�N��[�T����ҏ�r��ek"\�x��)��Zђ)˛Sh��S�ᆫ�����3�'�`���b;4S���ѵ���"��i ���͟�?"��DKC��Z��a��W>�Gn=���u���!�۷�d�z	�KA�_B\�jֶn�m{�m;q��gBP���>Aw��B�_U��
 �����ށ�uc�Z���H"{���e���-�|?�-��=�Dd�5N�7o�M��_7��$�0��@+MAǝ�;l����3�%���5���բ�}n�`��k��4�_�Vk��゜�����b�r��۶�]29^�b�̌5'ST4���F!��k|�&��1�1�f;нYg/�@{��N�&�NJ�-�}YS�����7�v��u�7�
�1 [_y�e/��H�5=�e.�!�|_l����/rr�a�m������6��_]��7�Y~#rC]qTIp7��7���d����5�R���+���I	A�8���d3/���?slMM>u��9�+I춌ҺpsF],{d�H���)v�����b���*�=�m�D�ѳgˁ�R�N�	�	�H$�;��B�@>��e�������V<���3>�U��� �D!k�t�)�ݒL�wӥ�@�c�gX�y���V�I�Z�q$B���9V���+Lw�M!	�_o���p8Q�~��G�@���u'�~����UWBp��q$"��*����x]�Z��Po�*1�>
��6ZwZց�8���à�G(P:/c��k9�,GBbDC�&�?�71�&%�j��
9.R{��Ot�JW�*��3ʃ�u���y4�Mݺ�Æ�K�4[��� .�C_5A�-�y�^�3}���8��l�̥��RVn��2�=��b=U����0�מ�]_�G��v�L�bq�����y>�~�W����0�u�~��mEdR�Nb��5	lE{�'��-�k�
s�"0�s`�Yѝk|�r��鉥�<'O �-�T�2����ݹpa�p�З
S�Qж��}T�7��WP��?�J،�,���e!��^i; 11�ty��4XC=�x���C+�}T�n�%S�ek�aP3d�!�+�I���菓`~��I�Fo��y
��
�!��p�Tj�D�.�~�5�r,��Iس�U�ڀ>��3r�聉gI5Rl^���Sj���C3e �@���®�ѕo�Q�]x��(�\��ȩ�X?K(�0P:�0�/�c_�_S��
9�G�`�أ�N8�*��צgMr�ƥ�MN���-�M'%
#�^*T0��P�ѶEz5^����bͿ�
*������Dp�
�zDO�c�G� -���&v�hi�a&	�ӽ���Q��N�*�+��%53��2�q윓��`��J`~Q���I�~��p}�����m��y5�Ɵ�W�䣒b�p�'���s��A�i��f�8����A��	f��_��5k�vލk�F4*<�^����vF��2���w���z8K�m4�B��g�z
���rY3��^>pM��B'^�[�d|H�Vʱ���jF��\_o?x�N�{ݍ�^�Ǵ/��s/��7�N*L�
T�8�yB�:��G�4�(`�i�>�c0��~O����[��X69��n���|[�g_��ȫ�i��ɍ-v�]�ͳ@K���~�����6�LBSG��N)�7*��vM�m��e��d��9=�:���Y-)���v���~$��u�5J�E��I�cτ�yk���|��ҥv��Lj���]+rlo�"�$��y��0�F޵��kǪU��>��
�ϣ\de�s�ɻ�3�<d�	H|��1�k��e1�,E��;����5]�!:m9��o���G��r?�)b㲽�H�֖����$�!�d�e�z��@��u�_��v[�������_EW�|�� ��2ojY_a�.+�+����ˣ�4���Q(7����y��qM�^2YH�wT�P�R9z��y_e�E�Px#NS �o�i]ƶgd����9;��"Ǫ���帷@kw94�4'��Zֶ��hl�,r<Cveu�p\%�m��2ol;�����K!��@o<uXap-���h�H�@ss͆�GCl��-�{V7��͍G��.뗚�f�Q	�^��c��S�G}��U{�����y��4>ߏa�|�����e"WŌ)�*�x�v�㙂��ܢ5��3+5���7����Y��Q
�]^;��}���4NܨY��m���=[6�����4= �C�K�(��!�̽O�������Ө�4E�A�M�
��ED�Q˚���yE������9&URW����2�n�N\�����7�P�#��0�������%��kF	�5�ˍ�84Y.GW7m�
:_�oC�O�g��3�d���oS��a)HL7�PG����M�;��غ��V0�;$����Z�XRF�8�!���ђ헣�Q�ο:B4��-H���j�3+��[��0|��m'%�G}�Ec�KF���q�H��p:c�V��Xƹ��4���c���BC**o����z0�l�ȶl�
h�#�,����2�Br��e�i�7lP�w�$r&�}�tJ�M�a}O`��0��]u�0
wCP-c9�FA��ƶ�]⎜�X�ߑ��bì�3��X�9��Ԉ#�k�
O��`m��KS=oq/o�]�����QsO�ū�K�3ٔ�����޿�%�KE���"���e5�U��lz�w@IDAT^ag��}��(X�Z�Ȅ��%�]�=��h�1����&�Ǵ�2��F��)�u�v�Ҹ9����$�N�)��˲O�]g]��L��?����<]�,��v-�������E���i��[o<֞�1l7����L�)�:�ٯC�@�΄����.C�^l(�f�P���X�}5QP�|N�П��8쮻�ijIu��E��wl��D�C9~�6��3���������$��fS&�JaR��޳u���t�`���J�M��/�u8w5LQ\A��pT�[�Iu^���mi�$	���,��w���h�빫 �
����=m-��+�l��O=~畦ŋs[Y��Z�����}4b��,�+
/
a=\Qr�o
	VHL0��hC���O�HG�
6/I�%��4����7`���
�y(-t.��.����}t<v�׺��u6����0hv�J�v���_�in=%Κ^��'Ŏcy�.�R�
l��6܉$����3xx@!�����Ș�G�����w�vwGc�od��'D��G׌=ֈ��K�塣�������Xj@&�ݐ5m��Qg6-�9�L���l7:�/ D�sJ��g�����؞R��k���R��d9�x"u�'_2�類���M�Q�����z;���r�|�?f����e�{�%R����&���u�^ϵ$�앮a&�:�2g9��>���b���B��q�	�Fr<)�&g�c���T���]S��!N`�{tu�²BW�M���>�F3^Iz$N2�
�?�*n��.%�g�:I�	���Z|���j��X��\��@=����
U#�A��& 3�#x`5�ٕ��v�˰� �͚w�
a�k+�"�8�!hߧ�b�1��/�2?�ə����g�����w���Bm���Y'Mܘ H!�3�0[[�'^y��-0%�#��l �z�J[��F��m/��r�����]��=*'h��.
x���GM6
Ç{j&/��l��f���'x%HR�@-���||	��^Y�?H��zۓ0܄��F�!��@�r"�#UK�ѶQ$�i���������9~d{wo���6�߅S�>�s�G�$��{Ko�<�@�<Á�{U$�w1��ٟ�c�0o����|���)�]�L���*�?K��?�z���Nat�#�&�wʮ�?��Kttx�#F�M���9�v�
j�rahY<v)��Ͽ���c]s�����0/�!(��%�aΰ\{��񘃵KS)�
$k��9N�i�ۋ���Bj���.k�P\��8lV�Q��(�<گ\z����؛���&4�D�����#*и��1�`�P��	U�M�>���Jz����	���mN�v;AlaM���t�R-Q�Ϻ;��[�ʹ==�Cf�|y[;:@�Ì���m��v|L�-��H�ۓ���b��9��I�6]'i���3V��2�-F`Z���E�m�ӆ��ў�YH�vꑖX���}��,^�儊'3�ѥFw�6`v�u�A�e���ٟ�6i�=�.4��_#��
w,�H��4g-r��g�.�4'B���~���JCU��2ןTpB .��s�M�@�g��x�d�c�lǽJZ�r�Q�ç{���^�J7z�����=E
5%��ϑ{T�%����O��dx���K�3k�;��_8a�3�5�6���:�%e�}-�(�p�o�bh1T�
�F6p�xe���^9�mHpH5몙'���r9 ]"�iP��/'�šgT��H"4,�x�w�X�{�Y�u4�\[�V/��&]�6�����}�l
nY�'L��20w-���[��I7��zbS퍷-��5�K;r�҈�]�'�ӷ�c&�C��0�]3a?��A�u���C�;
t]�I�mvTa���Rf� ��9	f�a(97v��[-'��}߾�~1TYt,Ǒ���(�g�M��i1N�.����/<Hv
�)����W��1��C�Z��/&�|pyW|�ʣ��O!h��!�Ի.��h�v��"���u��oI�����F������(��Ӹl(]�aӃ��mf�fl� M=n�hoX�>����'�-�ȬvcG*�WHʠg�SY�q��p���Y��Q9Fg�4��-��N�F��1t��;�g�VX�m ,ڽ~eǚ��Nk%�?3�7�[
ޛ�A�hx�!�GV���+L;ҹ5��()��w���$!%�b0Yؕл�	�6�d���I�<f:?י�݉T���'{Z_
��Ox!p���ZQ��m�|�$l��
��|	Z�xE'b�i��:4�@���ض��#UW
�ӿ6tr/���5r����Y�l�g�@��}(�ڶ�򼮲�����b7����p�n�Pk��y�K�iͫؒN�7D7uʈ1�-��
����5�#��36{��n)���0gĮ�{a�ݽT��5w�%E�cS�O�����r��>ﵮ����W�Tz�o�K�N��w�9�1~�V�ڪ�.�Q��E���1P�b�c�ѤY��0�k����u����e}Q�^����'q„a=jOO
\�;����ط�v�Ql�^��[�䗴������9�D���˅�þ$)̥;�g-��W7�������������hpt��ư닄J}� �2�Du�=e�fJ�.�-T���<�~컲^(���d��h�"{FIֱ~�v�2b���u��޻��PR��,^)��eM/=8БT#�'h%���S>m�ȩ���������`HG��zf�a�Ұ��w?���/�^�|Y*��ʕ������vء���j��p�4�^��Ѽ���H�"��ߎ.a�ƪ�K�="J;������������&���A9!�t+�q��ƽ4w{ࠇ�?kjj�3������~�J�	L���ӄ+����g�Y�%�٨��R��c*�)�4ŞҺS�O�����{g��$ۙ�,����l{���W�9iq<w	���Vô
��o�X�)�v�
6��	zd���ƪ6w�e[=�x���=�+!w�X�rG +��+�+�MCXn�W<�E/�"E;(��	���5Z�k�f:��>�s�"𩖂�ʶ0YL�Q7j�I��+2/���Ę���rϤ�Ķ~��N����4�c&������1r��������
��o�n��\e��q�1}	�� �.���H�,������x�f�/���=�k�.��$�lZS�tk{|�n!q�Ớ�s�m,�؀��HHxE�GJP���^���B z���s�
NӐ�8��e�
��Y�z,�YH�v��a��Le�`ċ�D2��S2k�׍{dkK��;�%wm�-���b�?�^�?غ�$L�.���m�o��*Ϳ�<d—&.����k�5>��%ߕ�B+�ٞ�#����nLfO�
�\XVR����6��D,6��ϸ�H�B�$%�a~	u�X#��e9�[W���1%��N�8�5�i�l��5a�2��U��1sO�ϝ/�2f���=<���d��"j���Rc�%,��d&��i���;n�M�x3iO���ȵ�XA���{��~B7cw:��4��,F���o�{���P+~����	�W͙�`�J�'�J=�G�����I�)�<��H5#2@��-��7a�b;�NM�X��*��#78�P̔c��jjB�RTGy��<r7�g8����[:�rx%�~5P�5Ͷ��&T57S
ڜ�`�����<R=��p���-�Bȥ��ۉs'1ͥ���k
�+�ڰ�ȣ���Z��q�U�Ę���=�fZ��I(�e�oo�V�n8��>^qE����x[�{?�����+P~"1�%e��9{q�*��[��Ce��-�+�ȇ�����HP��JYqfY����@.#<�����j߱�?o���K#��9�&�N<�`�#"�u��̙9x���^Xڬ�@⎀XRЮ�[.w������+o,�d�02O�K������I�?��K��yY�.i��l�׃����!V��K�k���p�{Ȅ/m�4����ロ�V��J8r��5[A�<��cy�jWwO��cB�A,��T"1ҙ��e���[8
�s&�A7�<w��:;xm*P--q�̤������a8v˒�P�5"���˞f�Tg��+k�d�u�'����W���P?�����¢��.\�{���iɞ�ɾQ�g�rŵ�Wv��Ц���N�@�90�C��'�3h�?�h,/�x����iiz�a�s�{(��1B:�Tٶ(:�Ȼ^��U@z=VpѰů#�H�$��/��G ���f�=L��i¶:c�~N ;#�3�b\�L��3)w��d��6�d�w�}Vm���|����lw��DquU��d2���"�� 7��(5N>�:�#n���1D�*�/,^btFev �IZ	�1WQ6�֚N$��ǖ՝�
X���S��w8w"���X:,�AǴ^XT�>@8R@�=��>���v,�iRÁ�Y|�a�F#Ⱥ���?��=r�p쉵?���.���}F��$���F�3�WS��՟k�\Յ�r�8��Lx�K�8�����
�SM$�t�z�6�7���s�c"MM�GL"Y�����*�8R�v��yx��'���>1(q_F?)e�������@�v�o����9�dΐ�嵮^�rSj��C`�T۪���,�.�ϔ��Ą����h��wQ�e�1�L2�����})a��b?�r�we��B�wA*hEW�jW�c
��z(uX��=�r��e�_���}4ϒ��i���A�N��ӧ��k�nV�j/�<�4�~_������4�`1���"����d' 3�T�N.�cI&�G ��(��KIY^���Յ�:�<�u:�9�!]0�n��qNCs�f��o���>��lo0J�[!,@2���?��M��؎��;=��?�Բ�}���[�)��K��R���4��|+Lf*Q7̮/�{o-2�T%$���:|L5��O�&'��ƐG�'�k�����E���c0�����J���-��4���ǃפ9�7a�Є-K�3��dx[ܛ�X���#T�4��?�=�h>e�[=����|o��f\�\�X�NZ��'r���9.o�)2�i3����u��]O�dГ�����]��>�?5�Ѡ��&��oG���D��J<@�_�3���`�sx����L���8��X��a��B
�-D�3}a�g���n?��dkl�!8/(��L��	]��[X��K�XW՛�FH"�YL�G��:��{:�f֌�@u�1��-�V�9�<�C*|_�;�Ȥ�4��g#�i�P�����L�lss�/*9�u���\�X�&Q��Q��?Y��b�������0�|��J2�~६�Kρ��
�H��Ν���(��7�Ifgښi��#�Q^s��x�o�BhL��I�D��])4;�t�d[z��2_���Q�E���ɗ!Jz�\p��g�č����w&���R2 D���<��~��1�1d�M���F<����������I�m��$4�@�k���q���*/w��;Ž���p0���Є�92X�H���9-�t�R�<���j�>�S-b<G�q���j�hjw7�LV�H\0�U���"�ZZ?���V把���>1\T�DƤ�}7B8F��D��d;-2n�:&�PH`���ЉG#�xE��)��ҟ�(����#ـ�p�"�6�	X7g�]ݛ)�:�4t�r�L4����2��E�� �1ٹ��'����I}i����&��0u4m�T��f;˼v�U7gN*�^[��	�n9�J�FO�x��zgU���q�1B?r|d�w;0'�U�w�nS�\G̼-�xew���KoDN� j��ZA�u�j�������Z��� �V�d�S�k��4�ՒJ��������H|����zR|3��]J<����
�n��d��f�BD�=9��A����<��Վ�L�g�Mg}�%�����Q��hRio�}�W�%s�o(�x��籅v����?M*�	�\�`&@n䶌��`��/�tԽ�K��-"���38>\�w��gGʲ�ߕ�a.���W�����[��l�N�?N�w6���;D�Z�ݗ��9��9\��Ь/�-Ջ
�œnq���]+�;�m�F�1����N�x�t�ae�`���C���>6�I����"lq}�7�Y��ֱ��I��qh	���:��I[Q/5M�a>T��6\�;46���3��\���[A#
��?
�F%>���F���{�e�$�ZhWOH3B�
�f`�G�D�n	،a�T�8דm���{������x"�'ã�!B{,�큝��N+�u��/R�6+�2ل�-�=�JK���y�=�����O���}�t���_#`j���L��1���t��ŷ��j8�YG�&I�/S.>���#�c��ؙ/��ooK
7����91ͽ@���ht^��M��랉��68�ˏ*�?���p8��}�35��sA�*4�]���"Bq��nLdE���vWbZ-��l��PT�Cmt�k?�N�KZ-f��ɘ��P�"0]�"��&�\�=��v��,�t�qe�W�'�474�8�E�C��l���JGx�dW��y�w���7�$oG����E�?�j��v�����Y�N�p0Um�3.�d�8ҝ����͸۟ٳ��qG=[�9���gy�b�9�%@%0��P6�l
��pu8���ņ}������!��(��C�1#�%t#�,a
l*��3��0I�bE^����؉~����܂��?h��}�D��w���fj/?��Gj�+F��f1�/�IĜ��ĵ��^~�?�(t�o}�xVb��:�~̎�A��D�l$�n�n��t%��AHC��J-B2�y�C�
�*�^9��2�,��E�&��P-+�w0\7!
�� x�Bg���eaɷ��|�;��;���s9�h��[�<����+w�����+"kM�\�f����>�{�}�S�,�|���O@;ج�`\ՀɁ^�~8�/�]�)�V�-�r���U�
���L��1�ŲS@���a�+�;�lJ
KW:�r�jȣz���>���~�-_W<^u�e�׍���a��n�L�#>&�o��Kg��0e0�E�+�Y�}��x�C��.���{�[���z�J�q�V�g��;'��g��E^��5�ɇA�=3`��%�[D�?�Em����}�Q���"��{������ �uǟ�a6�M{��-����q`f�� pg#�D�Z�g�D50[`	�C@��`y�FCDw�j�b��$��О9D�1h�$:��J.j�|�;
z�l*e{��ew�;�B�?J����}�eh�$vh���^�:@/�7����g�?���<�8]��bb��e��6�3��A�X���'���t��j�q8�/��
�6�6����Gv��ԝ�K��AmM4��dS޾�ot&W�_"H�6��R���Q	�bQ�2+������CЀ��M@g��vlp��9/W�6|�1�o��{`q
���pQH��lq����;uU^���{�{W������v)r���rFo<�(�~�d��<邫�d��e�{k��M��Sj�%���h
�is`�ڢ;Ո�؟:�� >�zT�w�z+ᛃ.
��!�Ɏ-�Y6���;���l�k�z�HiDҦ���wYa#<1E��3֮m"

9�K;|Μ9�=�!���;pB��;@+�V=��E�%xF2\\�����e�X �p���������j��������~�4�_�ַ��������o I�v��zs��<� ����[ly]�@��H{�9�^��'@t�|R�������N��@0�uC��ʚKf��&�!2���l�6����ԗr�ٲ�<�h_�g��ZI�
Q�0v�Y�i8`7v�eˠO�
���l��d[����U�e����5���JME�Oc���֊�힢�D�i�S��ލ�iV����P�7�'�M�	���A�i!�A�%:�a�������e��l�<�gY3�����T��S^9�8��$���S���i����.퇖�4�q��~7a1GS�ۀս�9����9
��z���9�-�'y|@=C �HFeoƩ,�s�A�!��D����zg�=�ȇO��xg��Ԏ���\��<��RWwвD�{n��na�eh��巭���S,���?��٠d)��"�a�;i�v�"�9fx.�^⯁9���ÿ�;գFr@�X`:���������T��Y��M)ꓠ�U�,+�XWC�~B�aYS"ܲ�e���a���A���Π��㮸�g��+�����~2����F�2�Tg��b駡�L�8O{�'���~l�VGɝ>.Ӫ�L��:�6��Q�wW,�A'5�1̝�x
&m�����b�I��2�f�=�76�nc��^o2��X�4����G1��Z�i��r@p��ƲĐ����6��U�M˨�$e���w��#Lu��*fa����z�@��LZ�*m[I���L>
�����C�Bv
��;��F�4�>�ձ{��T~Ch=K�P�x�eG�|QL�ipv@�£�9��|D�ʡ�Uֶ56�MK���E_��%뜑
�ᰥ�.�����ڢފ=�ͪ`N`Y�I�׊����X
�w1� �ԅڹ���r�,@�xnWS�ic�[@^d����;)��OO=�d�����+�Ə�uESėV-�u|�?�b���go/[��٬~G!�IO����7pYЃ�Ƥ��sf1;�]i("�/n=�ǡ�����G�
%��ˮH���\�</8��F��}�lz�3�F�ձWT�r�d�<��fX1��ld�g���OM_ؕ>���e�����P��au��P�h�<��1���wyvm�ɗO�����������1�4:M��'�1J��,þ��_������޻�-�hn����^��~�``S%� _6 oI�M%�f�����r�"p�4��Ov��G%�70 j謇6;	᥿u�O
#|ggT�Z|��6g��'�<�m��n�jF��x��cj͆�t�
l���I��FlϹE�6���B	еl�L=�cCwN*���e��VZ#D��pҁ�W�Q����� �^��;M�>
�č䝑��������(�Ҏ�5�~�׻�&�u.D� �]�_�v�d�%h��D�`π�vk�8�a�!83�dߕ%�!�,_�.���B��F�"�R��N���qC'N��;	
�i��@2�E�����{�Ac�خe^
d�`�_�;-Yk����)^.��E'��ږ�Z@�
X�tq�g�K�쪪t��ϝ窺5�R����LB @B�`A1QDEA@Eh����m�l�n��Eā�" aH�2O�2U�*5ߺC������-*��}�I|�s��3��9k��ֿ���s���(2�މ�0�&5�Jx=���F��?	w"��k��r�����]��/��9�8�[D�~���O�<��9F��㐼v�	�E>d{I7�n,��DVT��pL+}~\��;����`�-u�]�TΝ��{��i�|�ŀ2�,��6 vNp��ɵ��וi89$��ʢ#�i��Ș���H�&h_���Z�u�k1�
 ���˟`X�_T�P��¯���Xt/\Xz��Ù��cT
8��R+�Ru�V��5��,ë�ͳV�x�����
��;0yA$���.PC�.�n�ۄD�b|VQ�"�F�����uN�u`^A��e5����i���8���HfXM؂R�
r�}���/;�A
�'�T{9qb�C���z"�eu6�cQ�k�w;�b��_�i��D_�`?�Z�20�C��kO�7��)_��<d��������FjJ>�hZ'<�)@��n?���x�È[\�:�Lƞ���W��x��뛤����%��U+����u5[��M��଱��
���#�ŤF�@�	sG�
<��б�twwK�9r��HG�m��3��Ő#x�V���mx3�P���<Յk��\�բ�>Q&77���셮.kb�š^�w��?�[+d޼�v|��_�F��͘6�k==�7������%]A���r����iʄg�j^
�	�`��gN�e���ɍV
JF�O��2��ɿ���v�+3›%K����&��c���ڎ��^]�
�*I�\�V2U6�h�^�.:�^TI�3lQ��2��@\��y�~�k�]qE4Y*�;I�e�?��F�%���]`�=��AP�|Yuav��6�*2�S{���_��SCi��!��s,`{u��?p~x��Z�9?'HN`�QB��`܎@]N���t)�VB���¢�����9º����Ե|��?�����s��lh�۱�׶y.M�3�����߯?A֓�9��a��ᥪ�kѢ��<4[C�JBx�m{��e��Zj�}��dZ�"s���~��� Tu` �C���N�nnk;�K��9;��hj%�MAO�y�G��^��>+�g̞?��E�ۼ�2�[��4��v1�.)'�Ǥ�&+��g_��	皳�����m��a�'�׈��>	[�%h6i>s!���,�o�q1����ZbiU��wӡ��>��4&��$_�Zl�%\�խ���G���C�@�H(�rZ�5�L�`d��7'��|���dνO1��S���7�tM]�ݤ��lt�j��jO.��-���s�[|)���2���b��2Qآ�ew�z�wڍ�p�q�*P
�|�~J�-���S�]��2�����S�S��g�[�m���TR486��mԫ��(9���n�Kd�8�eg;q���K������hn��Dg��O)�������=�HhK.��Ʋ���"YF����7=�h��]�oV4�U/�	�
 ��a 
`��V2䕸�|3l���Vt�]>d�I���T�����
�[j&�J��ms����!�
���	�n8~yqYBX�u'��o
�Ng��wl�ri&��EN�}}b��ʉ����L��غ���d�_���$Y�����A�wf��@��E�D�͸S2�!��O2�~`S��ބ2�
�,�V�܈��Qq3�T׿�2t�?�W�g2�A�To�l8��ؑ�ۺ�Dj�GrE��*�=*�����H�z�/`_~K�j���s��j�uR|���*H5��"q��P�b�%��3@ڧ �1�-���"ʃT�&�ܟ�]x����z����=�����"����Қ/��{l�9��ii�ώ��h|+��~j�q��Ei�-/��ܘȻ`����6������d�|P��-��1̀J�أ���k'1ȣk'[,����������0*7j"��*�PfY��Q�q���W<��,p�5��S�xWxd��RK@��r��w��b߭�RA#ap����aZ,Z䁙nRM$>_�#����q3�b�c��z����c��Zk( {@Y��1l�2�6¾��S��\s6��L��t�!�3�;�'�U��%b��1�Ŏ���V˰p�;�ϣ"��I5 !��$UE�e���M��+Z��#���	��Y;�;��<}0�pn	�Nx��M��5�{��T[�
�-���V6_S�ެ�~����%���e{|�� �����C*�<1T��4�f߈J'��K��b*C$��o�	K�K�6���;G�=D-�eEn�6� �>A�vl4;a�ֽ���7���Ɔ�r��n���G��*r��AG5bs�)�䦿��{� �j�X�6����}�?E��O"n?�)�����yL��-��D���k*��@i�-��=����,-˖!>'���ag ���[��m�Ҙ�兾(��w�� <2���p�N9��l�j�c_�_3�־����*��?��[]:Q�?|l�d�F���^̲&I�\��m1nX�#P��n1�S����!F�����%��Ԑ��9$P����$��$�Ǧ��i.-�m�'�kt��4x�)*W�Y{�n�t�n�"4q�=�H��;�o�EA�X�Z��L~Gu���N׮jv��7?vqW��j�d����E�
m8+@�h�49�3�и'E���L"y��S=3@[�Q��<~�_�a���u#4���%Y$���x|�n����A��ݿ��I/��m'|�y��B�#�!�|�m<�F�u�v�4I�˻�͕��e,�����
��i,��܇w;vJ�`�I�8��_f4�fp��!�x̳��oG4�tA1���7�9<�ܓ������Z=��3X�㖃�q�/^���ǣ�"�"j;�^��	�����|�Ќ�3X(����ж����O��������[l��w	{}����h¸���8�.C�,@�-�jL�W���!��w�����w@�ڪ2�t��S�Ez�]�<��v��A��ث��LY1J���LX�B��i8����:�DH��6���o�M؝�y<.4-�hemL�����,�lM�V.������_fI
L�ްC�#�te@?<c�b"@k�d6o�wʵb�����#i��<A3�dNUKc�3��#r�"�I��x�!9Q�N��%3�� �\���i|�P<�ł�S�.�ןb��W.ܭ��P4�So��v���%�01J~�W��Z�3ϣ�
�Z
�55U=获C1����j���j�<-?/�$IA+K�7m�vd�P���M��8Vf��fC�o?Y2����SE0�o�u�:�^�����^8�H�$k��������ippl��ב�fu}�.:�ݩ�/���:P
�]cW�tA�/d��6��Cn���Z�n���f|=��1�+~I�L�Lhm]���ӉzR�\�)���PL9����O�B� �6��d�9�a
ѱ���2�ݶ��n���±N2��c��y����f�'���|;��i�qu������55�4Q�L{3�!�$��W��&-?�J�6 :̰����;�"�l�3�\����iľ�}��A�>�>X;.@:c�U;�w��kf����u'=h�$B4�V`7�J�2�����\�c��*��։��
ILTxc'ˬ���"��՜�z��|-��DB�Ua�_�
ҳ�'y����S\+������F�S'��iX����FAt���H�)�kj��H���N�
�.^P?���W����M�O+ߥe�fj� ����a��	���E�t�DP��y�z�28�1@�-���x�@���^fD/��L��Ma��{��y(��]'�l��@��,��k�d��9z�W-~s��s��>���#�D����{��q���
�9>��w��R�I�9�P�>gq���}��qq�]������\���;�_q�r�������'�W��_�3A�b���9J�����Z9G�!f�L˸��dƙ�@�X�}�B�"g-Y(��g c4w�*����%♸�������  ��v����^�d�@��R?Z����������'�ΰ�^+��d4��<CY0�K��cly���*��`��+�	O�i܀��gyηnt�ͽ�j 6�@ت��ΗʄD��|��m-�kg�zIa�{NW��=o��?���;��%��L��Q���$h�V�"_���[���s���7��[˳�wR�2�>��^B���>�7��yδXQ����<�˴�{����(bހ�����s��� �+0!��-Ɵ/�py��]�8�O#n,� v�L�D��Mzq��7�d{K4ۖ􌊐џ},N>��E{�S���ާVϟ1 ���B�vL��ϡ�A��u�/��Cq�Ć�Ty3�C^4�w�h�5��2�M��L�<�����P]���I���sz	�Bp�� 7��I_^4?
ۀD�&�+dPT����oq���5�J׃�~2X�m�A�{��:��&��-�(O�1��
�x���Qd� Gi��|��}�Q��r����e+g"�i9W�[���_����.U��?����+����ns"V��K�N�@g��oLEwb���q@�'�<�Զ���~�f��1�I0�XP���]]e���!BnOI���f��}dӦr�AB҉�Hh���a�~����(V���?���K���޻7��t�@y�G���g%��}�g,: �$I���Ď?�0G琉�ɮDi|�3콦%T�*Z1s�4Bj^�K�
^�w��!�ch�xl�nW[�l��8Ay��Wd���n�w�2wcd��{�>zp�ǽ�-�5%�O�E�Y�Z$��z	���E�}93z�*Xx�ܵ�ѩ!�o�I�+�&�ٯ��!<ǻӞ��k�Hj'��>_�F�-�ӴR2R��Pc��͙�mc&�aH�u���	z@�B�U�-��٘"�Lkk�E��C��A�I1M��Zj�`�;dQ��]�^��ƛ��*kj����gY��	��m��FŰU��k�h-� 1�$�1�w\P7����0KU��!��4I4�`q���.���r�܍��\�J��E�4G�̴��Q��y+��[�����@�7PF�*���&1��,ю���uFմT'OZ(pM����L�^(����t3(u�-���=`�l���[ʞ#��ԓ\&s<�>T���4S><πlC�6�����}��p�0*��_�.�����~��G�C\ޭ��7�	:�sHؕ`�������LNZ�dT�x�Q�k~���N�:�y�A��O�-Oo;�<
�4�^�!���b��K_���jȽ@o��ʉ���{��ݢ�H�oU��Z�S�M�t�o��YH;��ʕ����~����}�~AxO&b7�[u'=��s��~o{@0�]�[7�q.�WG��G��S��>������������\T#�L_&S�n�_z�O�͕C]g�{�C}:����|���U$��u�|�i�`e��&W�f��SOz.�TݸQ^*�Z֗1���en1��BN���tJ��:$�P0qn�p�'ݗ�zW��&���)��yg5�X�ư���@�g�%<?���{ⶕ�#��=���ۣɁ{�|-�$�V��)��G㣇�mو���i��NLYw��v�'�]b>>�{��r��rlڞ���Uz�N`{��?��T �k�N^\ќ�~�V�/O��
��\ �5>%�۔�f=ڀ�6<g���H0�Ԥ�?,����^͂fG�D�Xh�t�G؁��lp�D�i�,��IRu�~���ӟ�ִ�S.�>�yb��>ج �韙��s��X��2�������<����+��غ5/ph6^<�s�ʑnwA��sF���'ʮ��,	�uGA�gq+p8$3�}X�8qmt���^�t���jU9az�������V��T4��_�Eb8�:��O�#ވ�[#��#I�+��8!��"�9�6��;K�u5��s����80���?�H�Z��u�rՊ�P������,oM����U$��+:����/��Y*�Ҁ[���<�C��
`�I@<��c�M|ފ���>T6t�珥�ia����r����8�4�G\�޷�D��V'3��qH-!�զ��K����:��6G����G`Я��Ũ���9�@�Д�~����D��J���il>A�M���2���f!]U�����@U~�x�߻
E�I�V����S�1@�P͐����ر�Ҹw%�< )b ��m�f���x,�����vP&"ID6��mK]v�(�Fx�jU��!l�W&o�A`�u�m��BT2��4�
���3���W�����
VL�k�uK��LNe2�����.����mz��>1o��.{��-3A7�)L�J�����{�5�3BM�$F���G_¶�1*I-fZnĴ]t���ml<�@�{��)η�d�����Y�s�uH濨V�@IDAT]�nP֜ȡ��v�b�w�&�x^^��gO�|�fBj���P	�J�ףCG�(y�RP�[Z(����`8�,�XL�5���L�4�0S���w�K<��Z��ǖګ��s���ͩ�4�%xn�,��^�B�99��wm|�R�u�Ss�i͜5���Czjj�!��ש!��^�+���|��I� ��O
:�0�
Y� �i?���?��U857��j?p!�/f��h<�N�'�D��l�)��`�n{$iv.�z��eI!(˧-�<����V��+�j|��`8�7����P�!�`�.���{��rC{~������k�},�I
����M�G�+���H��7Bn��d�|ԁ�e�(���w��Pb��������a��[Y����rSSEMA"s*�
�(q${�ܹ�"݋D�4xϋ�������h��?���M==��xS��mo��!�}��cV�t�,��Y�,�/Öt�Z\M\㍤׷c0�n�2�J%E�Զ�|�p%lf��}X
�ӵВ��y��f��fUx7�D��|L�b��8����꩘�;,c��}(�ʞ����;���i{7f��Ѷ���c�颃��f���PGM��W0�B�mL��H�3����8gӦ���ۛ����I`�!���?69���ϛ��8���i&sa�d��L�x�C%��d���+��á�2 �O"�q��a���.R'�[޵�-������$��3E�eE�)�R;� `ُJ�][w��]��>���^��@�(I����Hf�D�YC�MW'�Z�rZʝF������k?�u��=.�^O,�j��T>��D���j9�	s��03;�ݍΟ�R�iȼ�"�_{��2L[D;�X�bF�l�q��G[�v�黻�}IgD�CO��g���^�6�[�-�~����uT��l`p����zb�i�WU��0[����o������|)lW�ʜM�%���V�,Ԡ$�	4��c���,�����Y�g�(��L`�}�i���[�qz���������WA-c
e�!��`r"��;;���e���dLmN��v~��S�Aq�:bRd9o�W�p�)��WT��P��it�<�Y��~���=pME��%�f�D��O
�`��[����3�֠dc�]��Ǭ��;���-���/�d�m?��M�:���7�52�c�!��<(έYٸ(��H!�I����u5 ��꯰�Ɨv���$�^��C������a۷���%����{ṭs����9���G賊w���>�I͞�u����+��2�Ùp�����Ѡ�vu��*c0��Hi��M���;TU㟢Q��h�I^����K:B��<譧CR�nL�5T�vA�q��L���(�]�M�I(_[��B�~���y,5bw\�v���)����N��R��<����T�5۹�
�!�怠��,i`Y���b����ՉJ�F����f,�	�t�X{�jvZ����%��5����x�П��%�x�TT�%D0��R�,p)�X�N�a��nn�:�3�6�R,�m��r'r�5�.B�f%�'Z�(�#�'���HO���V^�PAƻC�9�*oص蜱�\�)�[K�hOG���
N�dp�m��[�:�oK^y�����ד�k:R^��WvZ\YWG����ٓN#�F��>�Y�ނ��[�R�5Q��X�]\����2��KsҖ8
�lw����-e|$KqШ�0+j��1n{���^e�ۘ��C�l?�w1ēܨ[�qoWa�55�P�n���L��d���uff/������3��j�1^�y�a
:���!�y}*a

k�$~��%��AÏ��S�	���g 9ů��KSX*!�<�3�Jߵ�F�X~'4��Ը.��ﹱ��f���cos� h8�!
�����[yB�꽜���~�fj�����%K�����j�߳b��d�v�%|0��-�$��'(�~�쳩�e0��Һ�iթ�'B��,�*��NSS�m}ld���q��xKW�Ev6$���TQC2xR�,d%H���֐ؖ�n�C�u�)�WX�;	��F8�.)��$;�d�:K�:Ɗ�v�|�'B)7۩n��tH)��XGY_�HQUx�(�Ey�<��.�R���uH��svO��=�$Er�c^
B	A&���<��	K�֏3&�P�R\��0�?V^�|�0j"�iXv���Cuϸ�uc�Og��+WB��`���g�ϯ�
�c�ut�GS�[v�8�7.\�ƴ�d��H6dB��X��m��Rd���`]�1y��
z�4CW�3̰����*���"��P=��aD/�umU�ё�xe,]���-�"Z*Y���q^�]Z�B�q�u��}8
���|���ҼΔe}��0�.ko|�iBQ]Xd���6�,��kՍA��j�	����B�<$����<	�[��LYs�*���=��{��Y�[��ldv$�^��-3�X�n��ux���U�?�햓4\�?��6�z���/%;%����p���իO�8bI��oGW�����f�֖=�Z�F�S����q�aC�.������B�@�����V�4<{�t��tq1��,��R���5ʶ�)��s��r���]�<��ڲ��s�����'Ş�
���iQe���G`L�#����n������u9�f�����̫�^S�q��t�cO��Iڙr5�W���u��+�{�dx)BA�R)�`f�F:��ꮒ7�c�.�1���e�>�ק��n�ЇԦ	��:�U �?!�aC��+��;qo��q��M���衾�y���R;�1�/�6w-��5�S�4@V����Ē洀�x�#��t��?����]rz��kg5@��6��i��c��D\o��W����Z�G�v8M�9MT�-s��.�KJ�0���D�V�2�4�A���1ۑ-?z+J�ӈx�Or^�������{�]��_�m���+d�\&����P_:���(��/�������H�G����4Yv% ���:��I��핝|��b|c��x@�1pNa)mm����,ٚ�Z���߰x��dd�����)��8<=<�.h� �݋��و/���LF~N�uܛ��j0Y�l���Z
����fl}G�XK����a.�f��/�	���Ұ�[W�o0���#��N�KW�Ш�IB�Oj�9��X��uq����X��$8�w1����|#�l��ԇ4P�ky�"؇�>���i�����vI��R)��0�D�Y���/^L}���Z��]l`��A(�Ԩf�Ls��ã�ɐۀ\�>8����t�HA�p���!PQq�d���XwV�gm�<����h@l��C���S�F㳽'
�s�ҝ��~R�+��V��6��ߛ��%s���z�>|?dY��x�	i#p�)�
�Y�*X���-��f����|��v�&C��Ү�-jqF�f"$p5��K0 ���8�0�w������+mhr��:�T�k���i>�˨17�xۦ��.]�:�]ӥ�}}ji�*Ȃ�^�X��#��<`U������<��iüU�y	<(:�(ݷ�{�9�G�+�pr(�D�J�qim-M�f�F��\@#�{l��ُ��mS�����J��e�;o��
/�Fy�m��]Z�C1��c'/���zA�������	H�s�rq懶�:����A`Ή�7�`H�X����zi��)����_���$J[�	+�\�&g|���Ѽ-_�z�7@-��`cp�j�,����HI�ҩwS5uR0���6�Wpp{�ߟ��ŝp�{w_����{Ncݫ���I���}���!.
[��l���n
g����[����!���3��3#�,�k%��bV]��wBU��?��5�?�����s��������1zc�Ha��00�w9�U��<Z��ɚ�=ן��'pl��h�3M�,J��C^�G�$p�n
��"�]����������O��^�rAI'w��H���B��z�՞ή��\�7�.e{xøWT��K��TC�ψ����a�iQ�RJDi+!q��@��LBG�A���PX��
#h*
ƚ������U�@N�|�w����!�dk!���
z��v��hBqQ�;�a��#�8�=��”w8�?�=��\5�Y�"g?cZ�@�z`Jw*��wL���7^8x�Ҷ��E�賂�u*T���㥾�/���������S"!2>���4yC*�>��*�"�c/mfc_�o���k��b�cW���^o�W�xCvi&@�Z��g��ս{m9^Lϳm8�Z�y+�7t��-)I}�o�Hg'���p�����l(�k��w��\
D�p��G=B����`�����m����L�B�e~�}�����q�3~LZ�P��jo%'�C�o�cqŭ��	Ř��v.��ţ�C�L���㊯�0p���b�>�NT
��
�ƣ��TL�*bں�+1��� yWP�~�RKU��|�T�4г�5�]�{D�ڍXk;3�Qm���=o���bZ%1C��d^3P��ÿ́~;t�oʌ���)k��׆+��
���	���qϳ��'���sP?΍���c�n`4`�`c�����$�8'L�xQ�"�����q�e�����E3B�o��"�Rc�n���5�C�1��G(.i�l�̢�)u�>����e^������~y�XQLe
C��ܕ�^8�u����9X���/
e��-]���GPŖP�������ɍ�<���b'����T����y����۞)�!�w,s�:02
���t�;p�����J�6`�?��	��
�݋
YXI'�_��3�!2\1|aIߐ�_�̬˔:;W���v�D��v��P:{��o4�Z��g��+ɷQ�|�d��P9�(X�.�����n4�γ�^�d�b�#.(�N�ɡ�U&���'{�K<=���{B�39`l^4#U1���Z;wv�(�h5����<�Xző)=�M=8ޛRȝ��`��q��a^�J���*�"�ތ�ɝ�ඒe���+*���j5La�Ʃ��!�П�05��r��r=�`os��9�RI�5��bV�Q̈��V�Hٜdܒ;c$P��ܵ���z��}ĮDW�[���/��?���ߠ`8�9(�}����Q�K�[��_��:�����?/8�Z"q���j�m����K��{������48��3
�#��JiJ�'/�ܣI�8/�cO}dP0I_�M�w�TQי{MNzi������V��3���}�QߛE�����س�o)����ar��0�����K��������V�+��>שhV4$k�=�O,Z��;�d�y�^�t�F`Gx�&¹��>���%;q����8�	��gwp�-�d�F��	�Z�Y�:�7��?���d�k�%3��$R2m�zͤ9�t����U��*�27묵>���i���K[����5ɜ�+VG���bO�KT�Q&��-�+/V�m�P�m��m�SI}�N܉B���.�
u����S���[�m�FwFc�yk&�H:T�/"��o�<Uv��ʹ4l;�>��z
��:DFh�m9.n7�V�a�Q��1:6mb�ko/�2���Jl�2�ad������`"��b�_3���N�Ǘ�&��'��5AJ�pR����}t!�����q�=����y��0ZhD��c�c�0�ʱ�ʦm*�'MO|Cgmk	3w9���L�EU�{S���D�Q"a����4�l��x�4��"9��+�+t{�y^8
v��N��������iMC@�s��.����;�n������XS��}���n�}&�f60���a���?�`7)tgt���4ϥ8i�ch�DZ�\�{Z���y�?�r���
Ǽ�q�hR�r4���߭�M�8>��!�b}V����g�C�9��}��l�qO��竀�X��]j�cG�F�˜��L/e)��MI�3ł��Qo_ЄJ�}1�����H!�QN�Q֤j/D1�|J�#�8圕/h�s�'��-�O�.n��X�^�>�a|U`U4I�9�u���\��q0��K>���o��;@6ڟ�i�A�ߑ�
Ѕ�?$s�������%<�cS�^��%���w�2�d��"r�,�)��P�<Pq>�MtH!�
�Jz���sO"������׸j�MR1�8/�Y7>���'��"%�]~^Kp+�y�ᮜ�B�:�KY6��	o��E�:��?]?ד��+q�jT&�׈xgm����qT;
���b4��|T7��ޙ�����[)�'��ۚ!Yo�S�|�T�+���v�xh �y�K���_6oNTԐ����iOɐ
2x$�x�b�ȈK�Dt�;Ɵ5$�
��]�\�hMS�
U<�{���
��k��ܣ����{�`�yp���J&��s'�{�\�*ɘ���o��$f�S.�����x���U2
NE�Z�b~�������Ng������A�'W�B�|��To"���'���E��#��D����X�ڟj�j
������I:~	lP,V%���;Y�7�{��u�L�#a���;+`�F���05&����.�-H�y`�"}�Zv����n��#�=�|M�C��\�~�o�K#8�u���Ly���IC8��tF5{�%s[ �Q�w.X�E��.=���"���U��#����]�,Du/u����:���8���G�S�c�Ԩ�E�d���+��I�3��~�d�T-u����.m�%�*̪�0��aͼ����zjTW�yX>�O�7��)��y9>Av���'���[�/�����t@݃;w�DN�ÑA���aڳ�1����
/=�_f�K��h�mN9��!TL?�����/⨜��֔��~�����>y;��oGAͿ�a0�]t	"MlO��H�2��Al�G�	j�(9E�VY8��[r���’ۨeB�#u��Wh�3�)��ӆJCH4�gG�@^{�W�9f�&;����P������U˚'8������}1�ój8�����a�e6�do,�0E7:.F������/~eJ�[=��18�x�>Z1��T��w�_����H
���~��8�8�fr�5�]#NM6��r�����R�c��A����sF�dn/��fBMM<�h_��u#�](���Pd�Z�T^a��A�gZ�n��{Wю�����>ot�l�D�̅�;���y��yQ ۉ�_�w^F �{bZ;����+^�b����!>�:!��9�XG�>h�_�у�-Z�� ��˱��/�+;د���
������5
�����~�U��t3ƽ���?���T)��?��9�P��[�V���yK!Է�z�{����b����Ռ��,r1�2[AJ58��e;P�����3^^������2��:���%*�0���f.�?�U������ƒl�U!e?��3ė5���^���q�&
����^Rc1Ϩ H�W��L�[R���\R��m����̐��b�^��e�rn��A�'lߛȽ�����10��<�$���P�:$��/EՄӻ��;�󤦆~���GP�E�V�PfĐX)�:_��n����ߟ�x2����6;���3QL�3���n+ީ��zCx���'�M�yҎ$�1�u���>>������da��wۖӴ���GP��)��a�2>�W�C(�~]��T(�9�/?��==���0Z"�a߾�Ќ[��>���?~���i��梔=��@�8^����M��W����-2f�3����*
wBS�l҃����r;�,���=x���<��˗�ű���t�p�`Z���y5F�@_�1�%�,��_�`�5ZʑT�h��JY齦�71۵d8�&9L��{�l���C��#�{�̲[KČaJ?E5/dm���_�w�m��x��?�ƗN���ؽ�Y�5k�����p{�g���5��~���u%y$/���{�w�<�A:L�,bA��H�-E"�{�^7��	#fZȥ3y
�m���5�˘V.�D��!d?���^��8�l8��碦�G3~�]4l|ʲr=�lY�����#�Mgy�1ԣ��gMK���?u�E���k;J�>��\�™�9�%&oG-�V,��-��(�.���rqɝ3��`�"Y�KB��c�Ri��K���
5�3����wXͫ�ң]�Bs���b�0?U�jj�yq��w9�c�c��`KH�U:�~���5�.64�zV �A	��8����;��i��y);�`7��Zx
/�U��}t�����Swr��Z�
^x�y�G�Z�aܠ�dn^�gt�*�����o /hVb�e�2�i@iv
���w)��N*��5�*-�dq*g�>8�sq�i�V�'1��S��̯v�񰔟��t�E|zS��%%�����},ߟ䂵A�JA#(�6��5e�5#����t�y�+��,�;)�S�g6W�8�s�+��{�M��hG(�"A�)���M8�j���JPnO�p![t����6o��
�*��%���V�"h�"u���+|�����?Rۉ������@�F2)����
��O6F|>V�F���|r��4���kYh�t�uY�b�L��H��>�.I��� 7��r���/M|�E�p����)AI�3�dS�5�tk�E�� X2)iq�t�i7���I���#4@�	��,����yf��un2kBeojb_�2詚k�������5F��Ԙ$߳��#������,��G%.�..y~�n[	<��F�w;&q1P�qR����Qn�p�6����<�X��ӓ���Rg��5�����H��%�^��1��a쀢Wm>��L��M��6o�L�[�����g�Ɍz���x�
$1j���P�#��bQ_ҕ=�
�vN�g<+�X�̈́�yʈ�%��\�0������̌�ͺBE[G�.������0�0�i�0�8#cƍ�gnP��������̪`�P|b�0�G���ơ�����{�Ux��	rG[���ι鋪�:\>TL�b_S�y���Opo��:%GǦ�+k���w�#�H������MA�ܾ2ސ٩lb3H���5%G����7�
��ZT{��`��&�
T�l���2�U#4�R9*��ٵ3�+�oL�K���&!�M�Îv�)�ja%j~��_F�T��k�!D����������Z���sqLj�� n���}�6�y��-���em��E��Fm�9�Z���o�l�y܈F�o�d}�F���,�*��9F:�n;��V��f-DI���|�0	� ���t��MMR>����Y5l!�5	�\N��=�	@�0��h���@����J�rN_߁�Q�?��GP�CfF�e�c����aߚ�Uy�-�.@�<��O�����II�3��N��j�;��SsVIzq �jS�h{,�$kXw!@��o6t�P"w��ʚ��<<�`]<��x���nWqN!�e��$C<��$i
�Ϫah�?���`��t��07f��zL����m�S<-c~e�\1K���ً�.�����L�i�����ɍ����yP*��#�*��㞧=�ʨN��v���b������nz3i�i6m_���)=n_��fl�ٕS�T��l���/Z.�
BΑս#!�G��D�*�gVڵ�e�oZ%f��_�F�
U>�
�
�4�F�,����i����NAà� !�����=�]���_Ƕ>�S��<������q*/�!OE
_�s"\���F�~�6	I��$PS|� ��{�����!�7z:=�z�c�/��b��`hM�z?�x�e�����Ca]��t~.o�OE��N-�G
�{�Y���_TA��e�$�$�``r�\b�;ϝ/�+<�)��1�`��SUwpO��p�+!$��~n�F*Zfa{p'��c��ʾ�j��r�d�����L��{�J\mX�*�?ED�ur�I�o+�4�*��PD��*׉f3"�>�_&�����z��*\P���^0��,�v<�I�ۂѲ�k��3BUDk7wt�ׄ�@Yp�t<^ɹ}<?���s8���f�"B׸x�!�ä����2�:�ch�!)H‚Z��[��Tbŕ�k[K`�2� ��������s-��p�A�7i�rSQ(�|o�3;ۣ��&�sH��4TvF/���	[ݼ\5�O��P���o��b��R*=��M�6��!�_e6�:s��ʷ���Dhk=K�4�7û�N"��S7��[;�r�<nV�Y�	�pz٨�q,$�l�1�۞��3kAwK|n9��w���P�9�4ڈ�[�ֆ�m�Ra/�S�֙
�=�7ģ}��Ȝ6���ݿ�q�\0������hKT`5E�r����6�R������7�#������ω��0���NV�|�2l.��p�Ճ�+�r,��ڶ�'��4�&����?[#V<���K9�*���.�C����=�����C�Xe��H8�@���,1|�Y�&��'��a �C�JJ��[��:e�@� ��|�F����,�ݲ�Od�Rcq0>|�Oc�o���/Gkc.-��+=��ƽµ��B��݅��:���K��%y�.���U�ϭ-j���� �qM]��v.�*m��3����V2y"|�
H~�V+n���,d����9��Nh��GI�)F�L	��'���S��L�e�|P���c�y����k[=M�}s�	��W	���6�*�U[[Z,<�5u��\o�X+-*mx���A6���R��v�Ÿ��ȍ�t�͋�m�&b9�P%��Q���F�/�/��h�9�D�S[@���K�w��л=��f�p����f4��G/��<$kt����~���_��Az�%W�a�#��e�.&�X:�Ma�/��--�-�3t2]���
7� �E��g �M��D;BP�<��E��ܙ|���"�����<�بQ��9tq�1�P�T*������Ck��&-�Ex�(J��r�h�nY����݁�"]�(�Iv�������R)����hqҢ�c%i�݅԰��ff�K�x
ⶡ~�����+N.�4�sZ��6��Җ���|����d�T4���n��-ɜp��R��}����Vm�b�m��y�㌬AB�j��ږMٳd4
����le����i�btI���S���¡��4��vI����f5��~���L�ㆇ�ĥe�ۉ�F�;o"�^��hē�����P������"džXA�%��r�/�+�@l�;��\'�{��r�cw�����2�`!=R��>f@*�s"{��C��b/?n.��O���	�+�Zmg%�T���@��3\�I^�'��bQk�
�6�R@u�E��`�j�ٜ.��;ɱJ��#Ca�׵
�+K5Өp�U�Q-3�fcS�@�s�Cݎ�Pgezb������m��.�	�l8�;Q6�K ���y�2�&���z�e�X�-���7�֑#k�֥��sf�m�4E����aӶ<yڷ��uU�j��;���&�~�	�2#]�e�k�B?Bc= 2A4]��\r��s�P@��t�T���i½j��)�D��fj�6Y~&���믿�_q�
�����+���DɰDQ���Œ�����Mi��	�?�Yg�@�WW�c<���3�21;M��j�୏a
�0�s�����'�2���%���X�p��I�3��?��[=�W��OX���౦���:'��`��˲
M�s����`���tc;�ۂzd���Q-�7��#�^RP^�q�w��`�|�˖-���#�dU�h�'{4񒩜�f{�V����-{��
��ݾ�Q037�<�I0.6�"fČe��f	k���n%(0A�u.^\0zq#�^��_� 0N�Y��U���m���'D�p�5"Y��6���K�al�ey��I6,�q�!q�b�>�v�׌2�:�1Ā�j���&�#�IF����{�b!�<��[�Ix��b �xF9��5���
�i��K�'⛕>�똞��Lr3�u�&se��q�L�������2����k�}�8�K�&�e��_��bҏ�h��3������Z�ٝ#�e�� Gf"k��	a�2g��=:�K����#8�.��y�,��3����k��<��J�P�Zl�`̳�+�–j��~!���)�}�O�2)�e/�u��hIfQQa��K:������Q+��'��|ܱ1��%�~x8b���*��u�t���"ޮC���i�΅,��6l�s�Lj���r�l��Pf���s���c�s#x��:�-v�8��u>�g�G�H&�'U��i����#����DYQh�|0K16�����q�_:���qVCK�!ːP^�.��;%�t�^�i3�Aw��J��40�g��ܢ����8���_�8�
���uȠ�ڄ��ޏ z9��
3{9ք�mm࢕�+��������
�d8a!�QP����qQ��VᆠȂ�r��*�a�f����MrC�?�C�6���Dn�Cw��h�Y�
Y2e��DZ���wa�RW�����DA�S\+buAh�	@
� ���ŧ���%~��A����J�I��nכK��y�.�;lV��:b�j������'L������g�z��@�i�^�43��?��0�0&x<��p���/h�1
�/�\}˫_�R���QO��N��#���ҹ���d��V��Hvа��v�����I��h�r�A�BxA5�ar��p�ύt��%��9�,�,(�-o�;q�ɟY��N��>~�Lp�+��5�1�,�]��0��{��+&��/@�8�)�n��9��ҥ]HZ�0=]؅��4S��u�U�<ÿ�;�<Aw�j��H�ʴ��+��>��C��We��ơ�~!�z�`�)h����&0�-��
�i��p��B��[zh���M�*˻�s�ݷ�sg�d2I&�dH�������TD�*"����ڐ�j�Z��X�*n�jdQ��2!�@�ɞ�6�̾�}�����3w�m��XI�/L�v�����,��\{��<P��Ţmu�Qo�����4��Z�
��K��2[;M*y�¯�«�X��T�q��lH穒C�81%��u��g��R���#PF^�)=�1Z3�_#�p��h���b��u�Gw�U��?���ā�
VYѨX��Ϗo]�Z;����Hn����8�y��M���4��G�2�H#s;�P�a�(���m}U�	��X:>�z�@�;6�
,y�3n�V#�F�`�š!����$N��p���z��q�����-�Y�����F���ԍj�����_�a��3L�ӎi�J *�@�]N�*Li�B�,��N@g��B9}fj���,���nmjʼn?]^e���h��sP���zt���K||�K��n�o� �rH��h`Ɩ�/
�W\�M	6.˅�{�Z���}�e�1�b3�(����T���$\iVePV��|U��C��:`
:C-E����q1*[|�`�|`�ú��XOS�6bٙ~����,)%FSwÌ~�����I���/Y?�^�IaO���
|���o�4ׄ�Z��IHT�D=�J?�����5�}@b�2���„��4�� ׮͛l'�/�S-
f2X�,�z1�h���/bY�ȴS�ݛ)�{���Q���вۥ�������{��[i�U׉*c6A���{�ÑyU����܇�T�ρ]\��m�?'誢�?+��W_q�>Y�.�R�m��Kq�6�W3E]~�lr�_v�@Њj(���ޢ��N$`�M݂� �g3 f7'?N�G-M�@���t���p�“���3�(<��Ć�hH!�~0Ku4��N�JW�IXe���"/�A�)�&�3>(�Q��EA�t��Rer���%(i�wvA��&y;Q0�_x�$ϗ�z{?�h�7�aj��b^fyi%����q�X�&���c����ԺV�9�2�Py�"f���ӣ�e���q3��1F��;w�eߟρ��ԯ�Po��J߸N����b���hZ���299�|�m�LL�9�w
���f���6S���ڪSF7O	mK�	�ʅ��3Zj��

���R��,�2z�h�5������d/+���峕�e�<o{�&OS�1N&�麪&QN�f�î�|��E\�_�϶SVQؖa�-�`�I֋��Ry�O��SA]���]~k��;���~XO����%I�4@6U�Ĩ�a<A1��W��r��p�Xq���tv?K�����)��r2��&�۸Q�;����*��:Tɍm������%��R�]��/_*�7���ҳWt��a��u��I
���Zb����51X\��Ω:���	��p1��'���I�Yt��u�X�K)�RMv����PZ�(/�6���F+�E�R}z��3
:Өh��x:~���Ɲ��B��:�����P`x��l�=��M��5�x�!Xt
�O>&��f^���b���R����g���w\�6�\4�j��c|�!jU��&�P#���ѝN*�1���;�x�)�|0d�s�N2^+Û�����f�O��d�]��B����8��zFi7�ZW��#=_Z�ڡ�vr��
z=Z�t�dk��o�g*���-+�23��,"Ի;ΰ>�C�����"�������M�v]P7Z ���=D�����*^�e��@"�B�k��;��W6��b10"\B���K���J�Z=ω���‰�8����'���Ֆ�1YF��9Gs}{�h"Kn38lZ���&/�[q����� �H�-?��'a�݇<u$9R���:�H^�V
@d}���s��!��!��A��(/Y��&\G���W\���V�w���`����(��Tw7����]t��=�t����3	F6<�AT�o����*{�X9Lp�zŒ���)R9A9ͨ����q�\��������>��(0lg!��2c�׶7����WS0�#�Eԫ3ZZ��(�-\ސO��9��������o��	�`Ȍl� d{+��Epi�=�ЩF�k76��UOÕ�1,����3kU�w����93O�=�h�
�m6z�7��K���C��D��$�X����t�|���+=�^V��;ؽ7�z�z@�{HV�9�n<�`�g�]��%6��K(_\���h.����8�L��K���8>�X5��Wx͌�:���3㭼��Js��v:z\��
��Ҵ��HK������bS��@dҦj��<��}:���c��ӟ�<鬢]�^eӯ���4�c���/����!@�f駾���&�[뙤z7��W���������G���T�����g��gH��~��jW�tQ��mb�m����e��-*L�h���,��?����B�����N�E(��,6����%f�:�Г�E��C��)��!�L�s7�z��z�
dc�,�v��'Y�h�X��� 8=�pkG��B��w��f;�*&6RuS��� �%<�9nYPN�v�v���T��(�.s�Ok�ͮNu<��|cR-(�+�%B��A��w4�e� }^i_���E�5���*�X�[����;���@5h�7Dz87�T��x&����D&;B�	Ǔ��BA�uE����ږs/[�,J��*��H|;j��5+�sB	�d�!C�	���w,�toE�n7�v�����/�� �I��}Tԋ_�rZ<.�t��Q/����/b�?D�\��R5�h��~� z�# �T��9,
m����[�����B*�di4j�m$r�l�&)���_i�أ%%5@IDAT�Ur�!�:__�ޞ�=��dX[Ƞc/3+���=��8���m;�+<��ӏt���I7���[�6� ����Cg��F;����&�+�0)n��K$�*,\O<u�m��NS�9'��P�Cl���<�y�Q�Z�у�}�v6��7��@<����1)�e�K[��^�Y���*if��wh�T���<ۊ�q���b��y��m����X��Bɳ��CP��k�ԫq��7DA>S���N�+ϦS��=�
��^.�����H���Qx���>�쑁3W/lH�;�_�C��+����O�9|�|>	km�eD�~J|Ma���67�ݛ�p))�C��}��/f��/��K�!2�p|�Lg�R·Jr0Y� X�C(4z6Jw�s������ĸ;?���^Lil�~������/�X�mñٛ�l�O,"��9����ks��Em�)9�y }Z�K��z��?��_���h�1�۹Qf�/��+`������x_�gW:��C���췟��-Eώ[E�
��<)�rx��	S�f,�?ػ���-�LQ�tR�lJ8�}�&A���$H�����L��"!�|��>���V�������d?�+:F��࿄1j��n�n�X�H���!�m��_��0.�������k{5��c&!Y��J )��r�A�ð���j}�.�E��RU3�����|�0���w��DH@�^�m�&ғ"еw����U�.Ô�+�ljL��@H_� m,3�l:]�>r��6r���;��Ӌ}�ɖ��b-$����K$I��Tl�17�-e;z(�?]d�MH���p���n�c���h=\���Ft�~�R����Tz05�Æ�߄E��8Axl�
��r����e�[D�2X���F��H2ź����1uU�3����o��G�zL�xJ���#�葲�tsS���&4u$�h����sRb��ca��_c��z�=�2�7z�n�HQ�q=E�Rq�T�5�|x5�Y�6�ݚ�R/ffȇ2� ����>Ώ;��"�-���€i���j����	���u�p��z�>כ\��H���9N�Qb���M��Z�:]97�;>�2���f�*)Ԃ#��=��.yD��{�r��r�R^�.���4�P����h�1�+.�ڄ�ܓI)����?��b#2K�`��?���Q,�[h٫˗�}��#�W/t�M�7���'�l�����L��Q�"E�����*k5{�Is���5�&���ח���i��`���~*V�ql�v5o�dR/�F^���=��G
}�4[w��/��r-0P��1�Ž��š�h禍s{dz�<�aċ�f�:��;�D��\��m�՟��3M����tP �4+�,�B2�3����<�}l�̛�҆M���_�E|��"����4&��)jfc��/��d3/��K{z�EI��[a29?&�����G�QD��
������J��M�J+J��>�/f�b�Q&�6�n,<�r!�߂�fvh��'.���zY�᭨�6�Kd��=�tt�
j�VV��읳9�v�ՈLs0�
��n0(n���/ki����<�h�N��.1��-۟�iZ��;Z�zJ�Ug��*77�ޟ�d��J?�%f�!
�$f&���i,����	?s�5zA�!���u0<�p��o��O�G����q�+�n�/��f��E�{�s�v�xQ;U&�.Y�^���S\�5�!�f��1}%�{����
X�no޲f"��Q51+�)3�Y�2��%�&���@~SS��B׊�R��vҎ��~���YUJ��Ef����"���Ǔv)�@3�7�e�%�D�7�I,�{n��5�1�j\��#V$�z�bM
�Q�S�����3�
��<j��{�2'�~���?��޽�ٓCTU�}m!G�(�p&j�#_	��Cc��Y�4�/
s�ɞ��=_�޼>�Q9Ջ*0�O�c���k�P9��Y�`{W�K��/(�ڕ8L�a�0�7"��CL<�d�S��B�Nc���9B�7Lv�-�U&�jV��������U��Y
J����ц��Pޏf47c�s8A��	m�6Ftb�JJdjQZ��l^3o�h�%Z���`y�Ĉh7䃻�{����_%RfU�(�i�mh�I�M�����km(oIޓ�NY�J�(%� �=R���V5	>YvF&1���#��!��ᢍ'J��N��\�v.}�������9�0g��C�[ʁJ8+��
�'�i��U���� *w�m��g�5��b����YA�x�W��t3��E���]g��Z�A�<�=p�p^���u�ł���Gh���
�rL-���t' F�uL���Z�*��f5�J��Dn0����IRh��G�SX�!��h��3d��PfW�Pu~��z�'`f�k�v��هӥdb�7
7�[n�i��r٨pY�}T�����c� ځ��"�N���e��i0�O��#@3�Xȱ!4b�JIY~�ҎS��s9k1��<RQhi���):�tMF����l��z9�ݣ�(?��9E����?����i��\��~jll^7ꬹ�βa3E�X7�n��m�LA(_�����rto�5`:�:-�8����%Sq@�G��s,̹s�gO
e�a�֍ߣ$֧��' oEQ��V��~!�ҁ�,|����s�A�ycM��w���?��0�NH��?>q��z��ɕ�0TL��U�v�c�b�`b�@e��/�V"�ȑ3F��?Ѱ�af��Nn�?b�!�^�Sdӥ"}�D�N������%�����,]
9�Akz��_�DA0���W �iBT�؉�	 �1Y6��OZ�ъg�D6�b�{�噇bi`-�0��x}a5��(�Vr�@F�VH�p2�ɓ�b�� G�h�TM�bA�K�\u���Xjլ��6��B���i��*Z4D���q������Л6��HR��~��y0~����x��ϥ�;Ǹ���rp�,L�;O��
$�PFv"gqS���#��3�B۳����}Y��t%D��T��*z)�1�\¢�|^Q�����o�b�"�bO�n
9�B����T��)�����C��Q܌~�w���L�<��k�(�s/�?<���cI�YQ���F�d�p,�}�Y7�X�,��̌q�*e������ф��H+<�3�n��P8+޺\���[j�[���Ω�mLRAOiG�\%�y�d��E[��~Ĕ�/�8�Q���/�<)Lj���]36���s���r���`�B#E���1fV��R�5s�'O�}��~�)h��0�i0_�9x�K�"�g�ҕ��8�]T�[.��A�.����Ph�5�PcR�fW9jխ=c#T]��-����|iD^�N%��r1�j��η����m?;'�)�3�O�3%T�2m(�yp��}�m۟W߳�-_
 <(+c��RA¿�P�pIވ��vA�uf�a;�d��� ����;Npv��.��K�I�}@-�UH;(�ԩ�`|�d�F%��0B��@���ҳ��Av�z��8B�ϩ�-f&Ls�pԁ�ZScY�(��>�Y���>r��G�C/2sr�M4?�C�Y$��9��g,�,���@3`آ��{����Ky㋘�w"�ʁ9[���
�]�i�".��nה�'�tP�6GAI�U��s�b��I8�ޮd6�R`�Ց�*d�Qg��xJ�Q�E
�EHǢ����6ğ>]*X�j˟�F"!���WDd���n��\�F���!��:�B|�9�vE
���1��k �Tpߑ�r�J��x��H�ҝ��WɄ�����
 x���
@�DɠE���7��kp#9�*����Q�d6��b�������:�\�ns�1�]Eu]�D���n����h���
�D�'����dwq@��S�*R>��XP՜#��޽|��wvV�5A|��Zy�����o���F�6�~
m���Qގ����g��(
=v��Q��C/�V���+�%II�*>��$�/�t][�
0��9k/�,��RQ	�:���v����9No���u�Z����ٖ��'p��E�UM��H_����[�8�B�
r�U:���6�k�u�oQ�/��]��p�>��
�t�:���R�X�z�7��+�L���l�6�H�uI��X���P��xˤ6O|��۵����sE��@�IU
:�2i����L���}�+���ˀՒ3@�L.�(�����!I��vM�P<�E���']}��<��H)&����]�BݜX��m�Y�vY|�����v?=�V~�����R=�/i3'��=�hY��,ZK�U5q#�e�R��CxRD֩;�YU�����[_�����EAW�JY���,�c����Zr�d���	�/�gxbNO	&�YC�n�S#�k���{�����8Y�x��n��h���sPd 1�%KN���g^��^_M6��1u,�+
!�s�k��h�؜Gr`?N/C�_�\�����N�}�My5`j6.�AM�Kf
�9a?V��v�IL"��O(?w
t) 7yLhuCC�L,�w;>�&L����w��a��f�D��8A|dEaoZD3v���&Z���q�걋�aR�5�w�l<���S�r)�y��Ur\R�uI`�SR�f\h�%'�
��;���Yz��M�8�-^�d]v+��^��>�՜L��t%'���'�+�<&S�'
�ч%��y��T��sL����sه���m�D��PV���G���e���ux�����#M��tg�6��0[�.YÛ&Ǚa�Cd �G��uU͸��\�‡2��F����is=<�/C�?�'2Jo��lP�ϯ�x�`6p��Z���m=DB*��tx/��ar����1)x	\��;c&q3�m���{�|1p�W�S��f��#�f������ۖn�b��f2�&��(.:���;$"���ӷ���S���~L["�E�=C��^���3�j&[�sZ�!�vAP�2�q̶x&�XR�0��<�bu�Vdk�����z��ť|�Q�)�c�M��4����SM��h�����xh��Bˀ��'^ȡ�
D'c�```�B91�]��\�����}�e2��ɶ��!���[B��ƨ(��D����|���S��mn��Q ��x�Κ�6hF���4�#�M��E�d�������&�mO4��ߍu�>Қ=�&��,�2�VJь��#��ܓl������+,�.�.�/�d�׻� �
�l&�#LB~n�9;�Y�a��EKZ�.`
��g��o'NeG�JfC��*���y�:p�OU*��|z߈?fS87�k�|��%_�~S\Ш��AQ�������q_^�B�6�/4�X
�Fh9p~�I�K�C����=�Q�!Ë��������Z*]g��-'���S���b5�C>J*���[V�O��W@`<b�kl��a�lZ}M���"ˊb&?�V~C p�)��$�Q+i�5���w
��7�g6/�|�b&y����Ъy��L��M�W5�V�f�\'gDJ���
e�FP6��=�kd�囚���P+�h�� ���v4�$��)dԔ��F[��1|�C��~To���C�|��F��G$�\V���o�,�c_��P��CQK�J�
'	�ʶ��5_�Fpn7̡���kY`�׎�l�?G��`��Ch;e���'_��:��.�fL����<LM�̀�P]�F}�$�T�F��+ ��z��[�i��&�T�
�C�D$�.k!�]�R4���5���g.kj���aX�.B��rA�*'P���Tu���ZQ>��7{�ps(^�D�	���P��X6n����i�tJvRԩ����d��Qب�b�çX��9t�Ah	�4ĩ�񆘪���%\=PĠ��_�ț�64���5�(�>"�4QD|��y:-�`��lyC_�1��t�
4U`8�kM:_I�M��T�!�sl�U�;��Q�}픞S
l��Hg�y��_٭����Qn����S��6MPtV6"��ds]�H�_!���̣���?�_/7��!h��J���L	��Q�����r-��`*.��A�q��o~�F��&/�D¥yu�_>q���V[��Qǽ-��
.��Qg�$����;d�@��X�`���)�b��]��X��M�eK�����8˂B��\:z��]�r0�����9�}7_�}��mql��*g	gFW,B��6��"�]H���I�8ق`yQ������j�0.������}]�{v�P�j|\����W�bJW̩�}�m��2���;����QMU����ӑg$������-;Q2�(�%�j<���(|�`��Q[���3Ȃ����,��ܵ���s"��x�����<E���F����Ȍ:k�7�������>�ů�C��?�Te��)H�
��c"6�(<`�M-|ӏ�~���_�r_��͐Is�z���;���E0�k��Pꚇ��JjI56B!CJ�xJ�4a'�*6�[O	:G�~^��L*���&�R2Td2�~O9�M�EQ��3�	*B)/����g`���)� '� �vq��p��!����x.k���^�����;]������b�#�eɺQ�*� �\&�����y�J@</j�Q�|���lx��A�9ɯ���{ZC_�YA�u��ԇXΚųOn��ҿ����!F9!����Y�5
g��X��ՎApŠ	%m���e�J�	)�+�������d�M�ʷɈpOmG����T�֍Z|9��������R
��hd�\�~)(.�tT349=�(�z�" ��a�9�&�Qx+���
r��`|�X�z(`5�&�J��l�
��d�c&�@��������3*/le�����bMkUZWiۓpO4b�7����2��i����…�qDQ .��0����y<
�mR��%z�&W<DgI�)���D�Ak�)-sE�l�;�!�rF"�����
F��r�FP����KxY�Iv!��x�ӎ!�����s��ZO
��2�¨��	�\��M��:�[;:�1�kؒ`��N�7�**��8��A���FJ�����04B�`�a@xQ��'�vA�A�dݘQt���dc�~���Uj���hC�k�p94�x���N�L��y���O�߬�֚�ZJ�
Tro���g${2�^؟�!�؍!C6Zٶ�!1T�YֿuU����
�{kę�r�k�z"��Q�e�L���󱘍��^W
���({`�㌯��zh��(2�v+fzLy�:W�E0��9" ɾe���M�n$;1�#�
�T���	�Gy��k2�s�g{!���d�}�����-��b"��燢���FUl�V6��d2�1�`N�!�9>%I�{�/�I)6Q���|��� D�q��f.�d^'�%�VZ�,oU�о�b�:&�s
	%G�)�!�6�}�b<�#^�+P��!���Fhä�[�y#��^�����w}�'�C���Y$�_�����M��90��l0c�P��ͱD�d~Qw�T�>��mm��Z�3�q�Ί�l�z.�4�gAR܅���~T��*B�E�m�<�����w[\��ʕc��U	k�[0�m�f�Cs��3?~�E!��&<*K����,$h�"���i_+��=4�}��Z�Ԡ+Q9���Z�Qh�7�(�E�[�
\;�ZEd����������w�(R�|�M/]�֮doae �M<8����i��a�-�H��b>����ao�\����$2�9,:��\�����HNea@1J��Qiq.8�/f%�
e[h���5�󐍿VlZ8/m��.Y�t!�Y�CK�r>Xfw���� ���Ed�[��r�𚪪HR�=ϿX�QN�)�R-��йª��45�S�9�I��� ���� �g�_�|	������n�<7^@���fw����)��I��傣٬��O񗢞���H�o���P�f���*}cR
�+�&y�%x���z=g0�9�e��b�-��T!�@����-N�3Ћ��Fn&�U��5E�J�ؑnⱴ^/.6(��R<`3�Z������+&�ļ(�X0Qx��s'��	~G�0)fΰʗ-E�[�o�+�{��4M�q1������v������='8E�.�C�4���2�1}�K�-�=m���&t������;AIꧡJ�=}|���۵�rԦ5��+�,}��o1�C���(��L�w /��b<������dQ!J0�aD>�C�"I
�Vx�����A!t���)�.ێ&��})�(L�R0��g�����)\��q�l�`˃�Zr7���6���d�K$,�u~�󑌺��F'��s�I��3�F�]�� M�)0�JZ�f#���z���6��C�u��S�̫�O��zOV�J�0U�_���u�p=Ko�ģBG3�����2B�£�"Y�Ԇ�\w�9�U+���1  ����Z[}V�g��
gȏ}6bg�|�=����F-�t��GA+T�Pz���K�甃d�Y�Аc�n,߿,,
c7�9G+ܯ�p�0*-!��6�E>��\�9R�Tg����j�!�W���"O�DYpi�<����ͅrQ>�ܫ��Z��.½X�v��y"4�&F/�FF�l�0]V˸V�^qM��]Ӻ�l@�T����J��\l�ࢹ�
!���I܌o��׋��m�?N��
�P���&���!_8h�b2qX_���D����!�Ԉ�Q�Y��?���&4;X�Vs`"hO�㱱��5�R��f�prT��`�l��Y�L$bq�+�6d�%�|��(D�����ܡ�oL�{畂���Yk
m2O��Uٌ�����Z��}�F411Pw��0�qe�d�̸e{Q1�i>V���Q
�M-�?�2�Nm��v��H�1d���Ƹ6���Ma>�
�D�m\���n0�C��A��i
�Y�N��l�f"�i�ٚ��pv��K�x@�H�F]�������,����i$�p�)��� l]ps$ �cȢJ��g`�h�O�h��ڷ�2��Kf�k�j�\�#]Ʊ�vԤBDf̘ھ(�9���IyR�0Nma��6���K�!�(�Yn.�Qp//�i�(2(=a8S<��?��n��<���d??z+ccF1~���qz��fǬ�K]`C� ��"��gX����3L��m�ʲL����~P��&����	QJC�60 ����t\U��1&/�Ψ��h������wmr�r����$"�I������7Q��D��ܞǾi�ė^�Jٗ�^�y8M-M�1M4QuޟB��u҇���I�MJ���֬}%���2п�kh�
�p��
���#e��y����I}֊�`�؊B�k�Hz!�7�G�a���sE���f=^c��|����ǩ�rQ�(��aQ���\�T��%qE�TJP��.�2����!�/��Kz<�H�d���b��o��w�����)����Zp�d>�
�0<��4ʧ �����X����D��k���b���n��8/{R�˧�b}��MF0h�2̍k`�ذ�>l�m�0:�>	2f��^SI_}�X�����O���fd��&�"}���eU*��}T����}����E�K��\��͙����o��Z��h�K����W@@����_��=_(j�α�o���
�y�HG�q�*�v_6gB��h��A���9Ւ��=�g�E@�l�
!��y�������z��Nk"�DL>*r�l�\'&�ڦ&y�`-�t��jȲ�9� �)�)o8�k8�3@6j�t�;R)/�F�}�8Eٟ�4�Z�X�����P:<�I��$��4[��;���9�7"�Bh�1:�I�yUb���”ve//:{L���}��V��kc�d(r�w�o#ol-Y�fi�:d�A����,3� )��l5)K��{G���J�@K�+p\���:���a���Q���4�L�)���M�e'�����Y�)��z��+�%���G�܀vv�;Z���Ϊ���+��?|_)�o"XDu'�O���Do�7F��bB�A�ڷYCZV�gwVG�xK{`�q�F�+g =�?�y����h��d]�aÆ_ggz�]�JD��k�"w��f�qp֫�C[��	nn�)go�D�m��!��WpQ�!� k�5�io�c1�y>�4��Ţ��3�S�Lv��/@`n
�ϧw���-k�ut���Y+���7�<m%o��Md���1�Uh"�� h�y���<S��(x0ze$~�Q}��qT;I�yS	�Xq2_��u���$�+k�zZ7����/�Nɥ����12@E���p��D�ש�$�bi�G�A0kN6<r%�ɜȯj(�P"	!��wB�FFh��F��ܼ���>�e����x~	|?яtt�`�)+�|�?�?����Շ��:����
q�d�N�]�b�w�Tø4�o��$FE*�N�w��c���zrp���W�Y�S��n��U5�n9aB�)v��r�J�P�o)6�$�̗�]� è�xQgfa�W���:Z�$m���=��l����5���#�Ev+�����~�5�
��N��'��{>���>�~uk�a͚��I�ý��M�����OW,y5�޹�n���(
y��4��͖
;���[
i!/'��MU�K^L����^�5Ez5U��]�'�O��J�y�e�˥�l��*\qcι78�/.59p#h�ɖ ���Ӂڪ��֎�z�虻�-'�VPQ<��2C`nF��.ޤ�Г����%4�&U�6�U�����L�N�p� #��w|��:�{Y��mp���a�5U�6��C =
��^��F���"s�����n#0�s"򎠜�ܚB4�M�6
�ON�l�i(�m�C�gc]�̪���w�P|����X�I�/&K�[�j��8Xc㘖���s��8Y	�����'Y��?;2���0c�
"�q+7ȇ@ׄd̺�S#=�C�˲�NO޾V�
�pΐ_�ѫ��)��9���?�^2�Ͻq�&�ر-����NKo�sۄ?�u�JCG�=��AE�1Y
�@�P�	��jij��v�w}͘Ź��|���|�Ьz��m��w#����'��K߀28���5p��hiH���q����|A����D̉��9�T�n=黃<�m�B��e~�2�xכ�>}��W�\����ο(˲є�e��M��K:vB�A�o	��k	������OQ��)���������)�v�X����3/�p�c�ܤz��}(�]8���}6�]�u ׊4�Y���t��	>^��19#�+g(q����i��(���<u�9��Y�H����Z&�y2�z����0�m�&dA��N…�!x��qs��8�7�ij6w�%~�F��!W�!�/0�W����'L׊�z��Ĕ�R�f!9|P��l0r�f4+%�q��m��b|6��9���t
|]���Ō�����:>b@��h4��v1��V4�"�W�S�&f�EY�gE�o��:9�i�'a(FѬnZ���;�F,��/YT{��{�����Df�hnPe�{��)��r�l)y.���{�Z�焕�3��8����{��Rȳ%��k,!=/o��WӃ���by�h�;`�B lJ� �`�u|��d���OA�4����yP:V�
'L�w,,�>����%Ao�1�v��kM�;�
a	\���x��J��ΜN
]�;�&�:��?�-���o[qI+4�)?:y�\�8VL1������T@ �)jwj�q�L�6squu��}�2�?ʨ�=��� �xO��DҼD�˲�ȉ$��F]�w������=�ߝ�:����� �%;�+�b?�ZZ�(A��N�8!\�>�p���V7�#�K�\>�טWT�𨡫�SM�IB���%u���H�x�e��Ri�?PN�(�N�w��������2wȮ>�`��蝚�.ke��Z�ȰU��z)j*�f�HLQ)IRF}}}�|�
�x��y�.��+�Ee�����]m����ϸ�0}�0w�EN���@-6w�c�	�L��lF�h���A��/�E�4ܬ[�K�Q�#6܈�;�G��q����b�'-r������eۺ���W]��W��yE螪��`j�ߝ�f�)���,�|�+
�l3���s�6p(o�|T!�E�Ao�/D���R�ٖX#�u�Us��ʖ25��5M��89���d���ٯly�1
,Q_��Z����dA��}��7��D�?���c�B����P͊��>�Jt��3Y���)��]��}Z��yS�3�S��pD��OM^��z-�>
�qʐw��S��s�K2F�vg�MM�\&�oH�)��N&HS�?J:%M��zf�@��~��MT#ȹ�9,}g#�.�J��Or3,��/)�⿂�~��/;
�8j%L���c�<��?���gݪ��U(�F��!̆�W� �y@Ѭ�c��Sh��d���2
��<�lw��p֧(A��(���b�snЇ>�%Wm���sr��} ��
��s�	�Ť\	ʃ���j���/i������"�F��>J륁K/�#F�<��;����"9�:�y���7M��S�sz��>X;��n����(<�̘6
����*����xYk!չ0�W��dK�$<Wok��>{hɎ��Fb"��~V3D]�D�+��Ct]��;p�S����b6ec>/P��xFP��F�<܋hUE&}
��[���]����/c�f�"���d>E�z$ו}�eAD�-1-w�=�g��T��E�M�܋.n�Vw��[�������\ގv�ADz������ ���K[$�b�x�m���S���}�} چ��l�FP�t♟�묀,j�����8�!���e=����es���qRQclp��R)���ֳ��9v��s�/�H`4��2���7�Aϗ��|lgU[یye�Z�d%c��o�4i����{9�lcf-�1��,s�H��wN���1�w@�N��>�����$�u��f=3�D�aaV:e�4�~�䙍�h�n+Y:�/�P���]�he���=�\hWH�`2lAR�$����<[K�n�`���HOCJ����h��˟���F}�=&h��s���R0�4�)�|�d����9�P������H2����D5��R�
�F��J��X�F?�&J��C�OI���w�ݳZ3�� �1(,�����p��Y�<�K�P�qv9���
��V|����0\�X������0"��O^����)ˤ2��<�9g������V:�V/+q���@lTQP��:�@ʔ_��W�Ű%��վ�);��"��g��{u��QC6�1b!�J�}��QDʃ4�
S��鴖F5�tgw�c3kk_�yѓ�8�a��^x!M����|�Z���H<�}u.��z����sj�ol
ar2��rcH�T�����V�yh��~�ƿ܊������Ds$mrg��L���+k,��c0�d�5���u��%n�^����e�ҝ�_��_'H�O*��W?538��H��4�����E���s4��^Т��L���Ge��8��S�P���^d�L붫ږ�#�B�#'�z!�i?``Q�	�@��żF��8��?�j�9�eڷ^t�2���k]c,�Ҍ�����e-��Aq!`��kq�6(-A��-���zP�%QM��/G`�����t��^X*0'0��sb�yv���w�צiZ���T�a,.B�'�Y��|2gs�*�,�L���@�×�Y�V�Rc	�s��V�f=��m��Җ����h6_0�1�P�Aܫͫ׻5Cm��Xe����>�3�{�N1�.DZ�*O�����,�CC���۷o?ikk�K%�Z'�:����R��L2���m�P����=��X P�9`U��J.�*��ɋB c�$aB�HA
$\0��gS�{$����_���+-�ߺ�/o9��z⹤}��7���ƚ�,� ���>�_�	��Ɣ;�Q�߃L�"2���R��3�D� �����˷�5���DS	W k飐-v�U��1߬�ұ}�V=��wb<�vaA�y�'���#��ߏ���&f5��I8j7#8�������DGYr�S�@�Io�H�q
�0M	O>�����o��LX֮�L�J���;�j�'��9ECZ�|e���H_hƌ\"Q�@�UWWOPM͔nl�/s��9���(6�m��pl:�n�8���	��:�����X�ݲ��@����	���F��j܊,�"`;�mB�Q`y��V*�6��A&�6:�嫣0���X�d�M�n�uc�<y��/�]�I4��<g�f��X���a�gExK�-O�V1y�Jr�5��II&�A��VN�gܻ���=��Bz�QO��N�f�O�ʟ�)*ɀ��w��d�� ����d2*�^����X���!;�����
o�7ba��x���I���x��|�·Q�ì�N�m�V��f	�r�P�D*7Կ��S�,���U��̧$�ô�v�@�Z�g�[y;r3�ӽ��i�[���Z>_��&j�1�n|�s-���Y��s��)#W<�=}���Dk��b�������b?*������W��uy!�n�[�f���7�&���k"���єW�AU�^ض�~t���<8,(�V�I�^;������j�����b���+�;U�{˖BxÆ�j��v64��@�v#���U�E\	8((־����7�"�yJz:���ܜ<�r8���z��P5_w��h�숻��K!��ݗ�����C!�m��������ײ@Y��yM���wL4B�Z��$��������-���y��bQW�(B����ح���\:�j����A(\����'�a90��ȦɉO���GR�A���-���ؓ�N5;���{�K�h}��/!�'C{�'\lU�,Qc�:h?�!fl2G�.*ÄꊧY����G�-a�P���������fSD��P9�!�,����,��YR��c�h1��?5�]�:P͢s�x��+��E���t���;
���)�{�W��̂��O
��H����m������e�̙J�x�I�@*	���3^���jI9Y�l�k�o����=_r����80</@�c�F�3;���޼Ŭ��Ў'N�M���"X�6`�"D���J�r�䘵��FP]�ꤧp�%8c_�&'�KFAa���0���U�Z
��q ��!��
�%��3�LoN�=�+��ud��+���UT�(����̘�D\����Hr�d��*�B��k�jY	U�Ad������xX�����8�Ŀ�	�s�\0+R�I:�}[z�oEs;�V&�^'4Jbj��q��9G�@~��Ȏ��👦�R�ƨT���r�m�x��7���O���ef��gi��>�q.;w����?c��+K��$\’%����9�H�
�x�pk 0IK7���R�$��ž������y�aΗ-2m�(��z�b��W� đF/idr���m>���E������mdA�6��	�����(6�u(�H���ޕ9M���4[�ct���n�__%0�%�v��l��&�H������`��(�*,O���[�6�J�e�
&���6$��%��b�a��+
JqC�
���id����7Pj|�M�x���@�����:��7�b6̖�(�\5�rb��(���ʎ�s�nr)F.�3�_�������?�e��ڣ_���v�E\:�DX���`��x��ܝ�Z�Hg�zBD���mh���j�V�Ƌ��@IDAT?=�D��皐�r��3�0	�
@����;��D�c4���F��Nf,?��䠧���O!��V�3��P�;^7�B���>��M�϶��"�.G�9*��X �VZS8�xK��i�^����w�����۱����k�B�]��ҭ�|��!Kg�!;<������"��@���ց�]/RRI�{�EGs1Q�j�|�à�9C�&�s��;�5����X�}�Љ
�t�o{C]Y@~�r��Ai;*���⯐,rчk�Iv�M_y+U4�Pj��`6kE��z��;���A�1�s~���7�R�Ֆ�^�ev9Gs���qM��G����L,�^|i0V�׬4Y�'�|�U�V��_�lA�T�7��!�.�立5���Iv�oq�}pG|��O)̈́O+|����	�~���g%iֈ�p7��Y���m�t���Hn1\(O��e[�-0�	�ZA\dۡS��Hʘ�)#�w����z������~k��V���'!����(�<ud2_�8,��ث�v/�����v���ҏ�m�<�)2nh�s�m#���0�s� ��Yܯ�N]��N=�~�6�})��zI1f�(g�b+k4�ެ�Yb�@����;����!B��7C)bO�zHM
�@�Ρdk�>�����8>n���<~J��k%�!Nb��;�*.x�v��g�l�>�G�Y�_�J��%��~����+T��I��4+=����)�9�Y`���@I��腔��~����m�v{�6���h6��}s�@�0LU5J�|ٜ��d�N)���c�d���%�� �a�"p��e����A>��'W�9�nx4�,���Qa ����y7(���
ՙ��6����6����"e�
�1�-��!Lim��W^�O��s-pM-���V�"���s4%^� IgŮ�;�ůX�X(��Qh�P[Aɝ�G�6z<:x�鑌�U�b��t~P�&ɒ�k��3��Ȃr`;A�B}F�̘�7]-�H_����
Ն��&�GU��"�ktA>���G�q3�f��w@B5a��ڈ��^y��;a��lʙ��Q�?��,y�L�����tJ�W76��H�η�
,�y�Yi^����oΩy���p�)!k���q�g���ezѨ�bْ{��,c��8HLB	%!&K���M�Xۛ��R�4��@��,��d[n���f4�������!����\�I3���=�����8�(�S�
E͵qԔ���"C;��R�d�|X��"0|DI^�S����*�r�y6��i�tēNd!��:捇L�_p�D8��#q~���ފ����}u>��ܢ�]�y;���/��U�j#��ο �B�MN��?�_�Q"wf�X�-�v�l��5f;qS�.1(����\�Bx@�2'+���`h%qLi�'|v��o/,�)u�kM�����xF}��\�ǟN<�^������
�П���®��?oƷG��FR*�<
܎bބ�AUt�@���Ә��?$'��P
���P)�m�3�X-C��4��^��c���`A��4�C����|뎡&��xb>8J?G�EQ~��o�X��b�-�9�4L��~p)�a���w�=J��J=`��F�<b*����g�U���hM�|�U"{�mYA�<�����ھp6N	|�*�����~�DKg��}��"�	����Cik�,��@�|��*���a�c$n�������H����ǂ#Щ�|��� 'Z��?���Q�;��1�m�R����(L�c�is�m��)� �S�k�80ld���0/��0����T�7n8�^�
��%@jء��|�7�m��r���Z)`��*�U�l���v7W��Cmy@�i&��uH�@5	e��ls�G�E8_�-E
r�q)5K�\h٘��x�?B�o$�OK:T��1p�A�IYG�����/�5H>���D'r���l<>��O�������CYbm�Hq��f�jZm������c�/��Jy��.~5�냃}]��Fs��-�_��?7�V��`@s�>�"W|�;������O�l�tQ���A����}c��v��G���$�!6�&�m
�P@2��N<$�U�>���T��9��N�璺:��ӐN���n��hOc��A�vI;ǟNHӗ�4{;.��vB�
,�O��|��}�ޟ��br��ޒU����;=,�(�(IşB.�_vľ�
�GM%^\6��l�i��5H;�y�{�S�;�DK�^�=[	�kG���a���S#�����]�%����:�=��6��$�3������XA�GŸY2���s['���::DYs��S�u���=���o���3��	�@�=\�=��N��������~���ș*��&˜�~,c+�x�j��$k��y�1E�N�O��o��k.`i��Xqe��lc��
�V�Rw���߰ ��&!��w/ţ	����?EE�7�GsF-�`��c)�~�0i0�E5�l��u�Č��J��_lj"�̃�]z�<|�QI;�\�.l6"=�9�D0(j*_kg���HR5�Sѝw�b�{f[_��4��J2�\�?ǟ� �dx$wM㷨��j��"�d��Y:��xor%
��Zv�����0*Ju��o���zr#�=FX^Q4އ��oz�ݯ���:.ON�F+�
}Ȅx�0�}��8���"��ek&p��+��+@ϩ!��@�=9�fG��]���?MfG�,��u#m�]w�W�Sv=�E��KjC�L�9�F�s�^��%n�)��<>�A�V��s5/���Y�S(N��Ļb�su4��<͙���~���B;okz��q���|���<�����98�pi-I�{)7�fy��WV�TR$A�3p%Q����t��r�L���QD)��\
���N��H-����X�6��8�R�M��Y}���iO��w�M.U�L{��zhN���_���eEE��]-�n��oh�V�4feuu�`$���3U�{R��j���wz��y�7��q��q�8뭧qf�V�A'�!����ܤ�r��+�{nB}qH��Q���F��2W����bu�ڎb����?�\��X���I�7�|j��٫)޺
T�*8<�:�H��{����Dw�[�&��`��AIiu���z���%��1򮷢�w���v�I�����.�Wľ�CX�\!pm�3�[k�d���Ѐ	>l��^���E�=�d�њL�"F ��g�b�4�ԭ��8�����v��'`�_����Tʠx߬���^��F�֚q��H�4<
',e�*�T%t8_��N
r[b��\�nnX�G�?����c
J1F���
p�c�'�����:w%���Q�K�GDE((2��z���d��Y��
Z;v�c�@Pa��R�:��W��͔�G0!�Ƌ�v�C:ݜ��W�B����B�`N^�y��ܓ����t=٦2|��6��_�Ho>��y9�8��"�_h�`@/��!�n/��X���x��oIܯxB���G�?�E�_( �^��iu�`������������p��F6���u���,���=�;t��D��y*�)�Rڋ�/�,k����j�qx��w�]��-���)55����e�M��f��7���~ח�"k��yκ�����ݵ���C���
�>]җI�n[����TPB�52�x��3������t�vy;�M~cQڟ�l�R�([�r���B1��rC�;��yKBy�����.���9sB$4@��[��d�x1R�M���d��&�J:w��
�-�=��9x`��I��?f����l�O�xɛ�Ϳ�K�:��宍�#���ѱao"�.�֘N���`�D�M�-D��\8�'Uӈkّ�ÙL��r	m`��qdu��5kŊ����&��-��Q�����M�P�<t=�`S��G�%�H�:>�Rg`��}�1p����f�|��=��W����E4w�_�ݑ��4]#0�a��gOv`�/m�����B�9���C���bU�4b=���(��t%~Eп[���˖>��ê�V+�����.[�Z��A��,CG�����{���-A���K8��v�m8��`O^?����$��N����}B�$wK� (Y�L*$�%�O%���TZ[�[.���zâ�54+�'��І|��
d�M����q��i	`�Ừ���luF��v��J��k�,oyFz�O�m�V�k�>���wM�d^D{3�rs^��R�K�j
0�m��]����CQgfڼ��t+U��6",���!��b���W�W[YoRt};�[�]�����${5��=�!����`��O
$(ߝ�g�Tg�F��`�M@.��<��L2sa��/�J�e.q:����,8/�zv�����;�ӿ'H
!�^�߰X�A\�-��Q{��aLr���?�Ƽ���x�/�%�H�{�,�Ȟ*�Ō�Ca=o��0�5��E�\xR����}ά��^!�̯�K'\zQ��U�s3����
F���D}>��k �����UUC@5�v�py��IUJ�B���a���������]�u�g��9��] ���ѕoz�[L� ���~ɨ͟8���ߴ��@�������2�$����}D?�%�$�B���`��<�g��M�t���
%�J\	� |�pO8�ҢY7h��-nj���W�_�9Q�@�
��Ȝ�}���~�����D`}���㺤?�F~��@��������rIu9���y�"� �{�"7C@�9�t�i�Kp�М1���Xkoi���8zRt氮'�63��Y���p�p�M�dҊ��r{ִlX����9�1�J.�x���Ml��l��\��\ f��j;A��5��B���?4��^(Y���� �z���+��w��;���@,�����;�[&�&>���g7릁���q�n�?�v�7x+C��C��6��� ��߅2�N�n���M�	�HUQ/$�Kk�����H%/݇Y�H%�?똮��*�7^~�QtLS�S�(�}
a|5��f���/*�#�����+/�d��:Uȑ����x*�=�}~[�
�b33S"�d��J�2-ֺ�\4Bo,*
�<},D�@�bc)9�|8���
e�S*q.g�&<��i>���1D7"�$b�?�e�W"m��ч��d<m���ڷi;�����L��"�	�lY�AT���cXԶ/=�Uhf"�R��;{l(�ח�
w��6sQ��@\�{]S����d����*��%I��)�OlZ��.���_Oe�Y0��!��u|$7��?��bR^�y��9cF.$wOxJ��He�UV=���B��+|Ñ�+�](�2���=��2^|a�>�<�M
0|��)���^�;�o4)�[`��$)*C�Occ��=�"�w>w���!�c��}��6������n�?m��=����^�̙��bu���޶^��P�!���hń<O��|:�UbW�<{
~��/�ye��(N��P��'�<�*�&��S�a-sP/�$�1#C Z��z����x�.�֧�q�Ip��

���Xb�ډ%�r��,ભ��V���7��<3����[��R#������.F6�UT��@�o[-�3�ģp44��RTjKU~��3�{!��c���	��k�:�+I��:���y�[ug0�����nh֕@�eH�w���;�v��c�\�{ 6�Ye��rq����]2�M bccB��e�*�Y��![���*�Ln/����]�
�%^���<�f7�e��kymm��k/�+�"��	9E����^��	�f��C�,�¡d���
7��c��z���E_���p&#��u �9�p�QK<��F~�0�+H������'��&�{��s�L,H�P�SM+��KnK�h�Z@�����h���\J�|�����]�t�Wj�\�E9b�D'����/��#�<(ک��f�~��%��.`Y��(⭌]��kI���������Y~8��%�Fb��r|��5�nV�.�U7��R���|
y��+)t��`Y�8��}��!]���KB�B��AiѨ�M8Xt�e�F��0M��O
Nw��Ǹ)�����s���Etz5�*�ŐIgS[.s�˄���~�~����	� �0UV����aa�����g@��
�|��oT�Ri/R�.��h@�G���`�Z�}�rQ�[�eG�L�O
'�����-Cv�랅b�%��Y��3FQ�}h�<T�唭�X�#���q�C���-���O�BTts:9&1�E��+y���!�ҊAŰ���\+�<��g��k���'��sPǯN&��R�z�6 $E��g@r��3������:a�.GXՙ�0$�탡��?���}�6X��J��F�m��R�
��j3�p�����m��9܅�
����	�y�@�Y.�<�j�k[�M允�j:�
�Hh�TPJ�
R��1����[�Q��6���e՞��ם���r�nO��O�v
�q��[i��3����nqr�t
|��~�ß���竿,���?���%�v��RVvZ�Ԇ)�c�F����U�P���p�y�Xj�HI�O,	c߹����F&"O|+"��\�h��DZ�Jw��'����v��/�J*��J�XK$��/�ȫ��(�
FU
>�
�Թ�ܞ?���ߝ�y�Ơ��j)o��ը�f7F�w�f*������AK�F� �,�(�	��hGȞW��Qɇ>�m�R�����t�����q��jh���F�t�D�*�:���d����sD\G��e1�?���v�p�]A�#@���@:�ޞ�7t��6D�\~����fv��OfLf��[K�#�3Q��*K�Ab���ֹ^Q�ny��(��%�
W��vS����V�q(�^��� ]�S�G/��FA�>n�D||���
�K���s���ˑ+�9�'�?r&{+��˲��tŬ�kk�2��v"��p���N�.�F$緹+T�o$9	苲�7�)N{(5d�j���9�B�+��/,r��U�?hQa���K-�y�M�Y�#f��ʪ� "�Q�e�Y�<$l�!ù�-T��D��l:�c)�,J_�Cw��ޢ�������B?�D{�_Aֶg���1�g�@S�`�͔A�ys:�"�x�FR���n[����M79�q��JO7R!k3#��ޤ�O�.2@h���t�J�&�b��t�Yg��4���{��84���݋��I��sӆ�
�&�'��s��bx��tv���P��<���"�`V��ND�&��Sۇ�Vb�Rj��r�f�M�	��|�'��Sm��}���'B�\�}#�J1S�D�ɷL�T&�wg��[�zs����~�)��;E��#��R�r\��f�b�Hd��r��ٻw��n�fu�085j���$��1!<RCEH�W����C�F�F��'H�y���*���Q(K��ٌ��[�M���
�������hwVEeP3�(Ȓ\.�I���N:��+,(�m"w�xp�(P�B�ۋ�a���kX�w�	A�洎Lo�
^9g|�U��
�!`�����#L:,*��&(h�3�Zx������w��T��/�
&�sQ�/DE��.p�3!A�a2�s�zfK�t�9��㐥&�@K��2v
�$�۽�{w'ϼp�,H����L()(�O<��uIwQZzrk`��B�Ja�UyW	��ˮB_s���,[V6M�z�2&Óc���3#�S� �A�6�A�w�J[��T�%�����ލ���.̂����W/�+��KD#�,����ܘ��466Z�h|(i�W�h��-�Ql9喏	��p�71H���Ul�
�S��qo�C�!�e�A�1,���<�/:�C�g@�j��L*qe*%*�^�����U�x�P�j�uq�J|�̣���s"k.)�N�BnZ�YE��dxz?��^�L�(]L�
��#�r
����U%�h��5�dU^�o'�²�n��=��p;k�w��ۈ�8P��.�b�
�����tn���焨�<��4��&zw��b���
�,����h�sV>W�����hxh���
M(Y��EJ�����p��-��9�4�gMu�!5��Kn=�<����ǩY����^`�� ���U.0d�|p�����?�.��w�:Teh�ԝ}{~ii��ы�_\$���I6���\kP��y$�ҐZ"��
����z�ʛv�c��r^�)W{�r��lv>>:��:إ���~_rd�^�վ�|֏t�؄�|��o���w6�R��
����.M3��V2	�M���<+��
2�����&���$��Ly�Uc�/
M]C������9�EF�:�qP��F���7�D
���'�	�#e�
�50����BQ46���]�B���#P���*صt�H��8�X[HHEƟF�}oOl��r�ą͉e�-��&����0�oc����X�hC�ɚ����5$	f��c}~�9��u���r`-�nޯ:ӷP���&xNaG~��L�T�h���r'�T����rMGV��q�̷P�������W���pW�B��"��y|�W�Bu�Z����%r�Bc��
8�X�~�3τ"�m6�*������1��e0s�t�ZZ�XBST�c�^^�ˀ�q@��EV��hC��t‡�:j�"L��ޱ�z��h�ճ�n�z��������J5ߞQU7?����,�
���"�gF��Ao�Ӎ�hl���y?_b}ݨ�B�*��~̆R��;#�u֡��]�:���W(CM�c譢"����ǀ��LH�H�sրݬ|�Ǧ7�D&�Q����@�P�a�M���3��-���M��p�o��ҵl� ���&O��m,�Y~~�t��S_���Rߒ�5���#T�Ix���R�vj�[��P��D��g[���U3�NZ�������7�
�+�z�P�T�:b�s�2��E����↮�	�YE�]|�t]m����5�0��[\l��� F/��6�q�#���j�����V�i����% %~�0���Ȯ�n��n:�"�G΁�d�JY7¡��k/+�[1߾�b�OL��f������$í�~����9s9o��6�튪�����ߡ7�,Z7<IDl�����ȇ۫he0�m�����ა�@0T�`F=;��+PN]ͱ�?\>���{?�6��LpA��|�@������	����y��<ݰadf"�כ;t��,&�AC�'gy������{�ftFM�(�۝�B	��:PFP]�����HFUq:s���ц�Ѭ��f�F1��;��B9���Eȝ$���W�[If��p)Y`�A�	nf�b�E�F�J�c6�;'͗��_}��;��
m٤H+�
����*b7Ɵ���8Y[Cic7���݆l �ٳ���0�W��=�B�����e@�̵�!��5��[���4r����a�~��%�?����ўT�Qդ4O/Rz�7�u�p�����64�BQ�Ѣ�H^�H�wt��%�б��GN����Ԫ^���Ɗ�>�h��:�p��r���
<#NQ3ڋ��'5z�s^�#�μ���4h��1͏���k#�zn0�)r�$m�\�ޅ�B_�Y�u��Z�����r��Sy��}�~��a-�؍�U凨�|#�
�
J��-���	n_����y�0�ij���౮�	t��0��l��%dS�
S��P"���l���I<�e<���n�B�fL�~�y]t���&��"��7����gR�[OKtk[��O��#<v��}��u�v���fA��bw�gHA��Lb��H-��2Z����m|��o�
kS_L7h���e}4�z���
������1̀����i��m�T�ʏG�p�E��yH�x�5��@��#�}�ܫ.��,Ddp�E�Tb��n��S�0��JO6��#��S�E�;U�D��2��Fͦ}ﬢ�ܧN��VAU��EK\f�:�Z��]i�q?�o���]v�_�q�t��mH6���?��j��FS�PU\*��a�jy��	<�~�O�<��_�e�vnWFQ�J�~j�L���i�A�I�
�\>�A���7k��4Tat���G!U�w6�#`78���ñt�`vh��g,�F�S"4��(�AD$�L���&m��w�"Z`��w	��Ol�q„�B��#1�@���(���}���3v�*U*rR���
&Y�����B_lcR�˫��^ʿOL�9��s<{o�og��8���R�o,FM]\��M&x��O�����]m���i�›oY��	eA�^�,���涾���"��#��j�܁���L&c�F>;f	���.�Y�A�MQ��.kj�m�>�|9��4��O(��P�~�c�ٛ���Ƶ�I_��gA���ܮ��k"F?�
e�+w0����c��{ L�.�÷y٥@�I2J�4}J�/����"�p�Pd�Ǒ�NW̓���:utq�څ��
,��|k�
o�
�hZ&��Q`�<_y5eha>u!s]Ϟ�=�NZ���KݢK��1�fq�|�݀�W�3�hn�Ag�ʌþ��S�'��]�l][2pɊ/�#G_�I3y5y~Ԃ�gۓ�u6nS���ʔie�*�\dǟ>P���5]�6�"ݤ���p�NCvLù�=z�d~%R�[�B[�p��h�6�pt�~���O�ν�f�=çcGT^'����oG��S�$rL���o����L���q���� o;�7�]�ji�r���K��L����C��5�t�Rw4�����.�X����F:��^g�xw��W�	�Z����p��}r�k�18+�"ס����J�B+n<�&1�t����s��:>k�l�`1[RJx?�%�}W�FՎx���L!/(����0:ݞb�3�����Yƈst#�	�(���B4����|�S��PiYjHQ�v0=ڣ�6�E`GA�
.b��aQi�e&�Nd�<�T敼�^e��o���@8�K��*���2�O��О��_��dJ����#��@�m�T#�6M`�Fs��H�;D��ɰ��'	�%9_⁶$��@��R1ى|��,�)w����FY{p���v��g�#$��.(^F��*8*%��!O��~^�l�,AM��t˧5��u�/cG]��x�}l\ʣ;���r%r�K��E�i�]��4}�KYʸ�AU(X�%�
�'��U��4�.:D�u�S�'Ήy��T�PE/�|�=��i�.
�i��=|�r��C��[��P�M�ů��	��x.F��bt�͔y[�H*�U�@�
Id�.��f~�F��/sx�{��+q��J'��kW$��||ڛѤ�ԵY	�2S��?N,��K)�V�Ia{%.���o�w��zo���A �I��A�ː.�,س�}�];��@e�r<8=%���4#I�{��
%_}<6pjAy91�c�
��.c0��[����G^_/R��`�1��i�W�/S��OEA��Ǻ��0�]e��˚LE�Ʉ���ļB�	ac��|��m$��{(qN�;��t[�h���`�����6�C�7������9�/|J&��M+��7�K�{]{]�@O�M7?�<�|��H��C(���Z;!|�֍�֗����C�m0�1�b~l��$J��/�H(ȉ��^H��J�ۚ1�gc
�6`b��i�@l�)�x����3�,[�M��=H�!���^�&�c��;JKI�欍��Ng�`\,���Бdj�����-�^\�r��d�@��.pk���xs5�N�N��b�q[M5~+-�l����?���̓�c�]�*,�X��{�ݖ�ʏ�~:	��68�x��:c|u�#%�#�ex�nw1w��S��}3��ק�fT��"�c�F:c��i���i���
��]����Kj�
ɯaA7��Ã�ۛB������
���_��(���t���7D.B�y"�����%�P�~	��l;ג�SjJ���%�l�Ed�2-O溦σ�ϣ$�Y�Q��Zh�&������g���{����v �/p������ve�	��*/a�B(ޮ�[T9�k���j(NZ�7�B�N���BS�88?qJ$��Zk�~��mB�x�y/����̨�`�*�sH~��:���ֻՌ�XR�n�KT2.+�,_T���PɄ%m
�ˀN�ऽ�.�>	%��J�R�Z����Q1��_�H���[T&��n3�����f }�Ȉ3�6�k�i����B�c�uCO+���lJ�"a�7o9.p	/񮅧Of���_I�o����j)�vix�M8�dIC錁t���[c�@1s}��]\�s�vZZWK]8�t(I��<��#�a�3Ń˄
F��i�+]j6E��n�7r�XK���J���>*�[�2W��G��ܯ�ҳqZ
�`~����M���/O�����5b�0���p�ΣSkg�l�zo{�����'ZZ�V�)�B����5 `3�� � }O/��_t��s��!0İ� 5����v�<�@g���jk�N�(o����J��2IՅT�&-�M\SjB��ٚ7cA�P3��6��3<��丒L�x.+9�m��uן<@Q���pZyn��H+�7HηQ`٣�u�%Bj8�h���զf�A�M�um}�KkKzG�`��yݏY<D�ҜD�S9�[����a|��HD�0u��A~�����3C�L��02p�sb���e�/���tY`tHO��i5<�+��L�ـ���h��dL&Wv���Kݣ���o�<D�u�伊���
J+�@H�+�Mg{#�q��-�&�S��@�r$P�pZ�6Q7�d,�\�PƹDWRn���&��]
�F��G��p�>�W����wZ	tj[�N���w�s�E���V-�WZ�x-c�z�����=极�Ǡ��`��㚂�0�E*����G�l]�E=iE��n_��7���ƹ!x	s(�៸c3x�ҳ[/��ܨ�!t�ڋ�M(S�5�VW�+q1�7�09|��<o���$���T�M�S�
>�B��m5 ?����1X��a�L���T�v�)z�w��`��3v{0����B�Е�XϞ	9�n[ܰ����H��$�rʦU:����ȢwvZ)���G��t���ѿlqt �f3�>�8���"�P�@��GdFtU�21+���z2�R�[~*8��w��ũ#k��˗��!�
˩�2o���q���X�9��do'}pze9�d����gf6�,N(���=H��)�1mY����:�A�?�O���75H��t��	���q?ͩ�lZ�r��я~h^�ϗ�T��K��̓fF�4D�Q~��P�ra��xyE �X��o������H�%2v_��vfG�Ε�;�(ZQw0��>N�-bLRMe������
+W�=p�z
 ��-�լ�d�鮟�h�E�B#F}�<�c��xoH�2���?�PߓC�n*���Lo��rm��~�Y/=7�*Y�܌���t-�������Ǒ,A����.BH��*�,�@*��fk(8y5��y���G
�Y�2������~�ڇ���|F�3�. F�Ѳ�RŐM�w��y	e�_C*�)�ƚ�`��st����iE�Ϭ���٣�rg"�����1g���m�o�]��A�0����sIш�^X�w���J�O:&T�7�w����
!�~����.����ܙ�<12b��|����Ni�btq+���?dW��g�@�f �X�؉�����nG��������б��˧,��{�m�H�r�=6\R��PH�$J�X*f8,�8��я�^##	��R�x�3;��9�`��W�v�W����T�v��Z��P��dC���|�i���y���$/�R���q�${Q=_��
���޳P}��j
�o]�E=�5l.,�Ş����s�'`�qR�t�n�u�ĴՓf�uFw�V���PȦ0�S-o��z�*����G����|	��YV�-V��9�F�(m%���U:���4�Bf��a���F&�
JY��Q\��ӐzS�`9K'��xf#��M���W���g����Z�~%���Ԁ����>>��G"�Jb*�sF�
��&	2x��� ��/���
9R0�k�P.�#|�ѡ�>��Հ����g�Y�7�Noogt�#J����p�3鯍8���h���:��)<1u�?'Фe�MA�{��
�I�WW��%�H(��lU;?����h��s��$�;x�4,���m�ɥ��Y
yk��z����3�=�]��5ҙR&�~T߿?�������zKk�ӷ��c�_v��r~�O��Y�=���V5��$QC�Hוw�6v��#x]ҏV�һf�cg_�HO�3��kс�"�c��/� �-�x��ow��đ UF�q��,���<ho�w><|4�@M3ݐ/Qք���N&��ƣ��p�<���^��RK�\��o�����g���ߵ��Dn�P� ��	�4ԓnC-�֩S��]���H�?W��:��c�`�mH���~�o��2���M��`�1�IFy�h�Գ�܋��}y�Mp$�ۚ������,&lz<'��s��^�lu��=mFT%��]�J]�u	r52��]�at���7[1K��dP0��,gȖiO%R�V�IH8����%�HϥX1�'�ᱢ�(�T�����t�l����ex!�� �̯��2�Q�Ѳe˶#���W{���`{�wx�Y�(Hi뙄��U���ə������r��Y���.�f��y������#+Vh��OB����e�r���{%Q�BY�e��ʫ�/��p�Q��ӵ�z��DӲ�
�a��'?e��`8�Cgg��0���HS�ͻ��OcЈq�F&��4;J���\����-��(�9"�"�A�m&��#���;�Ŗ�}w͙3|��8ی��6qra�I�ץ8+>��@QK��F�u��h
քN�)4��,a�N-�('���O��2��|�h9׿7��)�?��x~/B�.�,�S�M
e�fݣ���Jˣ�v-';�	#�?�\����ŝ�mtI^B�(���h��[���<բomZ�\�e����:�����H.n��\���@5��(��m
X���(�ɨ�@�R�&��\��5�L�{5��w2Sғ�my
jlv�����m�@3��i>r��
�� 6S�p�鱓f�w��5P+��3�r=Z.����
F������#1kȦ�!��D��w/ՎTKJU��#'�R�A��~��?���2�WV�?U��Nf?����0��{g�@x/5HS��]}xOT�<�0lE"�J��*5��0
�@�5F[R�lR���w�Z��r���/Ϛe\��i�0�O��fw�Db�&t3��s�K3ֆ@�$C�ݖ�6�Zٛ��ڎ�BV���ˆ;i*x�1�	�!�C4�܁n�	(��X,u
E���2�-�g/��V_v�#�ɸ��h�gA��G���LW���&x⻗;"�j�q5O3a����yCC]�����0�ԅx�
�"y#n0������[�70���W㯬m~�	+��yސ�V0���@>b���zȳnv���˹��po{���J3����,�e��.K�X�+k}	�=!ph|a�m�$��d���H�Q��)g��
y�����ͷ��+s�~�4�ᅕ�o�vFyF1 ��F�D3�߆�9��C�1�"QӐ�.��>&Z�\t(j��h��0���6e@IDAT��Ȇ�!%2�IC�^~��ݺT�KX�Z�}�{U�twr}�ڸ� ��m��ģ�qޗ
��:J�Xp��@��u�g6��o=��Mk�]cr��1
2
-�Pn�v�<����X�U��!֝��.r�?���*=}G��A��}���ŷ�F�2g{�R6�ӆ�(��q�k�k�45~*1�
mӲ�y
��A���8����~��0��P�iUE����4ϛ��p:_�1�zc!�b����<�;5�ى\��k�\!��N0,���2�W��[�!C�v�N4�A��4�'3����yMK��촳LM6�.&-���;�t&��f�[$�u�H&�N��|���"��ޤ�L����E�!X��hS��qj��L����w��;@�I����
;$����1���%��B�h�4PS#��[��e�bonΰ�H��l㹬���ܗxO�D�[
�vq���8�h�
��Tݘce�+р��QX��(�9{qV5����F�J3.�˫�B��N6�L��6!&��
І�[o�w�����p4*�)s�S�A�gRӁ��ı�0m%&�������£0n'���Bj���23^.{ik^���x�v�~y����SS]-h[mU!�;2d�\T���쯵7��%v s��z�'}�67|�4?dpDHɼf��O�ˣrƍ^CQ�TK�&�[���^��Ie�Yl���u�f{}�KdҺ��"�����FP��l��M�p��t���%���O.��W����
�`�	̌*��.�*��_^�m��w�e�
�F´���H��y0���8E��N�,��iy��I፡!D,�~8������VZ�v^�Ѓ���Ƈ��y7�k�00�����_I���ͦ�S�H��$�1���U�Υ(F��4���PY����Qj����x����z�R4|�Vc�:�<� ���J�xP�zs]P�Y�kL8��1�ї��ץ�c���EBx�-�_���X�-���|�r@�VS��K{�DF��M���n�4PEf��,�g�#+)�E�r�m���UM��$n)�>�Vy�T�\�
��3����4E�/�>9��w��L�~E��a���';X���䡹,�����iZ����B��.��ބd7�{�Љ�9Or6�>�䙸��-�j�BY >zxS�}p�cmS�q��/→K�$@X\���W@93�7��[�ڽ�{�s�Hk �g�p�_vl�t�"c;zMj*�=��f:�7���L���H���p���j
f��|5��w�B�/�\›��������U��l#s�H��vA&��睝YH��pX1��F�ݤ���ڊ?�Ǒ��h�"R����+�0�:dž-S��v��=zN��tZ�[F<�_O��걨�P{ڣ'l��AY`�\N4\x��z���VL�P�%��xk���R6#�a���d
����i���oH`]����b�oć��{8�X�t\c�ܚ���qE���|�;8�ܢl�����8���$��A��=�|ލ��_o�?D�4���ƂS��پ�!g��R�D)��3�vw�s*�G��3�@�=�8I^�#i�%�����9���E��n�l�d@�V�`'߄w{�L�j��G�v��I�n�����S�!�x�[V�[��n�їB�,���t���0��+m=���b�'����e9P��ǵ��|�I�|5ee����U�a^B�O��S:;�׍�� ��
�5�Uǚ%豻����������
�ơ�3��E�|Q��X��O��hd���/�ߴt�$dj�=�Z,k�'EE������){y�p���>��q�.
&� �V�T�MX/�5kV��%��0]]Q
��'s��/�(�2ƲB��
l��ETveѬ��;�{�U) �iny�e��B�"x�[�_uQ}}
�U'@C�"7|;
D��'�_;����"�ӂ���+ٓ�
�>�0)A�1oɢy��Y�۵�P���
�vǦ�u-1"1��v�tZfUa�,�JF�e(�G9@�Q������;0��k�hr��A�~"4�#�b�!�>�	7~
��ԏ�{����wȒ	�T��n��;�2h�q���Kg��kUvҬ�+�-�'���A>m����S�c�B��QR��$���i-#JT�:�Y���hq���@�$�攅�Xw�ץY5 Z_�Y�_���1��`��I�NQJ�1�;�w���C��%�y^���zŗ���C���L-��)��Ҙ���l����^ɔ�3��Ҍ!w�s����΁X]Z�u� �����Z!�ZQ�g�A0�q/��(dן���y��d�Л�&����|-pn߸z�9�/�ɍ	�A��F2�)J����	�`��h5�Ɔ{�-��ߎ�ԯ�*r��:O�͙�T��Oʌ0A5�.�b���oF���!�3(VX�������qBk8�|:��{���# <e�?�g���py�*�!'W3~{�h����F��|�Gſ��ǛT�0XI8�=�
=#���k���Yո9�f<)��Y��� ���5�$ok�J���7��|u{�|Y�Ԉ�8Ob��*u�,>6�J/22�k-�c�C�3�d���R�g��Ɵ���侐s��J�½����C��}���J^�/_��6e���8�N1e��������R�j�A��h�~"��~Cz�!/߅!@��w3�_�(�GS��;J7��8�����#�	�1��~�(󭟕͖���gDw��I�s:�B��P�<�Y0����Qx��a^�i��M�3[#CVp��[6n�h^�����Y+�M��zq�r��<�����|8O�IacȌ� s�]�Zq�M(\i����<G��8�yC�&����v�D�6=�+=��z��9�fw�� �
�a�GC�,��S��WC�׿����=W��8hO�aεŭ�o	�u��~ϋ�{�ʕ#��`V�
�Pv���Č*v9A2�FC3mp�Pħ���$QVy���AW�'�Rz$��V�[t�iU�MfR���t���{�mL��j�=��⟇2�W�Ft�֮��.ϳV��aTi)TZ�(�:�gq-B��h��n*����
U�P�1����v�3R���Gb�,5�����W�O(S���-C?&$�L;[F��%��4/-�b�ZK!��٬��j���v�����]�ύnK&�
��?/��{���\�ă�S�@{�W�	�ȃ����Y#c&k���ާ>�t�,��P�W�F�TR)����"��Sq��a�zm`4��خ*���fҳ0.'��L���5���㢝:S1x��Hb��ޫڅ�'~��f|�Kv��R59��š]����q�dϻђep�Y1�s���4��d9
c�W�f�W�Y����'�i(c�)�-���{6��?���<g��U��!�]$հ��X�!��w���@/gE��QC��77�p�xʸ�V[P�!�i)��V����W&e��1V�1@c���#�CA��L��׳N=�.�d���;�-�._�e��F�N�o*�b;.�Z��/�"z�6ֵB����8�";�n"��5E^���˚#G�o�PP��a��қ��l:�,�~yZ�?F�?ɬ������yEs纖��G��"� �P�>�F�a�Sc:~���b|S'z�N�gj�v�P��0�'XZ]k��EL,vtV�]'|�К�VAU�6d䴈�)Üs�RӦ�&��t��X����q	�u|6��N�c�v&)�x#�oʺ삉�=��b�5��K'C
����eyeE�d�R�f�@Ę�k�fC�v�p�ȪÃ濃��ip�
���
Wo��-��]���E0�YQ,�&�
y�k���s�)gb��Ouc_d�7h��+��C�����/A��&��,��6�i;��灠�|w�U�!���+�~.v�駚f�8������{Bw.x��/�c#��/�4�G�j䄦&R���i
�z0ӭ,r����C���r�����c=�Q�+�E
����ųv�-�]���{X�C���G�l�ɦ�ʜѶ�,'���]6��ف���6�|z���Ug���u��
�)�`�-)EՉ0^�/�����޹!g�j��'P��6��H����]��+�;�
R&��,0ֆ"�����A�چ�>�Ɲ3R�;��l�����O�Z�C`�y�a���!�j�@��>�]�o7�l��]�_;<�#q߄���)E$��S:)�%����;�N��8�`�3��e�F!���Ah�h���|8dn�������H�m�xY0�yꋑ�k�����	�=`]aؚ����a���A�?/Ɨ�o2]3@�Y%[�|cXB���ɛSjl��S<@�P��(�q|&}r�>�7���y't���Z����'N8i"5\��A��E]�n=i�Rz1UB��[Ɉ���1Ë�c������i)Z9c���v`ósf��s�}�_y�ᡭĪ��*mȑ�����‚�$kkSc;�f)��[?��LvF��[���<+55C&����w�
&N�A�A��8(��y��@y��6�v��t/��W�C=� ImY7k��fpx�*u8��YI�r�S
��\�E	/E�0���sw��|�����S���(�P^��B����X-xKE�8U��
7�-�vm�p�Ր���,�
�K*Ȁ8KP�>�^r�T{�~v�;ǟ��_ߑpl�y5�°��a���M�Ȏ�
tb,����C�����+�Р%��LQ�)��݆�<?��ag
����M�㨮��ڗ�[�־Y�-[�7l����&&BH&�Y��7���$a�/$qBBB	$a36�e��Eؖm�־����{w�U�{[�����KbL=�[ꮮ�Uu���+4���c��0&M�%#�T�t&К�y�rM�T��ǖϤ������^��!�:���r�%�x
�p}8�4��� ���i��`� "x��	묜�z�~�p6��%�u�>@�;�C�p���{[7�P�g(�"�~���m]o�t+�c{PJ�,��l�	��T D?>���S���f���H�%}�4��~(��!�};{�[֍yok����K<������9.��m~�[``/򳾖�S1���K�2�H��o�E?D%���o��Y��SX�ɶf͚�+�/oX?yo�[iK��(�s�7yFo�'?����Q̗+Q��j�v��ŋ�%��ƍ�K�/�A�`hYj@;FT���M?��������I�ũ�.��	�m�$����~@�o��F���}�~��'	E��E��#v�� �z)�����I,{w��3�(�"R6�eX���?e*��%���sY���ձ���{�&#���� ȅ�Ul�{^�����,���ƛo�PH��U^5CJy�X��M��y�l!�F�`��6��H��qT��)�$�t�H�%��?��*(�]�N�ri�`#��2�,�}�E�o6�'�댏�/
�Ռ�m8�pˉEh��W�L�%6��_"�gTx�~}�~$`�bw��	d���0XEѵ������JJN:r�U~!q�h.������X� ���02���Nڋ��T�w�V��^�s?��A�d�Ń]tte3����X�dn�,
��vWͮ�-��O@��T�'��#�]��x�z����5�d�����8��s�nT�S��]n�|�/<��eؙ�R��S�.���{i��DsV:���������[�p�F�����
����@C��\5��9WGj����*��F}�cٟ�]j�(pwMP�q<�MZ�l"c�¢���6>���@ELvF�p�UT��p�N��׃P����/-��V�?�ҥsHx���T�141���2.�l�O9�`V��<�P�;�Ƀ9B�\�/PO�#7����*<>��'���dx��o�~�0FpL���$����w�)������	��tM1E[���"������]H|�@��4���/�&}�1�$���&C����`p��nhqm�����_����
���x$�M�,n���^���ҭ�~vV�_�(��4��PE�;[����??lCa�c��qͨs:i[v�H�^	�Fa���in?�M*��=�s
1\�~��~]X$�(�(]����K��8���x4�X�k/�b{��Gb�.�[���sX�J�5�iO��7��������3�B�
�$��*C��c?g�d�'?��H3��+z5��&(����{�w��s~�Ќ>_�d���{p!�k�KD�h��3ʫ$�elZ@Y�N#���g��
�R���.�=a[mDi�۴� ����ە%%9���z�O
c�fy����ζ};0�_ g�u�f؛9:{k&�(�%t�ٲ�9�#�����D��½������o;�9%SoF���ʁ�6Itw9�9���P��cp	9��<�~�̛��zn�S��0g�Թ(J]�*����Κ�;��~Y{F3�&'~��˰:�@�x��������C�ժ}�c�i�FqB{edZl���5X�@���ĉŠ^�Q���U�!W��~a⣧�0�♹C�Te6k�?������8�>��jn�ɷ��+VW@!ʮ���q��^��Bx�22	Tw��Dg�R�2s�\čk��/���M�\'ax�+��I���_0V�=0v��'#�̣���t�	������U���IBrޥ�!�?g��Fc��mv�n�
��TI�E~�%��B��Ks�5�?U(��x�T�핸��ŝP�Y@�]O��ܞ'����!�LD���̵yFz��:<�r��QF0A���ߪ03�XsyJ�9��-�H�#�`�W������2y5�n��7-���'/��b�a�G����orόb_���:Ab�z��rCp֌�
���}�K�%�Ҿ�]����,�E��%"#`��;/s�8�i�|�:aj*��j
��*�T�m���*��m�?��
H��rr�k��)� .���M�$o²?%O����o�{�-0�>��I�p�_���������맞c�'�H�]�هZ^Y��’�\�=������@r�޽���||�Eu��.DBuȕ̾V^���F���*��h+6B
u;��B�k�O��m{��pN�/i$��n��zs��#��Z�c��@��LO�!����塡�ˢ*�ye���qn��؝a�xF�l�X&{<���L?��	t�P�oW]�����e4"�AnS�G4���*�s�H�\
�g,�2�
qz-:�|�><��No#�ճ>��k5Ɯ;{�U2��ȉ�!Op�ꖇ"岜��{��\�@��
�x!$��P��cv��c]�k�
�&0��R��h�f��3m�&��pe�_Y���k؅�>���i���cr�^��#�Z.�8�rG5fB긋\�1ܯ�s� �����<�N�b��kƄ�U�'3hJ:�ˀf�-}��`�~?�5^K�~�ȡ����dPl�'����h��:2�fĿ��Q}�iu5�2��Y3��y��3�J��5�H�2n9��I��YC����$��q֭�d�����Ԍ��
+��V����J�v���$��Ƣ�u���r�ӊ��Ɗr�ƻ��	���af���윘�,N�;}�����L�=p�h��O�bl�
��W_�
�m�N��r/وKh/;i|���X3��� �OW��fs?��G�&�*�%}�H�p.UҊ�<�o}˨	ys`v�n}
/!R*��h�/ W�y\�S%%�33���f��KX���`Q[�,'��||��+���4X/�T�p��c<r��V��l59`�/G�.8�R;j�>�nz��$�;}Ad��o4�JG$�	������?Q����<!�V;-�]娫�G�Xȁ�!,q*LN�j
�0}�Hj�(
��,�7�����*���xbH'��+B������g��X�
����jD�vc�@��^xGOg����;P����VL��W��&�2�2wѰ�q�sb�/`tz�HL�>Ѷg��ٌ��+é��m,D�`\�/i��%�NE��+0[3���N<�%����rh��;�ѽ�9�_t��~'�G��N�&��Tn�*��E`%�St�;% �)HJ�X��	F���e��o__lH3�zAfc|N[5���
�2��n]ֳ��G5����t)gȒ�E]G6�t������y��r�92�^��O�#�.�ܴPtt 
�l@��Ԝ�Ah'	�m��Hl�@}����ٰ���d�_��$�}�o�����k+�{a ��?jm��`�}\7��Zo����?���5�l�r
���']�$���Lg���L�سG���Ġ`Z�'rP9�݇�|�o�	�z<�}�6Ɇ�;�
�$3����'�)�:��ぜ��8ydiyE|U�����{���k�G�t��)L=���.)�J�,�
��2 K��x=��k�ڕhh/���M��I
�u�h궻o;�ՖՍqw��_C���I�r2h�^�t�B�1��������Þ3�K2�/D瘌Y+z�ꭟ��d��yA���}=�H=x
$�ê����p�1�7<F��7�KJ)��Z�d�+$Ψy}<�,!X�.
�>��[�E	��H�=�Hm�S����c{%$z>�rSRt�	y���ŀ|-^|�NE��Z'RO��\��6 �@:���a��r�ϐ�_잿�{��~�R7Q���˗"�7Ӵ��v(б��BLz�.k8H	R+��/�dh%�(�Zm8�2P-�`0���ԫ<���r��@����
�$\���Z�l�*cEh�b3V�@�WYcC6x�)d���:>a�L��cw��9�����&wu��޸�2Y}u �����Fk\e����=�2������s9��@�\���w1� ��)�,
�Sf�T39V�u�zFZ˪��碚�1`e��U)j��6�匍�J�:U�&�G&A��G6o>D������d
a���>�Up������Q�t�jY�1ɢVk��Kd�{́Bq���UW�-���K
���.pɝ/�m�&�f�Y��
�A&�=1�����Qٽ����x�Q�x��Fs�t��d��:�G�z�II�����H����L��(ɟ���2J�6�;�K�K��a��0�;rj��H*�R$~����p�D�c��c�7��B��m�Qt�G��B���ݱ8dZۉ�����sf|e(�
���DvR䅬�r
�S�oz�՜/:h�2�~��c���X*.ÒQ�ً��M�&@!��e���'��y��@�����!Q@�ć��#�ð�@v�(��x����'���"�\�hQX�47��'"U��������'F�,Y�g�2ք�w=*7�<�9�kg�:�º���~av��y����F3=���c'�0h���K?]b��V���郐��c�r��M��ڵy���Qa�8*
0j�W�5�>џ0���޽{
g��C����1M�]tP�5W��ur"}�"�Xwd�5�
DeBN�ذzC�q{@ �����h<^;���Y>����~>���+��5��_��IDH'G�z�-�07��3҉��@~N�G��)����>�K�*=��P��
�H%H�"�m{4�;����K��/�@�ao���cz �up�{��Aׂ���
=r�f୻�ɼ�u	E�%�*���:~�THF4�;�VpӦ����(��u�/�m|e,��Ū*�Bcc ���o��*zƱ�6B�[����lb��ϔ��W������+���=�lΣ9+��[<&�v�V^�i֪Ry0�X脠�$
x������^~&r2@mP_C41���|�>�H{�oK���A�L��m|�����2
�5���+"cM-�4�����NAn~�h��M�����W��Q�̄�}q�/eYꞪUW]����!_/V'zt�|+����0�=U�Z��fthM9W�K�t����AR���]^�O5�����lOۉ7cPOk��./�R��|XGV��ص�`́�%��È�~C�s?,H�����܌�V�z��nHX�ΙV�k.���Y��0�ZAN(4�'
K�o��}����T�><3I��7ݘE�����ߙԢG�����ٽ�j��/f��8�Ł�Ea�|�<s~Ig����X��EeZ�@�C�UZ�(���Y4	%�_�u����x�:8����֕n��#x���"(�G�l�R1�У�<���6_6z�P�KgEI�1��ۋ���6���I-?M�@�JݺuS(r-�\���ǁ�"�}
�뽀n�M���CT&v�<
���.dl?n�w����e�X�A/���f���8j�B�r�K�"��j2��J���Fڀr@)S����]��r��l�g9/9�{e#΂�H&�=8M�/��ɍ�>�"oe�!#>���Kq���:k�3���?l$����?u��}ގW4�6R�(�)�E�bF���N*L~V��TR�^�!�@�O��f��L��3�JE�����"WA��h��u�3��sxWʎ�����"G�z$]H�{b�o�D���8x�G֬��^���^ʦ���W~*ׁ�8�
�v����,<���}}�����ͮ�Eb٘��0tYU=�M��g|�)�Ы��IY�E�z'pb�+�]۟91����&e}Z���'bif�y���q9SY�7�5�۩վ}&b�L7�r�.m��[?�|On���qZL�:�Ͻ�cF�g�n�վb����?��st�,{2g
�+��5�<�(+��Y�5�&7��X<��Veū�P�q��-C�h�SDŽg�%:w	�:�k(
�6�^J�?�֊x��a�F2��1�L�wΦck��ȣ���6���S�ޡ��rp�·�Fb�f�����%/���Y�rr�����a
�g6�>:f��
�s1�����u��T.Ά52,0�J��5k�!��Ⱥ�.g���UjXk���#qMҦfp4�
��HI�|lKٔ`I.�����T��c�B��C��^�.&��R��fQ�7u9Dcp�p�:���1����$�:����F21�gV�����j��{-7WBp���y�8}���U���T��E�"�.���X�-c5#��eAI���צh9�a���C	�W���c�u�'��n�+#��<zH�D�Lj�?��������%�L!d!L~D2}��]�
g�t#��BO͢��x����^}m�#B�
*B�*�D滨Z�!�n���*�z�8�fȞ[��m�ʼ�����/��.��\E�H|�(�"y���,f�S��#�U�4Mb���<A٧>�ME��M����0�c�9�yf֋
���&F���3/9��:w?n�F�ذ<���s���,^,� ��trK���N_%���5<����Is�#�	҂`v7@�gs���g�'�v{<�֕,��5���|�.����@WY�T��<lz�~��+D˽���7��6�:��|Q�v\rmS,�1 %�ZI��l4���="8F/�Y�����{qi�D�L��dt4�sl,܊x��7��h�	��/��᳸f�K�$��+���w[=g5�b��!�s]-���&S���Ú�>��"4��NY�7O�\�BP{J����P�����X�?Q\a9�n=m���O�*D��6"���T�����B,C>�3fo�1�eN
1�Ϯ�����sQS��$�B��[w�o�S�W(]�♳��g�ܓ��᤯��~�<��M�����C[���mN�PW�����*`ۡ=��"���z��n����i�A�
��B�C'�`�q���d+M���*�ٝw�vN<_�G}�!i	��R���3^7y~6�RE�(?�9�֑}��3ؼl���O��x�x3�Ԝ��+	�c�Y�q�ɸ�LF&��{���Zs��?�Xdi�u{G�^�bn��H�9�Q��	C��x���44^/jZSUR�@rsn��~2L?b��/�jY	�0�e
�_��WS�m�:||��H�v�(u����J�۱�a���!�օ޻
�;r�u4s��彎q	�X�s)��+H����&���󛗥M�HP��["9�XkX���v>d� R<�{�{�H�%�b�E�uc��=��)�E�
Z9�wy}f��6���`"��НJ
�Ǭ�ޱj�T�����1�x'O�3gފԳރ��`�|�J�����F}��D�L��}wcf�v��4�ؿ�h�<�Z��/���;��j�Z�vX���g_O�4g���2u+��0���s��m�IY��[�+�$$��v���	h�l��� ��J.L~A�c�������v�8X�h��f��C�T<3���)�����D]W]d"]�3	%ɷ��6��_Q��
!���}��/^BI>4} p�R,�����!���/�X+U�)êbL�V��ٔef:�`�ѧމ���Li�Hgx&l�\��X�	��SzV�E��af���=��emE�Ad�H{�~j�\��;6��z����vߠ;�+�Ξw���s��Ɨ�'�
.*�/��Xg5�W<����p�?���5V�T��12��v򴮧<�u|r��D��m1�+cSA��ۅH+.����{4��a��"�:<SmR�)�d�S��/�sWI4���q(/��G57?�����W�L��i)9V�' �����o�eG��Я�S��,w�mY����sz!5����m4m��DXF�Nf��W�ٱ��x��E�є�*A�i%	MY���M�����X����EPy9���6��gm-
�`/�x�I�$W
�Н7���_䶼�5se^	�TK"f|8��^w\w����U'
N����4k)�(�~w�:��ྂHp�p����;h�����.�V�_���%�j�JG�8�<�O\����|嶒�ߣEg
��/�Ij	"H�P�b��C�$(�E9�����m�>X��a�֧e'�lz��_��/�k(�.�//�_u$�$�Y�b�,�G����<��β����	tj�/UM�1�?u�ދ�p���^;��6���dBF?�_��
�r���Z��ޢ�z��!U��]H�%(��1���0����Q�I]i��9`��މ{B���c�.� �B�$6����@�.�1�:��P=�	�
����xa���>Ԙ�C߸��P�\���q���qOG��"ǟ�޻�-����0:ec���Xj�|WK�h���#�Y���'�S�dz�cee����4(�h�{;T���Qq%���<�8#���ﲴ�/
4��e�R-�*�R?ߛȎniF�oz?L��֎B3@����\\TM}F����m�D OA�3��*Ŋ�!�wq��`��B`�˼bM^��,gw�2M/�.%���WT�a�_�A�Ծ��>yaya'����wDk_Ղ�
�m�v��'l*=��<uSN�_G嫗���W�{
����(�<��xZ��Q�ţ��{T�][��ͼGM��W�}q���9߼9)@`z�g��ֱ,��3���pޏ	��y�	�oA�}I��P��aB:���(?�n�W��-���s��o����s�E1h^��S����v"ddY�@C��4�o�|�[@���l|/�y�c��+k��y�4�l;R9�;���)�K�<���2��NTp��f_~��F��`�P�s������^7�V7�w�
�D\J���CA~�$g���^|%�.��@�T�:WS�O�A��Q��J�Lv_��O1��]�0&�
%��#d>���*�� �Y���Ć�C�r3�⇿�9�k�g��DxH\V8<#�dt�\+�_�u\(��!u����	<�$•����};����e��214�[�V��w��%��w�\raH��D�`�X
d�b�/6�r��*�DD�%_��T
�}��d�8��'
!���c�ʡbÜD����x��L6f������mHl%Ƶ�ؿsl$�]$يQH0��q���5�@b`KJK��O���tΑ���i�����е��ɩ�<g��Aq�j��;,��s6�_a���T��̈m�-���
�Nc��TF����
^��H���$�ߢ�r�̒�R���5T�<�0r	"[T�s���z�@�'>FA]@��C�N�LPg�`
�,K�zUmk�+���Hxb��j�����������fm�T�o��'�
>�a�rn��=��*�(�0�K�\�d_-GYMMo��K˼�&_�/���y;��ՠ���M)��MU��|
��P�H��#�[��
�X��[Q�m��ʢzĶ�W��
ۺ~`�:�n�d��g�����g��+�5(	x��iY+1��~�א~-�:�t�i�g �#{ªM��W ����]]�;��)�J�Sǎi1� �Ё��d�G�2��\��2��sm�i�{�J�܂ȫ%D��K`5T��o�$~�3t3������c�1�|��;��U�m����d$7y͂�öj�9!��7�?�����O-�)ü�y����u�w����,@��/�E���r�SI�'�P�)@��9�Rzr�0��r=U�b�����p����	5ҧ�U��m|�Ր*A0T���6����F�h�{X����kF1Xg_,Ӑ��>�;��6Rlǘ:��pE�ʎ��s�ĸ�6F�EC�/,6J�֕��0)Zh���p�s=�L��Q[;b�'e_�cЩ_�Q/���y	��Qτ��żi���bڒ�u��#������7�2��`qAv/׿�T�j[A�m"37S�c�l�����S�)eX�J���VT���k���Rߤ.+�
�^��g�T ��v'1Qd���a�0X�����L��"��Ӹ+�$�a������棛�2?���eJ|z�}���#�G���Q]\_\�rf���A��GH?��q���z�PA��$'�.��z�ͤ�f`�k!Agp��I���P��̑h�'&��&����m��b��8�
�����i�s:���D��a�V�kD�9o�0.���|b�k��7������3���uj�{��������Զ|��1��g�O&u&����,A"_��;�J[c4+��Y�ɮ�m�wf����
k�1i�څ�0�{z�G�-#\MX簨{c[Th�����\[�D�SjPU]�P��A��>#8ΰ���lo$�˅���[��D��q�����o�<�{0�Kb�w%���q�����r�fqQT3֑��
�Ɓ�3�Pl�]_�&�O&_yƕGB����i|�# �+z�=p+AP�AEZ�f,�W�L��(��ƙ��}��/ȓ���Oo��mr�r
}�'$����^V7N��y����
uIQSs�ϐ�V�vb�o�)1��*7
����J�ƬȂBF�Y�(F��+6ܚ�x�z)����rҠmi�?�0�A�E�U�s��\ϥ�'_x���hM��(����3
���v$ڨ�QꘝLlq�����ʋ8��'S5`�`JR�@C[̊��~Óg�C�@����igaÜ�����ޞ�1�U4�[��a��8���/��I�?�Z��3g��eJ
:J:$������B�}�B�XR�
�K���
2��<�	�d7�<}�1���6Cm�J�A�#���?L.��m	Ĝ�ʣ۾�ΆB�ș[�'����p�O�I���/B�T\��O-+/O�þ ���K(�_���d�o�/����N#+z��F���ɕ��3��ˁ��������@�}w�'�35X i����d�W����Z��B�{�>9蜌���4�J��2:�:UL�OaQT�E�:/&j�#�+�Fid>�;��{�������i�'Q��� �䂜�`r]�|^ĩ@IDAT:��>:�;�W�}�A�Z�Q�ɶYu��)�M�<�͓V��#K��V����$��w�2�� �E!����LE��	�'1�8B[JP���st|�y�~�՜g�Ԥm�=l%�
 �~7�}ω�;}͠�S����G9���1���Q[�xb�[���
��[��0��ϧ�?�ZZ�M���i�>�������A�P7&Qq�T+Mo/��f! �xU�ȽHg�}�Qڳ����7��RuA�N;}|�7qͬ��b#]}�?.�km�	�3a8N��-���˦�5k
���->�u�b�(ë�c9�Щ�쟓uW���Nv��	�Tr���O��w�����(�%��l���#���zC�خ�4��� Y
�E ���Q@
4������&0OI�bI
t���+й�RVB�̣c�ث�bK!��	���@.�|R����)��Ɋ�fp{镸����x��"x;?���o��Q���:�g�o��М)#M�t����iF�\�}�$?.�]W��Ù�����SC�b�S�Ofj���=f���#ִ�/����XlGy���f�O8��C�'A�4���Q��2k�)��������$�6��.m��{�&=���9 pP��ѹ�M8U\
�o65�t^��'�{�����;�,1[�����{!4�`9zƥ���@Q�5~1EQ6u��KJ�&e����1��H�a(n
eu�P?�@o��\a}��,c�ax�:Ax�������7�i������d��[Z%����ݍKʔ1@�}�N��7H�7k��s�
��͘��P|�
��X������f�nZǫCgGb镀7}�����x�<��u�b=I��l��%R�v�g�O(�zM��]�?�[�B4��� p\�[>6�j'j
�{�S3�HB&��lݎn�y$5�?�n�ַ�:h��?]{AC�eH�Pe
J�_ǒh���A�L�~��ol���	#��I�d;�xN4�7���%���JA�f����-�b��™t�a�xDAO ��I$T`��*f��������N�4!�;p�w1��H��kNB��GS�t�݄�I2�wu��V�g�g����"��%y��<€4��/�^	�%���[0o�'Ц�/R�PFE+�&��E!�
b ��߅�_�AH�(�&sŃ|S<+�T59֕�x��R҇.�_���2��m�\d�~�s!�2/��B"Uh����.��&��L��\V,���Oֺ�Q��|''ԓ��:cY>}M�^[㹫y�h������^�"F݂yY�Dx��)B��NrE<Bh��gdb�x��T��K.���T.g�����9�|P4���\<�z?ީ�Ω�;�hbx_�ֆ�e�p���]����k���C'0��I��|"����M��������W`)�K0�M��S���H3��;�c�QPG�@��-���{C�Ӻ�t��6�ރ���V���\%�D�5��$�yjkN7���^3�Q��~��-n���2��TT�-,�=��8���%��+�RV�T�ч].���b'�ӱ�$O�+�$nG�j�I�ϩ����$�D��eS�IB!-]z�7�۟feq"3%�x1�B@�Ӣ{�<裳�D���S��ދ�\xߐ1����.��$%'G�"���N{�b/����A�5�r�>`TNn���vL�,�+@����>�;�JEv�M+��"��b�?�X�����'E��t���îb�L
:&�!��v»ݡ��K5?�S� x�#��/���m�GI��p�@�}�v�ܹ��R��m��G��n��<*��!kd$CU�R��O�[n���c��\n���L &|Pu�n��=/=�sn_�<��W�ݫj�j��Lמ�����3�w�Z�XƂ|��(�vrrr�Ɋ����*�0���K�x1���h��#�m���𒣬,���Of�����������O�v#��T��� h�u�\-)��/�9��p�-c�k��E`D���^�UĤ����G��C���� \#"G}��s��[���x�Y[{�>�gÈ%�K}�5T>�:�;�5gs�)k��J��8��݇x�-��4KK��`�"׿dI�װ`�ቆ��)�ԋk��ރ2� 0w��QMf&~�V4���-���K�,�@
��k�؉暚��h9�֚��&��ࠝ|��G<'�xƉ�n��d?8��Z|w�y�W��W��ϭ����խf���0�A/��2�}�ES5P�\o0�h��G�a�5�%�?Z �o�0���mB�5����#�&�"�o8V mi���?ډ�`3��ڐ�d��|��#��s�Ӷ(�+�����/Ys�&�_B�����x!*.v{��A�K���m�ۈ!�^���D|J_+�?raUQ/==��VJ>)��}�;I������h�Mq\��@@�~83�H�
��D��0^�CF�S�hgI�wrY��okE�Q�!���!��WZ6u54����k�L���6B'T������n�z���V�:�[DVZ��DŽ��o�9H\E`bĦ?�G��mߕ����G	av	��i������T�
N��/���3���'Yq>J���
H�I&�o�C}��	�9�h?m*�&�#(J�o���$UK��?�Y7���~c��^{����v�k�0��:�
�%�tzK�O���<�7:�;����k0Y!�m��!�|���P?���ڢodT�I�H
]�).v�����E���t<�ȟ�.nh�;�dEA;��>�lۮ�hD��x�ߠ��Aˢwun�}�E��KV霒��g�|T�Cޣ	3�Y��%0?�d��ʦ��+�V�9�A���29��5K��#�@��X�r�-9Ų��p��d���Q<|�E�zA���I��D��r������m��/�B�W���w��k������G�?�͒�&V�����#�?6N<�t$7/+�v����{���;'�H��W���W����b�����A�?�|`-��e;x�M��x+��ԟw&��@=G�l6?�D�\HN]�N]�X���NvJ,U�����ߍ�\�ߺ�2����O=��t{Q�c
���OMB:�KE�Y��`f՟z�������o�{{J"c�L�d"���xu8�Rl�W�����kXH�·��m���;At�|~��ڄr�q0�d(�(�ⓟ�;Qg���޹
;�j�GX�����.���MnWֱ�w?����7;�!��1�w˦>1=P�|����')�셷O-K�1R�]"@����
����.�igӨ��jٟ�{'�g-�L
<&T����$��|x]���b��.F�e�
�2�1���Uci�@(rԛ���W2z1+|�Z�t*u�W��ؘ+t����q��u,%��*���%��f���{�h���fZ�ǀ��g3�s�n&�I/�V�n�P\0֯�Z�~=��o�4 iU�h�9K<Ǩ9$���TX��ͬǽ��dw�e7�����t��12��dw��(.Q��70�0~#ܭ1ΰ˵���%ǯ�L[��׀w�G�<��MTj:]��>�0��j���Aތ���q���"'drHۑIk~�!4�D�P��2po�3��!*�_�1�#b���6u=�fM�F���߃'�<�~	��(ؠE��j\���ƒ�B�3]��|1T7~���r�܈����eY�9�J�j���~ƶ���7�O	�-����͙G{w���Ri�9���P���&c��1~@��vER�ziiV6�y����;8J��S�;@G�ҵ�¢��4~����~������%�HUX.��D�2+N܆��;�	Ёp�ɠL��x�C/<C�x��]1E�
�n@�<9K&��Cӟ�^ϕ�R��T$��|��
�y���s�%u�ܚ�aR^��1��2ԥ�_ƒL�@d7�v�T\r�� dzʰ>?����5P�h�A$�5�Is�֗�T˥ET��w�5%�৺�T����p�vRIO���~�Șl	����,>#x�����4��T���s���+�	��+���UΟ���H�hQY���wx�$Ø���Ƅ`���#�Ʃx����7b�q��
ӝ��Rk�w��VB�j�7�=e�a���o��88�>��ȍ0���׵�Q�v�:T�����C�T*G�m��z��*��'�mz+H���o��zx�g��
��	�Ѡ�bPYO�aTׅ��--}˚�@�p�^�pwk<�^�]��&��Խ=yẖ����C��9T%J]]���]z��>��λS��6�o�6������]п[H���o�_T��G�%�Ȭ��
	�[�J��*���KAش�%�>�+�|l�zC�#�L�3�r��N]mx`��(��!j��Ьz@ I��kN�2�5�/(j�YVѼ_zK���=��d��]�%���wK�g�PA�-��a��D��Ub�U�{XD�<�eF��e���s�K@m����?<:��)�;gy��?֤�рe��?�~�2 ���Ӕ��Gy?`�5	$M�ة��`���%�x�8� 1R�ž|��2��,�1N��2,����`�X9��~�eBK���L���Y�q� 	�`<Ǿ*��ڊs�Uw|�:�W�K|ܤ�l/��(�uh?�%���>0��:JR'��z�c�_�/Y�J�ƁVڧ�eg&�0�tX	�<�%E���<փ��ֵ8k8](Z��"{g��f���ضn]��#J�0v�! �$�*a���
�Z%��4��i��#z%2��b҄�W��[Qq�1T�b�'8]Z�ҥ-8�G<w&.��44ɾ�`g�@Y�%�}��¾��y��{�E�i�
2�I��·�E⳿@��[�2����h����{�0c�ǁ�n
��6��;�T���Ϛ��VgkD���p�z[d��e�Gݦ�׭Ц��R�e��9���������H2!<�ەH��dK�њ���9��Xz��6�'E�c�s5��Fi�7��P'Y%�6�6�M5��g�+*����xf��,��W*�DD�@��o����vM�S�:<O}1��_��������b��q�A����s3���1|�n��	Ã��5��@��%��:3��u��9��"��}P-�0��~�
�#.��&ٙt�Ԃ"�ES;�dEy��X��YT��SF��vV	eY,�	�Id��{�c?g�/��
G���ߗh)
�I�PT_����p��H�F�=OYC:/�n�V�?�����9�_<�@��$~{�m!��E�|�z8p��m�c�� ��X�w4K}\��
Ȣ��]]�"�_�qT����^y�d�Mũ6�����`�I�'d�����z����\�
�5�f>>���Ms//:q���
�͜Bзo�INtɒ�Љ��p)��%�=Ou��S���،Q	+��(n���&�D
�t����
$e��(�I�]H
�9Z6:Na���e�}�(MҌS�,�\��j�Ⱦc��/�{�K�#D�qLM�!d��l��PXCv�ܴ6���C��$}&5��ل)֗,��GZZ����+�lBYU_2�F8@/�;�6�:]�犌8k�G�:Ձ�|;�q�9�+�,1L���$|1���3aȇ:���e�
�L�jj�B�ԙ��cf&R6�t������zT��Ѷ�����@]A����@?�+wh�Z��(�v��4��Ni��Ps��	�=�p��2�Y��l@�|Nڴ߇��',��͡��2��z��o9��E��X}���������O �B"*��G�k���
(����-0�͘lohj2Z��v�B�6��k���;�Ũlg|r���؁/٪�Lܫ@	Qv%�,���$�v��n�_���5�TV�P���.��7��\ڙth�g��X��n����G���9��d�׭s�
9x�H��	9G�r��;�
�DTMg'm��PAV��ҋ�u�6�zψ[�n���ҟ��KwR�x��H��Y��	!]���,Ӿ
c�>��:,~��1��VB�BTR���H�h���m�+h�s(2YNI�����lg�^���eʼ�2r�i���S˛��f|��� ^�.Ͱ/q�34�)fI�(�X�����}!����^��]�z��c�Nxb��!Q�G'�X���Zb��^\�T|4�4�V�=`���7$;���t�����54��%���������8��1�J!�I�vpz���y/�	k��A�P����C/p;>b����?���p�Z<�'nUʂl>�r�-���n��.��/}��k��RQ�����6�,#q�ٯZ����r[~�n
҂��m�+r{\��@�2��G�9��L�DY!�B�G��R�O���'N �.��d.N[����_����	վ�ǹaIt�!�K�g���žO�;��f�ex<��U�&N�#�|�
�~����t������p"3�.w��s%{���wl�2eLfFS7b�;:�cs�h�\���咏w�9�����h��k'Ϲ���\�aq�fwU��&Sv^ټ9�<@�/���{n7
���/J�<�bN�\���p��i����W�<OW��j�i���='aræ��@�N7��fR�H�)B��;1'S�B��>��ߪ4��c�a�����kgxx��@��03`�&����ӟCI�K(��ò�sX�w#�y�iS�C��8E�F�pU��E�#�<���)��Gp������34��et����
����˱ݮ!��e*cY�h�a��/�[���*0_-`\�U=�[P�p��==~B�g0���B��u|8S�fy�o�3���@�'�������B��hbo3<"L)t�>C�Ք���!<u�ɽ8�9C�Zc2�6��� �� xH����`xI���j�)T)�y�����
	�9lx�p��Q�/��yH[@�u	��w�U�yGys��Σ +��3��ǀF�(�f��ߥ�4Ŵ]3t9\���Ҥ�9���CV!�`J���Mx+��O�����J7�?���փ|������MC'S���?�	��Hn�b��|9��e2�_��~���>N/9_��L�B�s{G�K*��ɱ��>1uN�{e���`���	��9[yp�����)۶^6M��,���RI�)ę�D�p��%�j!-�Je|P$�tH ��׿�wʀ]Ŋ� 蜏��|:����=�'�<���Rd����xV3:�:�$�F�� �_P9�f�Y[�b�CY����o,��w���j��ٙ�FSԔ��'��2���#Yv#* >���Y�H���PZ��f��0/��!�/�W�~#Nٝ/�-�c9d��g?t
	P��z&.
yGz����8V[�[���l��%��t@c��X�����|b��=�K#I}����K)��S�F���DmPVՁ&+�@DB�h_��m�-l̇Ⱦ���]8D(H�e`s�Y�t+�^���B�'^�����d��KPK�E�!�A�&xDž�V+�r�.[}��H�]3���-4y��YB��=�xq'�`ɱ(C��vx�ɳ���������/]8Z�SeH��Jæp�/�63��u��scY=�!x��W�$.��vzFc��Kh��2oW �����*�tFx�ܓ��	�P<���ܙ��щe�Е>��-�W�A��Q�x��2�Tڙwk"c����{�Y�+����ZI���TW�;�G�=>r��D2��Ş��}󗾴����.�1]$h�����Z��%�ým�Ν��݉Yn)Ѽ��'��=X� ㇀XEǹ5k\�F�6��_L��J��@J� �pt"m���*���Ҭ�$Q���-`��ڽwWMMM~2���	WϺ�+�Մ���X*�y��s���늋�Q�wP�����b�DU��_R�;�a����z<:��+��e	�[���/�{��ӟ�N���@h9.�<�cX����!�.�n�K:�=_��jX��]���_g�����
ݑɕE���}�ل�0�#��W l3��M�e8�2P�]
6��V�#��Xa���딱�i�/�/��`�:�gFb�c4�'���� ��"�e�?���.�<qx�d������k:��SG�{\��w3�0]I%{t\)�H%<m[�MMg(��;���H"kO�\R*�<݈��_}���@Y�m|��"�tW�$N�~3��BE�^1���Y0��P�F���
����P�Ȁ���E��6��c����>��6 �����/Ĵ�-e�:pA �AAV �y��YuV4�~>8Hw��U��B�^ڨx��J�_��j�^�M�U��g�����p������ɯ,��g5���#V�|��A���g���#Ur�ڋ&����n2I9M0by�
�b���d��c!	:Y����K���c�c([��ao�%�4�@b)�3�￿���5�W����ȕX���0����K`B�`�r�||����Q�L/+o�+�d�l��_�և��G:�s
|u�l:�����~�@?�ލ�
F��B��y���{�Q�i��g��VZ�.ْ%w��i��&@$BBB
I���%w!G:	%�j��L��r����jW���wm9���]���$b����;��W����2H;1�h��<��b6f��/;������~�2¾j�H�ݬ��:*拥�[۬��o�Wz�zWLi�Τ������G뒇�����Ɓϥ��"�&��~.�	#�e�K܎��
J��V
�χ�m����=��|P��{�x�m��e'(�}S���'��@�tI�}h��)�;\�u�w�v%��ׄ���t���#�x6�j	���c�V�����ؚ2�z���b~�����r ��UW�fU�
~.V�U�����Gb�sP��2ٽ���E�?"��"�y�Rr���+�qG]^
�\��L���]�Ȝ���+q���`]�=W��@�K��2:� ۿ�1{��`�y�R!e�_�ݧX�VT���//D���	���
��cie��E�����	��9A�-��RxEϥ}�1_�u;�@ �5P�ܫ��ٽtΌ�j�'���n��(�f����D�n]II��rr�$F*��ϲFR��r��6p�Lj\��c}�������ՔG����5�K��s��G#�
��˰ɹQD��咺*aY�AG��Z���缳�;O[���=Ó�Ēo��a��e��+����\�3�(�#��[K}>UsZ_��&[g�0.�lnl4���B�>l^�6�j�)��g��U��
�R�^���φ�C#��E�a%(�}��cǂ4}oh'�=�QJ��J��P���1���g>*�ٯT�
f(ry�_���$R���Ჳ�ã�>c<�-���Z�Z.�Qֶn��Q����o�
�)�-�L���_1~����BazLgă�!'QRQT����ŕ^����[�t‘�C�-SL��c�2J��<��<l�s�?�ߞ���4q�H��������(�����q��cQ��jέ݅��	dl6%@����w�V.����Y�-\w�򥕙���U^��y�k�OW�}j#���	o�����HV�����0CD�T�/�a1��^���Hv�В���.g��u�w��l<}ͤ
�+��LJR�����t#�'���*��=�q2r����%9�|�Rn�_�y�{��B�����t�Ԩe2$qe&�Zw��݃ҾVT�U"�

yl'T�&��#�i54- /L$��A�v��ͧ7�"I�tI��>���ģ5K�(A��ׇPP���g�I��ѽvI( ð���jzn�󪪀��4�lZ!Z�g,�0
̨�p�w,�:�'��8�&��_�G�r��\�s�g��*��l>EU�ѷ'b�kݥȓ]�T�jX����k��U��q
J�?�;�b���s�r��#Nk���^Ѕ@`<��O���"{�fz7�t�pCaS$Q��	�M;�b�\,�5�
��o��ͣ��'��&� �m�~���>O��ʋ+���b]\$�a��<*���X�"���k���)Y�ps"���|��a�Pa�mlt>$nA)ɖ����q����N�jTP�
Lp������K.��J���L�8F�є�+@ߑ�H�r��r�(~��|5l1����]ˌ!GG��\
PN����{�����Ԕ<����F�ٕ�H�s5���4����ǫldB����m�,����a`�B���P⭟tW&6�����c�[�D�����
��$�]�#v���QՌX%!\7t�"#��ȏF��Y^ȁ�����A��)d�A�M�@���c�M�9�5�0�LZ�=�1B���r�3uE��߁f*??2V�/Z% *	$c�}������a72z����[i�1�dp�&o"�o��D�#6ʝu�`=�y�㍎�c��.��&2� $*lT�ϝ�*�=ݸȏ��mA%�5�D�0�LZV�_,��դ��6���+��IGZ�$V�C���ќ)0�����u��8�8I@��Y�J�L�P\�h^GX:�Q�y
5��!pⷁ��d'E� �!���ʉ�OD}E�����]"������w�rvGL*%	ba�@�;͕r�0����C���*���_���*Àqʪ�0�!d�BAd�g�sH�$R2g�Т�jiх���C��p���'t��U&`l<C-8{���ǂҲy[,C�	2fv����Y�}}[�����_)N/j���r�ѵ�I��4�=Җ��Q90�S�|e B_졩�0H�(/@%aҫ�{�N�B��
�ۊ |t^�l�6�T_�+ؓ�U�pP1��h���p�3�Q�N³JB8pL����G�k������Ҫ�i���Mœ)���:v@����_G�+��(���9ka|Ad7�3|k��?vX��Q�˖(�:Rwb�)u8��v{25��)`w|��><�w�-m�/��f(���\�*0���	��|�q�Ȱ�bp��בrN�W���$��>��D'<���뻂/�0��+����L�z&�\��K����c�<�"�5c;�o���΃����! ��أ��7\�Ju��E�;hR�E_����B�b�Nq_��Y�޼dO4��;��v �ZV�<u?��	%��
@�hB嗸6��ȋ]�M3���T��~G6Ax���<w��!F������X1�l`����P,��x�e@Z���_tR����{a��k�mH��3L��!f>���_N�tݎ�=�18�bVq�6�FĀ�x)�����v�9e�-�x����5Kݧ�,��>��M �ɑi~�h,Uޓ�,��x��g��#�/�FF5�8V�� m�
�v'~��M��()��8��m��ܡ�Ḳ��:T>�`�3��/f"<��م����S{�+WI���$^׌�L���ZS�~�ksT�i�)�
�=��5"!z'8倞��	�6Ȏ����2�m*�4��*���a?��K���Z&Z I��Sy�8]N��7�I�&���G1�@b��	��g�K1��#A
n
�t#$��!PQ¼	%�W������ߡ?I���|إ'm*;%S(
��Ks�>��18�'�⁨����!Jj�`�,���Lx�+��e�����C��(!R�0j,���=3|6�@'ɼ"�{�wkUV�(^~�~�׾�AR��99}�3��[�'[{�6��Q�{���.����wu�����#g5\ގ��q��%"ϯ�<LFQՌ��]�b������Dv+b��:�I���Jo�dž�f�!���"QA+�W`�M�i>���C�9��Ҫ~�Gd�`j*>~��&���7�4O�ULI����Ɇ�OX:b�L>�$lZZ���v����K�z�VUU��o0���_��lV>�0�PpϞы/�8�E��1�ҙ�E�烈����<
����L-]�TXVZ��*�⡐�	uuᚘ�I��g�OS�
p��s%3�܇��*3z�n�ZZ��!M�1*>ɤ�+�y����o�Zr���}�-�`���'��?�7���Aނ*r��m��r�I.k�#��Ӻ(�5����E�=���c@a!Q1�f	1�6��d/kG^3%�T!\Yd�x�g^T5s�5�����J
��M��(�_����dT��OvOB�Y�0���έ���H�D����0�nɤX'�
t;�#|q����GI�� �SH�YC�X�70��
�ڀ�WJJXF���'��#�����r�X�ѼѪ+�8/�J\�����Xz8�Р�l0��H>��G� }v�Q.��%�%���pM�bs�j�aAa�Nc";��D'�ف��%����~88bQ�}2�ͽc�\*�=}�a�/�LN�E��cQ^p������B�j���h�g�	� ���x__���;-�yX��<�?�t(�u7�b��<ר��yLխ�Q��[�»�^��}�;e����f�{�[�N�f%�Û���}s}��諮ɳ߈R�+�9Y����ʬ5��K_򏄩���j �y�SBx�KAB^�&us��pXx^I����}9���wv>�m���
m���`�I�����r�������Bx}A$Q/�ڷ���-G��X�n�֢}C�������:���UD������(�hv�mT�sT�E�GS9�=n.��c um�n=>2b la`�7�I34ª���Z�x,T����aF;O�	��K?uK�,27���r���%�(n9�`9�H����l�<2�w�n:��
��d\�`]^��x� �G��Ypg�&�'�Lx�넕Ũ]☠��~?�����y�+���x�
��k>xl��}�}�,O邴��Q	15�!D`n�&�p;�4b2�l��p��E}l��g�����54�`��Hn�F��b���J�h��Ő==�ɰ^��F�i���O��7�\/&b�.��#o�s ��>�aB�XT݉~A|�w=�Ӿ�R�\,@��7ik�M)��I���a�����Ñ>0���r!?dd����;��,��D1�F%��`��ô�1��P?���S	V2G_�*��V��N��O���|���6&�����]�Ȝã��{F�3 �S>2�)�L`5�F��Z�<sz򊖘�BP�I�u�텆n=��l�CF��*�gg
QU�7>�77
�M�-�]B��W"��[JM�+�F����"To:xv�Q�7��>����M��
n����X�q�p9��44�χ��������~c��_c(��,��Ro�7�?{X�	H�h�ϻx�Y�B����r/����V��e��R��}�]`	�vqZ���*|�`���LfK0�|��#F&+���F�(���߹�J9�x+�;(ʇ�� �%d�ߍ_�p��i[t<�.�bgy��[NXKgp0H*��Ta�Ű~
:�(с?޲n]�#�$ �nt������Ǚ;Nx7V3���n���ԁb��B%.�h�L��[{�|��I-�iDž>gI�b��s�x�`����>��vy�6��@"G�B���U�N_����S�X�2���r�'�?N��«�i0P�� �4G�z�7���X� FW{}LuƠ�j�n���{��)Y��;�>�\4gN�
�A�:$�'���$%�mm��?F
�B�$%��|Ŧ���<�����x�Z���ڼ4_ �w�$��7K^i6>�z�pD�� �c�qZg#�<�S�
��{�l(��ؑ˧��!��}Y|m��7�:�}Cb������{�2�kc��Ó��Mi��Ue�_�)(�h��5��V�GQ-��w��^�Z���#�G��|>h=2��{�6�9|����iv>�ԘM��ds��T��M�ٝ�|�BsГc�
�d?�U�+��¢C��u�������xCs$[j�19�H�"k)~���\#z�@u�3�V���2�d$
���k�N�+zH���h֍/�GWB��A�=}�vw�c���uӊމ�(0��3�x\E�0o�$B�W�6��o�rQQ��ܨ�,J�]M1�pË%X|��uo�pM��5���?e�*�pf�'L�}�x9�a�(�B,����™���Գ/����Ru�?��hE����kf��<�'ˌ��B7�
pP.T�Y�6�]�?��X�v�\I�TG�Z�͖;�./����u���(@��k"O�>�������b�
ָc��v*�>�w^dTU�|
���A��7y�6�7x���o(��r*�n���T���Ѷc'7?R�Mϭ�}���.�č��BL�*mL����۞|���S��{�_d��h��&X���Ƚ��tY�����
��ZlO�2�#���w�xq1�L�
�5�M3��8a�g����0�gyƧ��wFQ�Yu`f�
��9$v>�V��	�Y�*�R�VxE�R��J�N�Pv�#��ҁ��V�1ݾ�a�8TR�8w5�����n�&�����]E���u�&��PD
ԛS�Z��4���[������ܔ��3�۴��A�	���E�uCY�Rڼ�|��ߺ\��w
*5�N�&�n��#�l�W_��u�ƔG_׾��N����=�WoL��RH�3��o�r&U�;���;�b.�xj���`8?|m�+g:̬D5��T���T V�3�gQ�vV�j���KÄ��#�'����ϛ�Y�"��� ���CBY4�H�����Qy2�v<�*J�����F����9i���@��y(��c3��ǿ���\�E
�V8&+a��p�Y�g �9��.����~鲲H_ϸIL/O�.�'�c�[aT���u����y~�T͑g2}L�|���q[��w��k,
�"�δ��L.g?v,O%9j@R���^HSe���AU�\��w��~&�6��7N%�^~�𨙯򱉡L{��ڝ�XB�(����]�b0�An�/<QW�woee6<Bں��7�:�О5H>6:����|�`�á�k#�I�DgtF���+�Y�ԐF%=�������{�g%cq����م��^IVP��G-*4�9�Qj��^&��Z8!?)�$���z�C��W�E%��S��"��7�������}ӗ1�i�z�-=�b�|��ceN�}`lH�׏�_�����]�=���0�&}>if.g
�
���L�K�m#$q�vd���3�a;$�-w�	��C=��+��Ҫh,q$'�}@��?��z���0�h�3Qh��d͏a��p^��)�,�B�{�
�'�x�yx| ���59.�<�%IBa��@, E��<K{�ѵ�i����а$#��Y��3�������ٜʥK�]�
LQ��#뛛If7��{<�N%{�i�ހd�:)vQؐ�R��a�ܵ�_�$N�"��"��.����Z�.lp�_�D:�Y$�/ �X
���v�y5��sX�7���~��Ø��tʂkG��^�r?�wJa��\ű�
lM���aq��Ͽ-����d� B˗cCnX���vh`�[��N�tf5�����P���GK6��lȥ�G��L���J�p���39]bn����5c�!��}#�>���on��56�ߍϜZ���ŵ!��Y��gS��)�2+�Z�/χ�7�(�)���o;
��X�wgq4���""}2�2��sq
�p�K�u���M��]�]�^�Bgy>�r�%fX���_^Qې�CG�$ѫ+w%<��`<��m=��7�.4��ec�N;|>:J |e
�9�2�evLқ��߸��=99�`�+:uNQ8P�+d\����� �@��hX�)
S���T��6Gg +�jE�(�U��l`i`<3`�]��`c��'��iBӃ���6a����dd2�A��I�I�?��圥'|�D&�`p;�U��v,�@IDAT�0�$���n[��
V38e\a�S��敨��SPD��~��Ry}h���hϙ���u���Ռ��e�*�3�Ծ7��cO&��A!P����"4%W����IX���SKJ]@/��I�0�1! 3���
L�J�dz�T�u�%TCF���OX�v/g�_h~����d����S����R��%���!��c�P�&�9�p��JJ�����nۥ����G�SU	�j)Ԅ�[/`���X*.�ڜK����؝�v��`F�A��i@�⸓WP��[��v���@�E�X�=U�������X��VE��>A��y�E@���$9F�!��':ww�AYP��n���.
�hZ��무r�?׾Յ2�Ӈ,Fbc��>$��1ud(�dt{�$5�%�9�{�����6���or�U��Ӊ���]�.��GT�a:���H6��n� �QE]�DA�	���@U9����a��U��µ��4N�8\NMӂbTzSM'�S�����j��>�����/��<@��I�}�Zh�=�����.����a���IB
4��g�p�\��:��:^�LZ�d��zA��
QպQ�X�{Z���
�	�_荛�9�}6`��������:ȆS�b��g��0	��
/7�`6��XN ܔ�:�8F@�O��$ѧ��D�^B��H�vz��=�\����dc�iC�L�Ct��ܙ�yrO��k�9��D;ܩ�`l��6-U��U�D1L������y�M�|�儗`���Mo
|��I�w"sS��1F�n&�3q/��K؁���8:�;&ߌ��j��I�?@�PX0�հ�Zy��o,9���(z�'�
+++�@���CbP��Ͼ	���0�J�`�YU�s��񖦱"i3S��o��V�|7^4�qŬ
�?�Q���Ĝ��$2q�@ʎ�g��r�T�Β�ti�}���q�J�_]Y,fbg/P֔�u*,���nDX-=l��uX"��w6��^�~/*���Q.�FY��rp��Ԫ	a���Ke�G��d$Ԍ��,}��R�Y�c[�Yf�@H�:�k�l�D58�~��sv�3�<�7���/�&d �]\QߓJJtpy|���م�X(Z��k�M�bζ��~Ѕ]���v	�uv�=�S��UI�f��3� ��(�������`�p��;�C��[�������c
�hj��Z��μ��_^���&6Ն�[!��i�Y
i?��^4�ϲ���0�e�g8U�
�EJ�ӑ��g�|�->�ؑ�Ϩ�E��p0�C	�Bu����T�%5Ȍ{A�nOeb�C�=���لW�_Y�V��
�Y��_�z==z�V����hd�G��Jt�%����x����B�r���J�Q;d_y.�9k�E%��W^�*K30d���Rd�Z��Ms���T���������eK37��9��A������Rp�f䴢-�*�	����O>�~B��_P��T�Z�q@Q�N~|"�{�jժro�����>��Zӟ{d�ޭJEYE!m�K��:�Y�n��p�����T�'�� y�/�Lo��	d!���SI��3	���W*��A���z`�}	X�j${6*�q�P��5�	��Zp�ݞƅC��8@8���3ub��F����0��e��X���c1���e�;�so�-�-џ�<���I+��l�lW�]i��Š:U0E�v?����'e�gUV��sG�GL�c���@�39� B�NCH�ۢ�}�+/)g���ߓѩ�D�>;�(�r�4U�W�SЭ��&�^����K��`%_��k����:��_�H4o�5�0?�z\��o��_R��j<�~ͷ*y��q��-����h@��)P�'{�%��(P���[����.*�_��UH�㋟Z�Q��Ԣ7}=bY �
�#”��|
/�H^c��-����kX���4�,��aIF�2z4�=2������Z�|.��=����q����	�p_Ԍ��,���a�2r���@1)�����,������1��/8����›���.�P#/�hX���d�2��幒�C�h#����(�5k������t_|T^yQ7�Y��Ͷ7�����PQ�߯���#0Z�����¡a���é?��{��\�=Z�y �W:ߖ�p�rN�IZe�b3�Q�2��Ϝ�K���^�並�i�o��We4�j��Ɠų�����ա%�A�;���C?�
u�3-S�F�$�D�F!B$�,Y�>��������t�<x�D-���E,"�8v�{Y��04�֝�X"P�p0������Yk�0E���j<�h򻜔�"��H�]j����usGF1S�����t���>?�|F�~��wͬ���V�I�5}KkG�T�3Y�9s�4�^��#;�.]Z��f�{j�O��0v�Db�?Q
�T�Z�gb�O�@�i��1���rz��#�
V�i#s�C��+�v��S���^[�z��+�f���,-�:$�A�9�����(�)x�6N�7�n���B�?�N�]�'�����k�Z�����}O'�$���
R	ϡ���N��l b!C)��ҫ�<E3���W���$�w\��/�ν�*�l_�����/荣r��X�(�?�5���6�!�Ӷ�_���8r9�U*�0}���5k�f|�,���"�<�3Z�
2�PQ���w)��$��)��M��_�
����L�S5.1�͞x;�����Pe»V�Ě(*��"h}�jk�ƪ���M������l,�߸�{d���Y溬5��l9>2㮓����|���@��K(O���d�&IOFF��W��Ƙ�Al��?�9?F���w����7�ᩌY:�@�����M�x.�x�=i�����5�>� �M��T�LR&Gv��4��$��k?|\U�-�T����7?�VC�
I���6� ?�	=�D	�zZ�D8>t��{N>��׃X�#�A�:�aq@��ڬ�ԧ좾���O*�NP��º:۠�4j˒�S���S@�	�u�j�À����<��]X�e%�qq�'a�S�ۋ�#+�0e���oy�|�!{X�J��H,������F\�Ǻ'��,�|(;��n2g���6ܺѲHi4��!,�	��X�…������E��*�ey榄�I,�-���,��H���~O�LF�NӠ���� ~2mIv�w��\�i��}�E�dA6�),��^��Xb+��q�f��#�%�B��h"���zBə��3���"�?�ԗ�/c"�
��F*����1���yk&����p��`�g�^���:��fn\�h����@G���� n��R5�
��oC
���ɐo}��==���Q�Cx0��p x!^��w�<�\Zɔ�Q����m���~8,�d͸l�eT�)s;��z��j�
�1�/t5��\c䠴I�}q��o:z��ł��7�֐��5 ��^o��ķNhư�sl�֭��|��/f�R�ڛ�������
�x+�p�f��`�o��;�ޜ����~
!���Q���ހ�υ���J�b z=Pn���(�I&"y�

d��j��@>�qW�p�G�_��a~����|�ޟ	��?���C.���8���>�]��b[��z�5I�`�v$�����[����O�[��t�6A`���p��9�*}��Q��l_oxCY��m<F�J'���>��3���-��ᆞ��ю���[������T����|
,~}�
	H?g'CPO�}v7�¬�����׳K[��_U�藬a�}�9�
 �s��l����뛳�9zt('Q�Yl��@�`�E���ۍD��j��i^����K����|i�j�7 c>ePUׁERB�hݔ�̧:��2Qt�N?�ȡ��
Z'��S��'�(a;d~���*���ym�]{Z[���V �C�N��@����lk���?��@�Qw����:s%֮c`<��,�RF��!Gq1`dup��z���ݟ�?��l�瑽�J�/��3�'����,f{!�v��R��r�"-&WRg��Pn���T�Q��EX�}Kˋ5uzA�V	�R.V�}�o�u���
��Rv!-g
[QuN�C���A*��������79�,d�;1�T�i�0{:c\���Y�����Z�2�?��Ñ�o�%��}��X�p�u�6��1=���rem���`�5�,?�q��K�K����zQ��.�N_,�R�XlX�0f7�7\��O����m�<Q�l���1@*߳c��ߜ�+��dz���L�h���Jn2��ZD��c�ŭ�A
Unj6a^<�����B8�TΟ��0��� G�()ϖ���t6���~�b��atA/�l��թ���ټ�����i�枰��-V.�?A�CTv���K����:�����J����Q𻕋���e-��NwF���$ܦ[<�l"h�I?�mTv�V�	�r���Z���xh���o�UeYu��F�?��0���d����s$.Tn1���%>���;�{���g@�(�i^��^��,mYQ��Λ������]G�U�sM��ݯ���z���������I<�Z¦�+�s������n۩R�;O;8�ccV'��(}�k�i�m:+�snm�#��K�\O�K���k�z��^I�	��F?7M~a�y�>��T�	��E�X,j7�5�G4���q�a����I"v'3� u��[ȳ��cXM9E������W0�sXu�n����Y~Gn��/�ZK�%��K~�(o��ឞ55�=�)ry�S��q�x�&r1/�.;JEaV��߳��[�:n�)/w[�,�iu��̶��4Y���ñ��,(J�n~����`?�.a-�W1�c�I"��D��MFTM�=��nl<��߉�L�
�ZQ�T�
�n�k�}��(�:MaR�������$�MA_�1��R������U��o�������
��On���#�&)���:M�o}��;�h6�i��ܧ@�ႉ3�b*|lϠ��>����K��+I���@�.�H�ĦS�r)���s��Z�)M�����rM2��3��o\|R�LS���tlk���խ/?�9�l�9(��#7�2���m��b�REK�υnm��Ӟ����ŷY�����'�_��3���1��a-�A���}��r����9�P8P�2�XU7�7�N�����z(�p{ۗ-kP��t�u�V�"���DŽ�� �z��;�]{�y~޸���dx(���ߕh~פ"��)g�
o_�������rF^{�[L�E��[��`����P��4�)T��]�Y0�wrza��3�r��J���Tp__ϱ�Y:/���&d���o��ѓL��Q��{*Y����$��ھ�p=�3�@р!k�'�T�m�+s�����o�f���	������ �ڣ���}������E���3TZ?:03�םI� �����q_#�A�`Oʨً��|R���\͋�-����iQp�~��Q� �ޓH�)Y��8`s�C��j���z��w�6��}��%�F�]�����d��z���9�A���|�)mf"���OX4�0,ρ@z����b���iEQv6��K���,���}��4��yV�cJ[� ���fp��I��[�6���u!���x�ԫ(��2s�!��s��\�x�f`����T� �G�I���`�;9��T����A>Ǥ�c&���Kf�THq٠�w��a�>��O;z��=KrN����qK%Xn��<)�D���pܱ/��6�R�{>Ƿ��Q�6�H�;���K1J��R�-H��1�$����''K�^����h��
�i���O �tA�_���n�0�1(cI�#���mp�!u
	o
1�̌}}}b�`����e���ݟ�8�O����)�5[�÷������X�^l��iJ��9E9�����ekd hG�F*�y���ќw�a���uc�CI�gc"��L��ocub��"��M��ٌx�㽈�o��̽r�ɚ��7!f}���8Ɂ@��1|���/@5��}9�����wa�s
~��4�N�!�Q�p�._N^�
89�n�FG����f�zDFA.B��Lp%/|>�o�s�W>�X�伻6m��͠��ʟ��}�(=4@�i�QU\M�e�Ç;�/�m R�&
�
lPQMgZy��O�(��-�Z*c]��Y�%=ٴ��Xi��/�t��9����0#'�n�g�OY~�Y�
бd,��ݺS��eA��e]�L��UTo��ـ��K�ߠ�𓚬��|���W�%�;FB�2�g���XgC�a��d�Fr.r�?���7�v�u�ŧ{�3 �\u�x
�B�ZøC�κ�Je�R�g,�#�`A��I;m�����$�(d���@~�e���`t>Id^^c�S�.�EӠ;��	��w$x~#H�f?��Ϭ��O�"#�3��թ
��� '�p �p�O(X���ڔi��$���1����>A`���9\������Iʨ��F�d���Nz�iеN��x}�_r�-�yT�3��&�Ou�:�r�7��@1v�R�I���)����
�Vj�ygSv�v"\�j�!J�"ocF5a�&�A�3׿����8(Sʽ�D�G�R�K`�'.Ev�����b�A�z��
�
i���p�
l[�6�Kz��Wg�P��`:n�b�26��#MU#�����=�7�VϽ!�;����CԽT╘)�X6�'Qiu��HF��sC(��Dh"�n�N���m�Q�r!$23�('�m5r�鎏C��;0���E\���y��}�aa��J'ϑM2.�C)�Cb<�w�̙Sw������ՂD\Dg^�Lq,�A-8��m�����E��%����_��D���W�_�v]�j��uAUi���fr��9��Dl���Cǐ�:���w�F�gR�of��/�\���-υ	�����
	���Sz
;���|Ы=>|dw��v�� ��� �Vy��p�b0[B��O)��S��D�Gi^n�SZ���n1a��b��??�=�u�w]�W�y�r���YׅS��K��>�]�8�Ө4}�n>�o��t��'ҿ����ϛY^�5>��/�� �c,�\��xt徉�����";p��+�UXt	���0��7'Lz��,�V,)q�=Y(YeA��Y��UU�)���`��~�C�����e��F�H3�Ab�D���%�.�8�xa�f��H�2�`�'[��#��^{�s߅�IR����P��^:��k늻N�L�����D��I���s)��h���ޞ]<����5l]�=bJ�g�#�zTz(�8���bH��PP�J���	Bd�/�6~Sτ�w�zˈEO>w�A��v�dom�x�w#��1u3,��+	L�L�,3�����4�2�p.�uݍj�WcQ#K"S��iʼ`�z�5=�X�o�|�ǹ�UZ_��3{��~��+�(���\
5��Z��5sk�*y� @@٭T�w��Z�������h4	���C!Xʯ�{��⬏Y*wQ��-y�'\�t�D㜊�%
e6�h�2�c�]����"/����}�Ay��
ʍ)M+�I��o/;ﲳ��F����~�l��E�n}"���VW����N���F�7���b�r�D9�*�3����=�홷C�̕i�[7�I�ה�.��ʇ�H�n��JJ�!IR
�B�t@�l�vI��՘��cؼ둇���z��T��P��%t��E>��8��ݖ������;��oX|Qa�Q��<��:����.]5�C��?SN�ή)��dR�*��sԒlb�ѝ ���[M�� I���%���Ι~}_c�ӍI���,(3c�C}���lD5j�g[�[��.����J"�Zc��=���;8�`į&ܶ=�T�l.b,4�o����KfS�\�v�W:���@>s��p7�*Ϣ��>�<���"��M���@��E��Ce/��u'��F�g������BC��f�6�M��z�{nă5-����9�dw�䬒*h}��}ݙh��':SM'��R}vi�U����#�L������&�7�Y���
͚��l����(0�����ӽ����,�cef�&�A�[��^��s
���[w���⾲��l�c/FE����;/7��\Z�E�������^��O�+ym�}�{#@�9�~9��a�e�@���h�iv�4}
<���� l��f,��(X��E�A�B{1x�n�[?���R<�jCIZ5�5�Kd�%ا�4�wyZS}�'6C�p�/Ȳ�h�V��S�X�]�������c�zIM��ş�&d_�������
�s؊!}�*�U��T�0��YS���M	ͪ���o'B�BӨ(̷%��rj�}����G� ch0������)%%���_����@����HXDs�<`|���I��9l~���|��U#�dIo���̴�u|�G-�ET�I�LFu��W@P%�v�'z��
�/5���п�A�t�-sX�6�*�[�8��:�M~��o~aгwx��_|6�,�Au:��|��V�m���	��c�ָl٢�c| ��`$0�3R\����D����%vХO9�lLq������T/e�
�]�I���(EaFw*�^ r�S�����;�@�{(m,\�:H�|a�ă�')���m�J}��va�V��?r��-(��m�妲Z�+Y�Ĵ�
�����o���!��^P��L(���L�a�F��|���2�2����R����-`[hj��V�H�=2'��=Vq����V�#�un�=�"�kwH�}%������,��4���@hdnZ��Vx|���
�Člb�CJ��߉�Fs%eu��K`.���is��Hc܆�q9���Y�r��@�ء-/��TF��' ��n-���&�o*���2��Rj����\��%��?	����8k�Z��	����@Iw*���K���4�*���_�"	�?�rM�Z
�烕l��:G��tc$��eI}z�ȃjH�y��M��y<�3��J�V���w�bn^�@A#�b��eMw:���L�~F�J��>;�"H��O�p:#X��� /:��ïf��F��(wo��n2����}g��n�@Ά����,�#�d9M`���?���s��hl̠��k$#M�610=6�d�%{"�ݳX�����K�"��J�.��M�����*�0�^��#�bN�k���-�z	RD��K���G;�X N���/��|��[��[P��%:��N���|υ*�6�9��g7����*o齆b��۹a�v�x[Y��ހ'v`��׆�{��YZaq~Y��.�?�b�M}
R����P�jop���͕ىO�X�[�c
v_	)��}��=���r����b��IZ/z�/4��48�M�
�,��H�����:kӎ�H乲n� �G��E�n��Ќ��6��CIKԉ�aOCa�lEW��iS�k�Z��,=���X)Ͷ_[�o2J�D�q���Gٌ�V�S��_�Z��߻}B�M6���l�嵍(y�(�	 �0�ȡ�@@w�Ռ����D0�F�X�3ڼ�����V�}���8�e�8 ��xo?V����.TI��L��TR���X5#�Il�.᪪�(�:�_MQ��M}}}�9g!|�I���vF:f��sr��;;�L5���sC��Ѽ|]�뮟1�|�+�v�Y�$��m�Y���f��l!�i׹�<B�Fe��r���XS�i��נ��s�R���l����c������y�qEղY���Hd:>>����k����&�� �/G��Q��8;77�s,:�Ё�A?ZX�WЅ�x���}5.(B�zX����nV���ر���L�d��9;S&Ut�{�T��=y�Hhumav�$I��o�N�[��
}��]#{ף"�=[���]8�{ߜ���x�8x��~�o�Ë�C��AA8نKU�-X0�6�tu]�@$��n0+uմ9���\�:��V&�CA�!-ҡ�ga�l��Rot�@+ųW?��AgנB�Ӵݮg̥��;
��4�-۳���/y�sKQ�U���Yxwv�eΚÈ��u�-��c�#J��_F3ɵ�����V�q^1�ߢT���w�6��AJ�M�I���0gPp% |	�
a�mQ-��!�}S����ʗ�
.��Z��#�f�55uUj�j�1����4Xa�V>�=�]�%ݜ���������T��*|�`/��k��J�2�#���
�ѵ�Eb�y���A913������scS��|_xâx�1��2��x��M�rT���PCK�q�j�8�e�'��3'�I��/ۏ��B�_�������������,u��S�$̣\<�ݯ8�BS��	P�l̒��$�~R��:������~�ID� �����
�P�e�f>wAAaʸ�F�u���瓬�?$���˼���<��+&e���y��h;	�?�:~�MԏZ<_�f�$�v�6��A�g�黰��Wzz4GC�YN����ho��ӬY��Qx�Z!���S�y�p�G�dc�vLDw@���`�OH��lL��!�|!6��
T����-�n�f6�|�*P}�`�_�jC��F�d<@;<g%���z��wI�S[�$=�E-|�^s��#�v	��rO�^
k�Ή�d�b�2�‹ӟ%��d����L��`��,@vsx�
B�n�V[K,&�~1)���p�n�i���&�ؼ@2��J�6���AB&8�4�;���k\%��bי�nm����v�sQ
�u�����|���r?��rv�+D��=v4���x�59�E,P�9���[��0l
*�|�P�4J�WT��h�C��Ģ#�
�V�窆ՙ�3a�N�[eg�vN���|���XS���%�\�GlF�Zƌub�"�yT��y��1 x��9�V��}��$�Tp�b0��T1�a�o'9�:�l�G����~�왾�Ŗ���ף?R�8�yc�G��n�FF���uo��<�	j��yr��z��\KοZ�������z���D�6}�I<
庱)o"$�v�����{�T���}��+j}�c;<w���3�wfxx~������R��ź��s�b?}n���`b��d�?���(�20h��8�1�:9��v��ؒ�zȝ��ZIE@���"L��[]�V�/>rl��+	8�s��L�Ht�@�C�O�E{t��dӚ�9M�^E^���"C��}~�$}�	��>�_���p�.Ԛ� �t�`4�9�<zNE�;������s6��3�K�Q�=�9�p�YN+�V��HѠ1E.���J���B���
��R� �#��}�%��������#��OS�u��cj�ާ__��O�V�@R�����O�O���[�|�sg����sqKpN������9)o���v�, �B<O?0�{k�u�4`�$���c���7�5Ֆ�`!c���v�fj�AX3D��-�Bp�v�E�7wz��{Wb���}���l��x\	�y3ҳ��NJv�ĭ!U��Y^�p<�ڑ��y���8�ɕ'�3�D����"�6��
���C-hM3e�����[j�D��0d]���>�O!G��H%�K���vJ#��#��2�[:�s��}y�J盂�>4�ΌZΚu��|��:p
�D��a�Q,�U
ZJ�{&6]X[H�'���ּ�2��Q���d �D�胢�ϰ�l8�Pz����μ��Oj��f5�ge(c������d���Mx���/
�wM'��8>���O:Y�rN͢��*ix��?D
i��yl/��ëƧ��C��4�qP�
��a�����������m�F87�T��F�ڷ���~���`���s#���j]!��a�[vo��g!I',sx]��'�����r�~�M	�����M૪��=�3�����s�@�
 �E���Y�b[�֡ý��z�W�`o�Zm�l��j�(
a&@�B�|���3O{��u���������IN����k��]�σG?��
p�m1�Md�[�~� �~XW��RMኆ�P6V*�X5�+�$n*��$���h*�Y	#r�o��XT�\:�-c+-J_��oN������}h:�)'>�`�U͍:Tָ�ִE�͚�к(�U���>t8лb�M��;��s��*���}����N�Cl�LL�P��6<�}�b>b��u���{��@����,2���R�U$�'�j����8��2����<���/�����1ˍ�ᙢ8�)p�Q4�R$��ax�ko�cJ4�EՍ�OI�X*�Ee9��C1�NB���]c��P��n���`��)�X��x!�Y�f����B���,\,��E��X���yw��H�oY4)N��GwbQ�`f=0t-U���� şI�͗��8
�<��ؠ��0�em��P�m�V�Hb`��ѥ8�%g�@`.��\3Ԕf 5�k��˗������̦bY���0^�i��ս��]
қ��`y�;�g���E#҃<�ɓ�,_e.6o�
�iImm�XMQS�7���բp��0�Z�5�vڜ	��#ꕢ�_R��1ϙXS_R՗TdᏰ���MJ�P3;�I�`���`-?��"�p���ѷ���C"�y�8����	δ��&�0��!(Nm�{�pͻ2�uR�!Zs��F��Hʍ]^ڗ�c�b*�n���E�Qg��t�,�¤�u��e#92�̋AZM5���rO��/��.|�p&J��q�-G�z�$�|�H�,��`����#���E�[J�TR]I�J��nC�C����Yc-]��+k�7̜�k�IB�D���Yh+]P�⋭���:&*�q���ek~�d��Þ��Ɛt�la	F3�z�e~+�Yk^ەok�1ϖ^��!�|���_Up���ȣ'�
�6��۩Y�2Vc��.�ʋe��v~n�xHhi��&�k��	K
J�b���.�����;��i�f���w&�"���
��[����tE����
���upEA��?��ǧ��z��A���@��р�i�u'�c���"�>`���ǡ�f�uް��C�B�P������Ж�#��$��3�}L�ۺ����O��铏���)�Z����a��C��:�A�E�p&!^F���9%k�{׽�|��{���~�%���SQ�>���vd�
dm��/���>`y�P7�����o�/˜OR�(b�N9)O�򔞷��/ꉸ���/�^�bϙS�k�o_s��|_�c�ĶjD�XD�uR�ioqC�`<�K`���~d-/W쒢�T5�焘EJ�R;(]�;�1��O�DEeV5�\�"��I���5�(�P��bI�?1Դ��b�Hr������mC�̕��"��[3dUI(��<�=�Q��<e�nJ�|)��7c��cY�(��XW]���i���/1!ZI�q�~�`oO���x�V"N�Ė���T�OU)�W9LLR�Y���%���+�z�h�c��U�=����������>����zI��W
���Oa�+����zd�?�^@�ri��z�������P���ێ���z���pj��������^�i�RXlʲ�k��n�
�����8�v�>�}<%��NT�F�Vڦ��[(�{�a�?:�<�~?�4��j��w��r%��z��͓���F-��
%�� �}�Ƈ3cʅ����#�CC�VfY	�sO2t��Y��:����Gm�)f4VN>=y,7����a����Q�.�ee*����[P^x
�Y�%w��C��Z4��]���'��	N�l=J�+�m�BD=z�6�u�b���m3�"��H2����qV�qp?x���R�"�%�'�X,1�u�s��%�g�+v�(��{&[Ґ���L\�t��C5 
���!�c��w�ɲ�̱`��,Q�F��՘GR��V�'u���G�6wJ�P�������|�I��l�N�T4Gך���K����[6���R�	Iɶ��� ��l��,�<��������s$��i���4����F��m��QB�z㖒��U@}����t���f��q��K�&�����S,�
��������k ��,��;\�c@\�GU���r����}��F�E�;��;���s��W%�Vz����ۇ�%9~�gJc4Գ�7P��Ӑ9r<��]&�^
Uz��7�݄�sK��ƪN �x����J'��f��[V݌"�>���Sj���Jo(�$�7�H���ZpH!�T7*�>�K��Nq���ҽ��I�~	Esi��zfa,,����j�Ga�mcQQ�A�gێ����mb�U�<ہ�6a��.��-|�pb��/����%�R2r�yͥ��=���B�P��75UZ)�16�JkB��mLB��=q�$���4.*pu�. 2���l�0���u��<��L2��6"-�5	�h��K�8e�y�S�N�t�:Si$�@a�I"\�S����<�xB,�ܶ�ᇡ����~�~����Sv��&G�l1Ɵ[�h������ "Jb��8TÞ��E��}sPM�s�2�(�$�>�=Kl4;��5k�=���b��5�^a3�DN�l�oG|�~wo�j�ca2�ha�,AH�L�x�m�l�C��{L�:Z�����a�bf,s��bY�!zU�bG�y�j����iP:�N�#�hw�ֿsbň��b�&��L�
�x�q� 8�����vj_�VC;��)�d�
�Yk��<nY��KoȮe����*>��O���㈷��;���9���&���zꜸO[�9�?!���ͩ��&��>�F�l����箷WM�D5���;c�Њ�O��n"�9�
2��z��.��TW��TI�Pd��еUs/YP_��C/3�*>shiӇ]��m=4�3m`��V����Ӂ�χ�=�]�磰��,}�}�V����}��x�*�H�';c���
�*�"s��p�@|b�7\K����7�,��.��t����׷�x�����������/1r0o����f���#obbn�Ls~/���X��$T�v�1�[Eyy�ÙJ#,�v£��UQG�ӻ$4sV��-���|1����6����޼D`3��yF[f�L����\�fR?3��`���^�Wl<��n�s�;T��E�	��Rg�Aď�[��j-� ��Mӵ��"G.1"���aJr�b�p��!���53�d�k�8He����B�ρv�p7 t�Y����TՁ`����7V�#����7-u) \�����SK�12=��E�OA���T�A
� |(��\jX7�� ��6SKI�-B���-�0�I'���΁��KJ�3{���d�ѣ�:�儷e`M�q~���ho�cϢ<g�ʕ�4��Z���Y6w.G�nF�}�Ĵ��2�$�M�h����;/NѺ*2�/uۖ����v+םd6��m�ƍliy��!��XC�k
I���P�t��q��썧&��;���jL�˗�*$�A�B��(B^(ؤ:���
?We�˵��Dx�Kn‘�N��/��W�p��"+O
)ԯ������|�I~
XW*K����Bo�~��_̤��N�)��Xv���>x��ʗh��������H_2c0���#� ��@t�#G�H�Q��,�ab9ė4�z�7�m}!�nJ䌢c�a�_9wY��n��Nh*���=-��hc��Y��S�$g&���O�����bx٪!�o~����f�wN�����n
�P��ݾ�̺�P�յ�Rq-��@IDAT?�ܙ���$����>����.sێeoy��<�A�/��cHF�ld�6�d�frLԛPd�6<�]�����ɞ����/��97b�@6�N3+�V��7#���L���"��c�㝺*�Nl��O�3�%�z�?�Œ�f��a�8����Ψ�<(L�3$�)F�>��D^��o���c�p��,�d��+?�?>��R���}��d�o�#w����辴c�=��]�YroZ����UE�,s�+�AJ�ݰkz��*b�ʙʨT�J�^�4��Nc�	~�����W�Ϝ���)'g��7�:}0����ۄ��(�0{����tǩ�݁d�}�ԫ���.���-�HT�%�������<9��-;�4���	��?�F����/E��:7}�kVq:ə~g�=)�,�^��0ғ���*�3Q�fT��U0dm�4+��LX|σ7����"��n�}��ڰ✕d]�3��A8,�Af
��ť֢�߿��:�K�M(c��=rk�Ň��oO�n8I��J^�s\lʣ����b}{X�����T�]� 	����84���.�+
>l��t��{���O��ް<k75;#�(0.�a�5�W"%�u�{���Zp�W�'��s��9��z���)u���#7b���x�e�E����=m���)��.&o���h���充��G���.�y�D,5����T$��>�UVu	A�6�R@�P�lL��%�b�< ^�%���7#DQ��e
b��^�B��D�eͱ#�M�]�w�?!
#���{7��k�u�
%�+& f�];�uݺ�|���ȳ q�w�s��w����Irs,�j�3�$ 3&'
c��d\b^������6�D��v/L�]�!�r�þ�c�\����G��#J�F��Y�tБ�2e�qj
J��'ro�b:�j�3OE��8��|� ��=�4$�"��:�@��9�=�%���ؗ���u1��I%R��EAVT�aU�sR�L�g��h}��	™��EoJ��3$�x
'~��<L�A���E�
h�h߶D4�"�`%�hfQ�q��s
R�_�OB���/����ښ��5�h5tjӖ?�~��'��O�0�2�C.�y�@�zz"��׉˷���ɒb��Zr�HsW�}^�j��X
k���/��pS��v�6r�m�o�󐇀*
;�<h|��H
þ���j�)��#5�G��<��j�Hbᆏ"�2r��h�c�#sl�x,��fS�SKW��B�J��Tr�����V�vRt�ݱ�V5^1���Q����*��x.�&����Gf�kw_G�cY�-I0���l�tKR�1��`�+c��!�gvΙ��C��L�{��I���7��=��`�
��$Y��l<�X�Liƻ"�4U��m~#�����v�nԠ_��p�p�{����hv��b��p�>�{�v{�^�ʜ@nG�B+��y3N)�.��#�n���:'�H��
�\�~"M��Z~�K���m<Buy�,���8�0�ui���OϵϽ�����]W�k���U���G^'��1�>���'0ݑ�-�h�O�Q9��b'ø��]��h�:�1�*5��!���
a0�S�<���{/x�S�]��Ț5kz�q�,��4���V�%�O�ʱڔ.�$Q����.�'3BHM��P�E�~�.�<��{�`�GwΙ�鐓�R����=�zń��s
��Or�[�}QE�Gi���*+��TI�ʺc��,3'��}v��x��XP��f��k�a'�@��{{#�(���dՁ��c�Z���V�6��h<W�Ӹ��)�.C��|]C2�0HX.���W��J�0����vI��asf�Qiv��Qv��X*v޻��#/T�*[z���f]W�
��%��A�T��,y�WQZ~N�o2)!즛 @w�z����R55dy��dNi`U�UeIJ���"0����V�ͬI����ؾ_S����yX�Oq
�t��6P��*uɬJ{񒐲dcDŮ��g�������ǀ^�	�,ۼ�y�(\�*�� 0sB�jf�@jh����W[����.[���T^*��F`f��>Y�S�� (����ozЎh*�piý�7x�M߁݉��ܠ:�2�i`���bĬDQ�١��~��yCS�{t55Q8g\%����Ww/����Vo��b-�{��Ӯ�'3�m%��|2�4��o4�@m���,U���k����'Sj[f��֑?c�����썛Jl662K�4�d�����`�c0�����m�)��㌪��2��H�׀=�L.���o��<m�d�Nm`���WJ�~����#Fic�̝�3��Q�&)fc�U��$H�Y=�d4�7Q���z�F?\db�&��8gE��_4�KR@}��ߙZ�C�A���u��-�\���M���;��M��*�/�N�[��^Y��+��JOD-�)T����y���L*U��P��SD�sw7�6̨����R���o(�sX�.~�\Fa�N-d�b��E��(��
�%j�����}�8��2�H����RN��lۆ
������z�'zþ6؛d������;^�<ʂ���cǠ�V������L$��`��8ࣸW��Q�����{�����)���ş�+I�pmVVρ��_�u����2�u��y��X�5G���.�,ȖI(#�<�rT���c�Ʒf,���B�F�O�Eh�����<ow�7�5�‚������!΅�x)�u&a�����R����@51x?8�B<���Œ�����
O�7�h�{Cg�L;I@��� �s�
�n���.;d-�n)�-�a)t�.�l�%�HD�F١�d�v�\���\?:�Z�_��n]�Yy�|\��ML�=
����*S�m���i���	���
�!@���w!Ay!�k�D�C�<��a{�`�������L�wrk��jτ�xű�F�O[�f���D���ں�G�0v�{�-�|�f�YK[��cJ�b7*��E0�!�wL���{�=�v�UԝN���Yꐕ���2?a�׻����įOm6+��Q�z ��J���v��
������}C��X������TC��`2������n����a������Y"����< ������&��;(iĆ#�
��}�w�̦i	䗁�gX�rɩ�P�˸%EN%:i���Z�+��p.F���i ��0\+	���;AT�WU���k.D(������*EB���r��ă26�����|R�i��^O[Ăq���*��[b�[?@�V�F���
6u�K�/��*��2z9��f_#����#�!��jjNy�÷��T��.eG;"����}���z�FOr���E�F_'ӦV�{�зi���Z��j5�>�S(Ui�D����0���� �C�%^�֘��va%�,�g�i�nE1翫K҇V#����Ȋ��$u�b��L�Ym<�n���(P��'��F�����D�5r#�~CWph0���v�Ÿ�<�꫑�+hOo�C�~���
�����&��$���W�G��ST	�Z�k�Na؅,�A}
]��p�9�KqK��Ās���G���$" ���qN��j�&� �����"g�k@��̀ �wE������G��q�>��(�0���i~�*jw�4x�=���2
����_�f�~L6�a�ʊ�ƲҎ�ޖ�4*���0�t��� �^7�d�Y��o�ʘ������
ʜ��uFT��<(��ѥ�CGu�<%ک�����i���D���%��ߎx��K����Qc��pxf�y��MC����z�#$�н#ٴl�+=)�2�@j�T\|Z�+s�o�'I	Vr(�C���a2�]��Rҩ~܄(�I��ԫ�E��EZ�
Fy���>�B����
Ij���ш��ǔ�N��?�Ao��Sr�7&��G�,��%���:w�R؞k�b�8z׆N魋˳Q|s�j��%�?����3"s�V��h��/��Ή��X��t؇:ck�r��cE�Q�O:3?*��[�K&&U���W�E����X��a�5�f#��I)�U�X�_j&8�����]hSdз���[��'����>�0�?��E��nA���aF�$���j�)d��
,i�1���~�:T]�g5nG�[-����􌢂9���v��T�["s':C8�&�w�7<
���XjO��ds%V��'��"s�j���	��X�>�r�b�A�A�rW�)O�#T7E��ǹ:P��Z��K�scێ��!,o�"����K�}�����	���.CS��a܎��H��9u��PL�E��6�Q�:\hx����k�0
�F^,�>��Fldr��*�l������}s�\~�=�*���
�'���W�=oڻ��c�E
:�|��燦5�8��$��ڦ���Š�а�4�ڑ��DZ����ߵ��{�I�D�Xi&�2������x;)ď��6")G��QI^i�US�N'�OӀ����2hc8�)8)�Xu8v�O��=����fz���+5.#���#10���]��]"|�{P�oY��v�h�>���zZ7&'ދWS��$�T�J1r4��1Ϭb10���=��
cW��в��UP�?n׹<�0�
Ə#�z��_��$V4�!�i�Dd��I��YU�=�`x��-��GІ�T�ER��')i�f��L<�S��s��s��û�mT>o����{���v_��u�J�����TO,���K�pS�KI�#�8Wi
=���N�a��ng$�B����zpP�,�(���
*[�z�B�ـ�M�|y�bg�r��c�]�e9�.�
� �3K	��k�槓^^��_���i!����o�$hT���ގX�U��ɂGڃzooJ�+-�;<:��V`J,���b��<Fա����.Hjo���w?�㥨����ׁ͇:eb��ް�N�dɮ�S��j�Z 0������^|<H���>���o{�����I�����̭�	иF�gƒ�c!ˣ1J�g��cAa�J&X�cD��'���yg��·����;�K�0
I�#
'�8�j
��u�/���p�S祆�Ι3�3��`�d��]ta�?9�EM(�p�uO��Zk0)�Y�
�U��[���� �Hv���o��$�'��l�K����<��=d����q�,U�Z�hQ
�$�_`��0�I2=�hOo7
��eb��:$_�����)�,�'C%G���<cT�W�m�}Rpp7':�=����ݗC&���d���L����Vh�\�\~��L�Δ�#���?�&����J�qY��à���K�%,�7�Io�og���cǯ���5K�㡮B�'�/�壏RtW4y+ƶ�<��Ӣ����s�E�1�5U*c���O�nD;��q%��|4M�5�"�aP�5�(�V�+�����k>݈Cq��Q��D�`�F8;n�`��hW���&ω狸 ��h�B�K��Z�����q3F㋛����p
�/���>�UW�/��'�"�-,�/Suq-�)��-G�7���N.�-O}��
^|(�M�xdAN6ⷥq��jfy~�����|����������#�p|YK�NI)]��l��'��+�0��AXq�<UY�wڠ�5���j�2��Q���`,���<Jr���>'ǵ�d�C��w�V6e�?������V.&Hlk�x�T6��F�ziS��o�wΩ��`�E1��%�S�A�{��WQ�����U��?4ș
�G�!o���:1���
=��m>e(��D()�m�:߶:O<W{�ϊ��*@�)��k���N��]��ٔ�6���J�?ll��P9JO�FnD�HA���l�Ǵu�+�Q��붊��5����n��uD8ngֱC�ˆ�(s�_65Y�Ăy�Ό�C�k�GZ�=8K��W/��[V�+�R���lm�;�G7�ob���<#L'Uw̠�=*����
�Q�ZPRC�T)��4J��zj��]�#4B8��7�?~��a��a�=}�i��O���<�2�O���f4��<��4��fpl3>&إH�o�
��Y6Đ�E�0ed��?�ysj��%q�H����������o�'B�$$QT9�K9�F�#o��;��;�j'VF�0\X]���<��L<	=xG�E�̜����kil-gHI���H�y�^LF�^X*���&$9v���E�dZ�e���{���[e5E��'0,$cN�t�&��3v�0�Nz�q�@$H�wq"-@(p�:RT�:|HrkQ1�G�G ���	�`��˒���9Z�0�6�Y�����O2;��U�d+9&q1ę@9�̼�S��&|߆��L�ܽ�-�Z��z'E�~�D�Z�唣��Q�n�<.��N��D��x�b��v���pב�+w�<�Q���TW�1*w=Jg��>mn1o�s00�<����'m��/Y��"~BT����5C	�H
7-344�Yݚ|#x<�L=��:��$���V���B���.��m8�۪;d�`�!T���+c�du�E�$�����s�����f��[OS�sd��v��fW9
oQ��	M��șo^pk�����U����C�`��ǥ(��\[Y���Ȯ�>��9���Ꜿ���TY11E�
ʹ �����0������.�0�&�$#���h4g����[���P��mF�o�xꏼ�5�y[�رɞU�y��d���F��^�z����K(N;_�nRSR@��<J7!�����5`�+�,�v�@ti�`�rUR�gnN��#�l�#���@� ��PR���lAgI��K݈��O_�<���n�N��冫��|���"�I��^��!;''��	��L��E���Y�X.x�S��/(.�}��e�8x�`ۧJbʃYf���j(İ;=����0�����Ht�p���m���E-.*\�!Y��%�!�~��SW�	NBU�l��ƺ7z���]���fWo�~Hq�Z�#������x��`��-�]M���}F����؏��L�b�ٗ��Z[>���s�"Ln�=)��4i�Ҋ�A�/[�#�#�=$?F���O-�#��K�Z+u�:P)�+p�-o��1b����abfF7	����O�N���xٗl$��wˌ�����5�JD��AC��D$��
Tu�.!c�4%!=�t�7�^w��J}�I���3
%��`p��M����T��S��XG9�*�ݔ����xDuRy���i�:�dk�P��E�R]
Ri�/џDv|�F-����P>_��T	*�iΚ
Z�o9���P���RE{��7���1�����l��̊
p�|zo͑�;��߇��	Z�_�z��Ct<Q#�q�A�9n[~2!�)�%6W!D��#�/����_v�4G 
�Ƨ�ep��ii$a���U7"�6��N��"P���I�/��8����<c2���}�Ed��K��RI5��,J�qJ���/�~�I̗0	5���H���W-���P�p�FBjl��<\&
��%X�_���{�y�Ji%��ND6���:��tJニ�C,$}���\���=���?��J=��2�Y��}����1���l���t�~�\�n��r��d��[7M.
�ء��kP�0�*�Ӹ����Y����u��5�n�{�����2֭z��I���G���唾�)��"�N\r������la?	o�����Ed����U����*��fa�|�H"��Ya��p9�����ع�2����g�9�x׷�+ac�k����\�&MV#,Î����L��b[{�c(��S,
DQ�3�V�>E2��$�(z��(�퓨��y]�[��x�Z<�T����P!���,L�Ʉ�����?����͎<_K�J����-���ԓ��mh��L���'#�lˉ���G�9%^��x�o!�}yIJ�8
D�O<�����ˑ����_6�[�����b�B�VU��=6S{�p_fڒF��|��&T�i�z*		�PvH՛sLܩ��1��Op&f�ڷ�"�Xa�w���}$Մ�~rMb��G0"�:@��Ar�:��k-9O���� �s
����>�i�/��9
����:�I��N�y�#�/�	ky�{�X;�V�C�n�F��km��V�3܏Q	���!&�c(��e]��b��0V�yxo@a��C^0,���|�{N�/i�H�\�N;%��e�㟍��M�;N���Ȑjx��;L��c�B!����gLU��!ɰtu��g9�������%�bϱP����1t��	�W��9ˠ�W:���^PB�TĈG�G8��°�U�197�]�{��vS�=;Jǭ�Y�2+((7&�{�/���v�Ӄ�$+f�=�*�3D6��E�뀯���8��D�s���29F\�;�e
��U8w�f���ʹT�1UN��Rǿ��.�9��!6>�j#!�jtQ�OO���*�S 1�3�э]���e�-k��ˣ���,x�$>���>��g�u�'a���w�v4dJ��4�Vٗ�u�cRWPR��;�c)>�h)������t�P!^�̹Hh&b�3����/�5�lpb�)2*۞@6� F�ϳ��57n}�XiIM?�1����Mw$$��[KB���D��؀OkGf�yH�RG�oX�Ƹ���6u}4��-�<.ϙ3�'(�jD�-L�M�����lUW�G�{H�v�1ߴ�u��I�bL.㓆<��%H6�M˯�^�:���E����9�Q��1}
�fR3��Q-���? �n�(��k�U�}�3�U�1��Yf)C�I�@~>�dA���fu7��Ț���-�>�:�0�VX��o�MH��hs	�AM(M��>C5��[d7��k|�9����
�9f��'c��6n$NI�}�����~4&=���8E~��dz-/�2�|�[xS�U�C��v%g�K����T*�|�q/X�&�l&�f=6L�C�5r#a"�C�-F.�*�vOR�t�
@�����V���Sd��B5����?��q+R=����Œ��x��k��:���fM���*�1�S�U��K���1t�1�x�D�ė�D}b��]P�>����I? ��Ȑ�H/��m��_�@�%�%�W.�<� B�h�%
��X����d�E=W�Q?�uk�q��2�&��`&������.p��B@;L?�Kg�QMv�'���_�w�>���ZXt^i�u#��.\�}��S3�f���R�N��$4{ڵ���EK]3�L���Y�
chsD�_g��,�i��"r .�Gs�|�y�p����.L:͕E�S� �w2�"��y�?�W�g��R
�X�_/<�ӮA��&nx�r �ZF1�MS8B{G�BI�w�{�S�O"߂2�'��y���}�ƿ������I&��O�c{oѰL�د�'
4K)�=M�4���*�/�
�+��"��$���&�~��	�o��Z�z��7'�c��_�=�t..�$�I�d�cR\d1��<+I���L�;�At@'0����J`�ʢQ� ��]A��@0>�J<�@�H✟Y��߭Ñ�C��D��΀�T��|%:&��p���IR�~�}���|G.d�+K�-�=V�̹e�UG���:�ʭXI`ҩ�_|1u�=��%��<J��ꄍ�^�\�ަ
�j�o��I:Y2Be,�5)q����\LyN��\�ap0���9��/棸�U�骳�s�u1�wJ�>�4����ť�L�1! ��ᥡ� w1T4r����ߠ~֯���bqm՘�8���4�"�C�8k¤n����=���o�N}���v�}�k���d/x�����b�t��S.h��`̱�Rs����#��=R��~6�AO�pb�#�/w��� �p]�<��/[��
�Z�ʋ��A�h\�(jIqn�=�h���6�<\7&u)iq�י*��g�����>�H�9��v����?�W�؏�oiOm�p2z���S,���P�	ȱ��N'�3P�����n~7�ȭP�ٝ@@
�(%���JKO���1v=E�'�m�9�6�Q镒���r,�U9u����N�5��K�(�]��-ꤌH���Y~��(e�Ƽ#X2n
�}hd�%V�2�&�
����MZOQ֑�|�?�3��"Z#�OKPY����
��[��ׅB���&�<=����)j9�~
c�|��&R�����^��Yz����o� ���!���]P�$i�F�YoJ���y͙�l����Yׯ�!NJ�+Vԩ 1�`\q@ڶ�i���>
Ka3u��=�kj�y��%c��c?o��]x���D�Ue�E�����s󃌮^��.�t4֝�B����7�p[�*ĥ���-��KV�����#E��.Gr}at��6ϝ+&x�?���9�w=���s�>Uī���C�C���P�8镒X��Q`r#��|�:�@�Ķ��̵�yڶ��݉0�m��,{[���Y9�V��@�<��n���F����u't��ᓓ���9ނ�j%���	��P
�D�a��y^y�e!��$ߏ�>n�q�N�7@�\쪗��k"zB��4���^�c��l���m5Y�n���#��X��?��ޖ��,��dP�D��}/j.ƀ1o-��l|��L�y���(�bw<�o�vA~�^�s�7��:��^VQе���K*�vGuX9̮�
��q=��\��[g��j X��]��Y
������lj���@��((zb��x�����Hj;-�Pv�]lz�A0,�!{��/�ʖ3��"?'h�m�`i4b|+��(�gZ��퀍M^���T>��Cј��p�C4��������6�r�#��-&���8!���'Q��x�[���'ˇGv@�^�v�P�͚��ms��^�`� ��qH��DU{viu�)�g��8���G�Ix-
+�	�Da"wc
������N�
�J&����l1�^�虧N�Q2��rƙM쿂��2��)��)��o癡��NM�]�;�*�m6��z<��ux���;:���0M�"�9��%(>X�CM���E��;�|�-��o�n��6tL\L<p�o���jbt3���|n�
y���|���@Ԃ	���X'��\��W+������?pUB��C��m�o�Y��p
���+&MO���v�$j���wD��̪��ߥ���'�[JPY������ڋ݈��7w����0�����_B��W��G���ć�%$�jY�����v��#�4�)�p�R��_�"�jp,��l����"A?��.��y0C7�!��ޭ<��gxٝ�bf���PJ�n�ی��i�9���m���!�����wW@��s���p '�rj�Y�`�sC�p��s��R�&s��2d�:7�ݔuM�st�K�뇱��o�8�JL����f���9���
GBGy=C`��=��B��B�����CX�d�L�@��ZU"��uu>ؔ�!ӯy�����"�G�vT*���J��S]���0.�]Ư��E9�3��,r��hI�n�4�k8�ח�����=�K��[f�w��E)f:��\�����=�|/�?�r!�<�v������Hx=�J���jX~��K0cf�`��F�����O�l��X�a��7��[���+�dJ��c�����y�|����� #O�5ԍT�.D_?����O�R��v�o���]��A����)�!���\_�s���7ލ�˿����r���&�r����f��SCB�=��@
Тh�q�'놡a$���N�7<��}�(&�P���w��,h�2�tW_ư"�bC�~��`B�9���w[R��d��6GN��n<�a\(Y"�d�݈C�C)yh#�Bfͱ�_[����Nȼ��'�
�#�*6�[���;sn�yh0\EC���"oJ�z��P��?	DH���=:[hi�����
���'�e�7�⼘���QV_�a��*�����q�c.\t1��Y
2��H��*#h�L��5q#)�$�����E�xbA��"<�7� ���k��(ۣ�Y�}��o�P��8�����b�ת�'�=�q�p��L�9��8휂	��(�x�Ҭ�g�p���
�#��O.(t�����3�K*K��Bg_�O1�zˤI��d�(�P�;�S4uo,����5�+R��ܩQ����~춎�k�g��g��q!�y��n�݉�	��B��6qF�r��]�Z�Y+Pu8�H��a�sz�$3��OC�ȹ���^���,�Va���YFSj3@�O�)�j]�܅�������L�D|.�P)ެ�X�q��CdiLη�;�0g%R����z"54����@�Z,�
9�.�1ʣ��|�T���<Ն@�
ׯ��k��&t<C~�������d2�#F��-s�� ��3%����G��.x�B�;m�+���%�˩N��)
2���Aǭ+�T\���y��F�:�Qp��?
O�em��砏G�&�����>ya�G����N�a�=���n��3�0��'��xM0�u��;�@,yBC��4=��R��
@8���x�ߵ����Q��r�y�(�y��<(*/���ޟ�Yp��W`e,�A0�*U�D�zd��s�zvU�5���`^�Y�߅�����Re@�n�Z��I`8#�*�u�5�#bQ�ِ���o�]x�[x1��`���K�~ҡE|��s_$�%X�ŋF0�y�ۺ�s�a)BkA)I��#��F>�3�����]`M��@�{��A�]z#4ޘ��ꡀ�L�z�C� !?+��8��;��͡x�6����1�n���'�L#�;�?�3�K�)�ɧ�,M��]���X�()Vy��_�}�wt�b&ה�jΥB�Pz��јb��I�`>V�Ro�'|�2W�,���E��ԦK�����1�͵�e���ʾP,B$Be� ���mG\��|�N^_�������	�6ktZ'�<�'7j�n�yH�+Z3��=:�߉R�[�6������.�p_H5�����#��E�w�F����KP�5���ST�f���};�0�gM�@�o�o�A��;��8	QO��>
A˟��Z����wng��S�����|�>?�8��;��Tr����N46��_=2���?��
����>��r���텨凣l��
������B�M��"k�x�U4�?r��J����MB�,�T����B���c�$��Gv���@��fW�K�Y�P�:�!0�p��Q[̒�t�w/i#鯑�cX��47s
+��j�{l���-���}�/�70�]��6��_&8��YG����� �(��3��G��-�ֹ�aI�A�����seH\B�N>�*��?2��c�*bmr�}�*v�o}z��3���3q^���MI��~=x��g�"2�&�uZy�rX�R8�DiܫԮ���̪'��W�I��[q	4�):��طk�~Ҟ�����U����yR�2Q��t�:�-�տ?���f��&�hz*�6ā�a�ze*�o�vc�������Y4h��%��
<XsJ���.$�SU�B�7����w�p�!�2?�̴P����T�2/��C��Ѫ,��=�Cs����qL<��c�<-�\���/l�}^�w��+���]�o(W����CJ����"�Qa6�M�r�B�j�\L�'I���=�9f�?�l�/괼}>�z/(�H&觑�y���E����P�g����vPG{6��'�����5;3]ִ[�O �hO����`��^r<�V��I��s��7&��\�+�7���i��VS��-�ݘV��?�y��(J���*��u�R!2�F�,�&�����S ��@��=�ѥ�3}�9B?���}���q�<GeB1��X+���|Ù����LhG��:��8�p��q��W�RL
���0qu���?o��vcii��7�aX~�٢���������&�{H��@�9r[��I�<��B�o�7]��WU.[ư��	Vu\���v����OG���,���Z��	O\�` ���b�Y��E^�{�!��^ő@�P�6��r&���7h[u�.���+���	$�=�_�
&��㉷7����l�>�p�����J��B��M�+2y�!_�^?x~=��>��	�W����}�]\gt(�cE}��G�q꿙�*fW�U�8�}��8c'��"(1��xʷ��~������v��d���B���9z�<b?8]�-KıJ�O<�6��k@y�""V�:��(2�)ix\Eh��,�d}!�KQ��'B27��;�N�
�rԼ��\�j���4��No ��+V�3�_��7��%��ޕC|#�	
E
tt���b����ţ��Q:���,[e+�φG0l7�W?b�i���(f���~��gh�=l0����ń3���n���'���h�����_�e=+�/d)���k3A8mD�o�;+�,���H��UW�6t���w%M��HRԜg��I㟶����,f���6�?E^
��
�@��
̴/�'����Z}u�ԣ~kB����ST
12��J��J`l�h�,��D�Z�����wo�@�^{]{б턿zK��%�ǵ0�$���3�ᅠ���Un%ـ��R�T��N�$!(��Z�`(c>&�+u�;DQ��j�"�:v5?IƑ��F�6��֢�z
����_#C���F�!������!+������3y�'����	I�(��\g��֘�$���hҶ1L'�cf����m��6�}�l��b���{X����+[_<��A�g�pb��A�3�����e�����۟���N�_D��"�'Q�q��H/(��N�G�6�eJ��}`�� .�W������%��o.���3��L�����Ý;����<�z��@M9&!�EQ!��m���T5%O�<��qX�}�I15�b2����x�'��	�Ǣ��J/5���^P��]���㲂����a�4>�����ͣ	@�H�Hq��`.���>EWFII�#V�C��i�D�2[�����c��n}z�];�Eخ����P�"��@�1�v�7�UI�*i�PXR���@����	�Mb	NkQUn�)��]1�f�F��2o ��`P��K8��<��0�����O��,��o<�xg�C>��p
�_8ߟ�
+V�C���XF�h�Mж���n�ũ����ۘ�$���'2�f�o0Y�Z�a*��2�#~6���V����P�%��1�;ci.~υ���
�?��m��T�^U�l8GkW�8ܻ��{<�HoC)%��O��C'�6`������$�.�o�����ȸ,��m���P�w�"��=yvBE�Se~i�'7��
ʑU����C��
�>�@�$����B��XG*�fs_����N뷯�_d*�3�\�c���-,��
��쑚�,���Isn�8zCO�.�j�����b*���e��|v���P�����Q]���_����y�ʋ�TnEE�}�3��JF#v�4
����%��$%��F���U4����.�p�z���<8�IJ�,qZ	��Q�S�s��Uy�H���dA\ejF��I�����u�<��0<��z"��DI�Wàc?�Z�a;Q=���}ۺ?|㍴7G2��Rlv��-�ރl������l�|�!Z8^�(
�ۄ���)��/V
�y}0��%O��!�"���S�VF�����l��)!he�F(؞�,��s�@��P�,2;���~3�9����������LۇO���LzO �^�Cl �}a-kw��]]���������P��J���^'���3��301 ����/��2��3�<���]����EtN�8�?z� 1���3��ˈI��P�k���LJ��(X@IDATi����ru�)C��
ܸ;�-=f�����;���Aj���0u	��8X�:ݞ��q�i˼��?]q�)��\��4b'F#7�׹��Eᘑ&W�p5�P�>�T)5��6��/�~�$��}-+=��YP0�1�@��r�<���̧7C
|�Eu��6ң��GDu�3R��t���o܍T�60�H�A��I\�N�S�F
���Q�*�M���S��'��}�fúʋONR�4�h,ܮ��X�fa��������É�yS\���7Ǒ�ZdΝ�z���7����իUSq�i�1@�u��4�c7�e��ʅ�֊����b즟�y�s���&��<~b?:‘B8C��m��Ďo�ڷ�����NIʏkԳp6ε
�ix� z��nw��5��K{��w2B�W24Uq��k�5��pb�Yh�����V�{�k*{��Ǘ����C��ĸI�����@�
�zqh�������NC�:���јt/m3����u#�do�:�Ϧ�U�-yH�Q����5�F#<�b`���@�lj���WqT��D��
�T}6��ճ��#�|��-8�0�ah����3-�K��&�?��A2C���1O�U]�����t�J�2R�\D����l�!��䘈!7�R�U�_2��Z\��,�_*�����BұjP���I�ȫ�^%�א�P$[A�	��yzB��9jj��w�d�p�]>��Y���~vI���X\
��6W�?�Gx�-�c��������\t�?¯ǿ+���7Awx�,�ܮ����&ev�il�~�f�ۅi��Q0p+��6CA�F3�l,ʫ���v���*��v�˥���‰��|Z����"H�xB�ҢJ�.�I�X��=(���������7q�6wP���>{�)�|&p	��b<��j0Wh�X$"���V),�ekqFc�8�c9:roV�#��T��hyuMZ�v��u������Fg�-���]���\��a�ŧ,0�])�k
�	h�9��&���Z}�RR&G#(X�\.g�=��Þb�t�����_ͷ�S��7���O��a2��pV'�������3�6^�����e.�c۞<����F��:h0~�EM(V
�nT�}Gr��z\�$��?#�:��r������Dd�5m���-�bM�P�\x��l�|�=�B���/u4x�/�4���Mܷ0��0��&Ƣ�� h(�_a�Y2���x<<��ͪ[U��(g�B�;�/��%}R[��%E��9��=,�ը����?u{�
%�兎*䒟�i�Wm�xL_��«��{��d��ˇe<h�j�<c�
A�����S���n_W}QN�OR�;����x��B>s4� 2�+�-"�8V"!�e��X�=ųO�v��iz�U�@/��@@�����lm5��CN|����Q������,���n�D�����vt����c��"�^o����ͪQUxY�~ͱ�h���l�֟�-��%���"!T�"-C-���]�hx�`e�wh����+뗹�A�z:�_~��0!i�7Ug�G[��k׮�D��1&�\�����
�EUËa@����/P�~�
�Y�kl��%c�W��t�;t�g�
���~��i����C}r�z�oރԔ�Mk�	���S�����zYAj��
�f#�"��c���7q_�¡Lz����[��
��3����>g�}�m\>�%����R���a�(��!}*)�T@�nY^���-
â�$�%��>�g~n޸����#�/�W����%�LKg�RT�C����J1��2�{��~��E&�5�b�v���"bXu��{Pe�'U?�-՜�q�{��i<�������I�u�$�|��</�br;��@�y�"iX��Ǩʘ��Mgn?�0X��Qʚx�T@��t=�<�K|�<�����h��U�{�H��i.fʊ���H�o0����T��q"�jQ��.��D����ؿ�<W]��h�\�����z��L��Ei���0���	��7�T����t�o|EE��VW9�XTW��W��R�l7���i��(5S�HUj��Kի�PpL��'�����P`�)���mE��}���LZJJ���A�=��
p�}�9W ���xf�\DÌ^�]���Üa���mǿ�Ey�.���
�����.
ri{cK��Dƚ0�9F�@���h�^���Ԏ��ZyCފ��)a��f��醅o>��iM�q�~�S��T��oQ{�[
�s77U�ퟛ�T��ַ�.��W�?���^��\{�:8�,ǴFT~};cN(?$�<�_C�����l�bQտ���<�w�g����c�tA����o�iEYl=t���O@��9PpΡ�fHA�	��b�/���f�SPO��������-h�=������i����,%T=z�0F����'��d]��<p=+�oz���mS��+�����QU��s�X���}��,��E�@�1�(���%<$����g)4є��/�����:ԯ/�e�1k�pMeׯl��������)�x��n��vxs���B��J<���g�5%T�A���+l�B(+&�s)����G����J2�%��c�T���)e��1p���t]�P��sY���P�㘲R�8��)�����*r�Pm\�t������b��o.$�9p�3M���Lhw#ܮ�|�$3�K���ַ�n�T;�O�,�SPA{���6V5%�����
3����P1�˚}�'�bFi�&6P�^��h)6�R�i�3gvbrJ�&�����janC�(K��h�X��HI�$ϖ⍑��MX?qk�v5Ļ�m���gI�s`2P�BB\�#ׅ��(��8�ܩ���Y�c=�������M]8r��\�
�
3����o$>Q-��hk�yx���7�{E�w�q�a��
M���@T���3d�o�W<#=�'�?Y_�#]kQ}P���AZ�7���#������ 
Z�f��p�����m�Dq���vA��G^��|Ԭ[�5#����~�� `g���3�cCx��Z��^��4f4�������������L��0�Y�IR�#"������k�[��������5�jϙ�
�����;�™����3��6�rύN�r8t%�~�{D�}Z֕"1�B%����;ҋ�R#!�A�
�g�hw�*+�zoS9�-6�j��m��7�g�߉��!�ȏA�"K��`,奶��c3��!+A�˶��9��	��]Q�����F2�t����A�V�٧�vwA��	i���NV���[�Hl���Rw�c<4�C�n��fZ�
L?��J����/QK�sF���7�Px���^D��0��H�$B�"*�XȎ��W��^�C{9�/1�+Z<cDU}Au�j�:���GD.u�sL�3�m�$���o6�����c
�bUGk�z� | ��R4�(�G'�y����Ґ���0�!�r��kM ]�*Ah�(��}��-{=��E"�D��_A�2	y�?H���z�IWw`�,��d��il9����s�,>��Ć4XL���ώ�R�Ʊ(2
�+j],.��%(�.k�'�&� �������T<�����Ck�|�^?x�oi��#�Y�@�x�>��3�R��0U�D�s*Kgӂ�H@�Hk4��s7)�kCe��֬9��y&��sCm��h�&jv'�/�h�u��Co_d�%?`�K�`�9��H^ن
 j�}�f��O|'���?p�__b���
$"�6F���9��5���h��{Wy�B��5k
���?n�xf��a�7�}��"A��2�$�[}�A;��9-a�1��/E��&x��!��ۛ�!}ӎ�+w~{��=��fUU�ȭfYm�tr��Krs��`v��@�~�u\2�5oz�s7ւ�V�A��Y�nYM:�!�*t�P
��MTq-��i�w�m�o���3�����{6=#S���Oک׼�ʮ8�d��B��( so�j٬ѹ��["g�Օ��t]��QQ�I���>������ހ�ѵ�.@��2�0�Y�񛮄���c����9	j3~���E�4rE�ȟ���,A�.���'W�[U����l}�+�Տ�ą��U�񢽾е��Z<.�E��x<�
%&˞�3<
�W�ܸж��<.�ۂb�`\�9�Si�܂�AC���}���hف��
8��;����o��rlIvL��^P_Y?�1psqF��4�$�G�<
��a�E��C�>����뻇~}�5�q�?��vްQS�#z���?��L��n��n�.��&�j���yP4��%6��	��$�"��+�]�{1��i��u��nD�!`�Pc×�J~���P���+���ŵ}��M�"k��O1����K�%�zڔOʹt�=(�3��7A�*��?����ү�Rr�(J�)��O�b��L/�f�]y�P�e�>�>�ֻ��4:����*2+%��i0��qp��jH�^���:�Np7�J�C�'bX��~�o(
g��|`4��y3���qT%w]{`���_Gh��Ɗo���TOu�v9�d�9��_��̏(��쫘��Ƙ&���Uc��թm��Ւ�&��p:ƞug�g�[sN(��/��Ϟ��;#./!Z'��~�a����[���D��h�)�X�
w�h�i&v[gޓԒ���yv
�^u���Q�e�i��;R5�XJ��ơ���||��E��GW�P:
HͶ�{��.�k�yFg����0�X������WlNF	�p9<һ@�>Q&�6~�=s�,����x��No3�M(�5�e���[���`d޿���Q�mfbR�,i���^�}��8�scZdƘ����*+�'2h�C�&i�HO�:Fy< gq=¿;���Y�v��3:������{�%���B�*��o ʯ���>�M�(��	�ϜU���|��Y��tt_�l��/נI.4�V�S����X����/.,�Č�0���b�Wn8�KRy��D~<H5�-�;W-[��z���SK��ݾ�lU�<�[k��Hp��x���^b��	���6E��
�-,�'ܵ����'��1�����u��?{
�ѯ���C@8ҨE�!�H�B�ע���j��Y]پ�����
�z@;<�/�{\�v{#P�5b�,t�
�V��@u������u!I�7D
�C�0���}�
��v��ַ�N�_�[?�/
�L�E��꟞�Y&mt�J\�zx7i���L\<�
϶�����dT~(�[�������ڃ���]Tί!m�}���QS�3G����:�c�5��M���%�\�n����<ۊ&	k�W��|�C�K1��A��JSi�Fƍ6�٤(ҩ�{�QM�`��>ۗ�=�_d6�}hnbI�	�Il�LX�����=�]�
�/�JV
- �Q�ԓ��_3ָ7ixk<�1q�}
N)�,��4�������"���nw�2�	J���OŎJ>w(��i�h��RX)�;���2=�5K��/��G��Q��ut�Qz2�IN���玘H
���&q�ʺ���U���&4�L�}uGYn�o�
V��bs�_&� ͦ}�y�T\�����!��<O'���f���p꺭���OT�R)���p�1G�H�#�����UZx�Y�E�5�cODU�#GZ��c��#�������Ң�gT����D<�^���F+���	&���:��:�u��M~o����X8@���� k�
���z5{��"W�Qǖ��������]�c:�E����
�K3���.g&���K8�Z��C��rp\��2��
�J=����`x)�̏�K]�#���*D��X	��0ō1R�H��}8�@vb��Ʝ�%0��me����Q�#��M��K�
�M���5��k;���c�=�⬿���㲲\�X+p���Y���H�*5�~k9�ٓK$8zI�MV|��qԐ�j�j�����O�x0r�פ0�*�LX�l�����Hj��f7!�h��=0�2���5�!����>^g�R��<�R��gi����:�zO�����@������Ͼ���.�r�; �t[��*OT�p�,!�.��]���*%��h`?�0���<_Et�o���h�?���DL��:\cE��o�S�|x�6x˗�� Ч�G��/)Z9<���L�B����>���I���&�%{���nŽ��]~G�7BU���&@^	�˘���7����*��nQ�z�Ǔ鍾}	��$�p9�o����V�-Jc���vy("I[]1�M%�}�w�_���B���1yU4 FU.��3е���c����b Ib+����IKT���A�qq�ȳ��Ռ��|A��@�����\&1)H�}����@�l�NZU�C�j���`9�'�
�#�ξ�oV�:�i�qQ"�~]��yK6�23G�{����t@n)�c���ց���ʾ���8y�({�Na��:��4���R.Zg�@��6�dc���4�{fͷ��a�����:�+0��k�p �X[�U��b�Jv>�&"�@�xy(�C#�!�+
�{� 	1�;qZd����2�Gt��[;U{���;�d�)�1>DQ�E��ؽ���
Odr
�5�`Z7[��&������r���D��{�_��z�Q�6uWI��y��T@��Q꤈�|b�)�9�r=�m�u��g$�)?���!%��]����������ӌ�U ���i�nV����A2��� &�O@�m#�����nS��
��j5E������a��Hn�͆�7��k(���p����:��W��yR�&U�#Ze6��A��Qt#$���_ﵽ�vɫ�QO��������#w��uRhM�?�D7s��'�-��p� n<�ڽ�P��G){�-Z�H=��6��F�ڦ�0<&��j9<�5�AO�=[_���FX5�Z�'�.�|�iuؒj`�gϢ�-� ��d�F��й�)//��;�
�P6�� �I���F����n�	�`RW�z�n��@�����{�99Q��~���@^�t�r����4X�z�W��ׇw�=_r$��w�	��hɊR��FVϟ8r�1��9s��A�׀8��Tޱ����v����F�0�$���ij4�8W,;���
"=�F�ղj��MY2��42`У���yԎ�򥇦�G3�Px��_H�/A�끨�.���#A*��Dxy��<�}�tw�����<���Y9#ثĎ0<C��㮍+�����M�,�_��[)Q<���P��|?>���<�R�f8<���!9�/�հ�F1E���&��~J#�m�J��crS��
6���Ë_�0��N^�����iw�K2q�z({@��
��e��$�9z)��o�l?�%.�e���
��OX�^Z��`�‰?�k�@`8��~ ������V���n���`���+=�yG�W
"xn�1Yt��U5n^Uq���g[ȿh�ݼs����&�$Ia$�|%�H����]�x�`�]b�d};m9
�����9�֥qP��V���SL!�+r��o>W�L�$����40�`jA[z��\�^Sc$�
���Tq��05�e���J^�6	�q}�K�XU�bJ��k����h|z�'ګ��߃���a)7���$2F21y��O19h�~��2�y���!#w~&����!Ɨ����bnjص�.�CW��Z���.�4A���ꦒ�Z�yĠ��H�vpԖ~iT��`%z�.�fS�?���gA9a���b�B6��ŵ���BޫPv�6ܷb!�!�����Eq��#��`�]h�ф
1Ƅ>V
�c�zHR�/Gxi���bW�����ftY��c
y9&�|��kWdx���7uG"������Q����1�;��ZY�ܨ���J�m����x`]
c8E��;��"�nXy�;��*"�<L?6�����.��\hV�G�o���k29�����J]��&P��aQz%��O�Lj�tͦf߄e��C�9=cĈ(
��ʹ��‹�;|3o9�t&��0z��fA��L1�P%����,D�R%�$����A����n�ȄQt 
�99�#�<h��?�J�:4���;��[�a��g<P��	�u��R�\H��6y%�R�L� M�>��V#R ��®�^�6�����I����o���&��c�sSs�]P�Qqz�G�,�;�fU)rb�>���Pd��ė0�Pa�o��w�������"Z��1Ѡ�Rz���ymp�;AJe�Y�j��@����
ҷ�uS�f��"v��uǍX�XF(��8#�zZ��k��ҧ/��P�v9��>#�P�� ,�`6KE�p�����,f�
���GFtc%QZK�Y�/�H%��B�4�5���Sr2|��Au�*�O@|?��m.ˮ��K���M3:�l�\fx9x�/�ь�����]���4Ώ�Yz��W���gd�Y����6>]�ĻS���<J-�n�@t��UG�[ �2�����0;l��j��g��̡b��������S�E�ى2����@Ź����
�m�B��[�r�]�i<+u�ݭ���V
�*�lp���Ԁ��򼎃��[B<Ҟ�`0��u�Q���)�F"i�r��+c����P�,�������z\��O�!C�$�w�Lx��r� Ǥ�9��#0�=;�RA��ω����4�����+*G[��(�!�0*+���LpE��n���h�Q)}9�/G~9�Z��iv���%����5��1ÁB�&�*Z"�Xo�6ʩ�-.��n�7XqX�p��iHÔ�[yp��� b�=ޓ�����a��xz��ѨF�$���oEK����ٶyME��!G��ۢ�t�M` �4@�k��T�G��\$�����S�<x�{���n0s3�G�w|�����*���Օ�j�)���T�GvV�]Ez��{�5�d�a��ӄ�!C�UT<zfT�]�X�n�Y���N%�Tɴ�f6r�B�y���0�(�i�.R�]�ؾ��l�������L��?c�q���P(�"�5��ذ8��G�.b�V.�\�,���R�a�9��Ӿ���3xRb`D�]����Sk���^���Y�;0.��|�/�U�qKS�",N|$ڨK��榝[<%%%Z��
���a�W�����NT������-�ח���M�z-�Z������
�.��i��MV��6QrVlJ;*h�eYm�т����U�'�mfS�L{�Bʼn��xk�";!7�U�f"�o%i,�:\��[^��2�W�I�{�	#|��Z��!�s>�)��鏯�u�����h��Sٷ[�Ί���#�
��)F�	0�u�&�y(�3m�B��Xl�+8<I��6E����8���Px;n<��g�Ikؼ�G���
]v���5�1�aHɗX�޷��3�Cg����D�7�Q(7ȵ�m���ƭ�&�떣��"��l�٭�N>�xf#�-|<ԁby]H���A���zE�'ÙظhQ�O��>� ��8S�Ǽ4��t�IJb���IW�w��DA�����]Ӟ�ꤣ����q���A!�Đ�1\�g6E���%Bk�=ɶ�ʝ�N���|�C�h$(.�d��?-mή:�+<�*H�ݘ�p��b���>�߳����K}���B?��j}<�g6��	�F��g5O�ǀ�)7�Fp��4�|��
~~|�5�x��9ڇ�S����gF����\Q�7��M��{�$4N��{��<�j���I�*�ׁNb8��J�^W��5s��@�����cm������sX�+SC�7��Zr?��=��$�b��(��9�Bq�Q����A���Z8��8cZ�F�v�5��.K�����]
��y�=���E���+Ì�UU1�7�32z��d��"9AΗT:C0����tDAzG]8����B��q(�.4��ͥ8��1�~=�.�$��]ZD�Χ��<Ǥ����e�{�n����s�H�̥áT�y�&Q^]`*"�;jH�%�`-�����^�IJTk��q��FON�|����b�Hu�,~aЩ{(�b�
��m�f������J0�g^w[8�ܴ�1�+d�_�:o*J����	�;hhޚ�(<��q��L�GמP|��A�;.+�hvY?��}�'�߿@�;��ͣ�d��{��N���W�e#��
4w9�:���+W���#����B�_s�L�)K�=ghQu�Tj�0�\*@��lΝ0iV6�20��U6ʹV�|Q�w���n���h.F�s��2��ot��
����ka�.�zލ���
�+�uE.S�~/�sZ4�1�ˆaE?9f��<i�x��g���6�9�4�{-Y�#X��#�	�VD^�n�l� �?�R��`�:@tbxI>�`�7�s0�ߜ�MP�]��1�hV�:��T�'�u?���"t���q�-��g�5���,w�/ixI��i��bQ��e��n�R8�S1�aL��aԠ��,Ƈ��ҥq�X��Z2mo�lo�Ex����`o�mPva��iWhW>��0N�P$�{~Pc�E.���1<$_:�����T�����lD[��K"�	��^��}�9x��Q���`���L��&2Uԙوry�ho���f��MW���L���h+�<}�.\�
w`�V�v���s���ݼ��o���bR�颼D�UM�-��
/1>BF�n�eY#��:5�*݄�(9���U�v@����+X�|��E�h޹yQE���T��:����&:D�vX��)&��Х�)�����j���z_!a�;�A�Q�?���'��8DL��N��44ؓ$\ �ڄZ�vW�o��ZQ*O����D����h����~��Gd������8.��5 �'m�ɿ���qI;��F�F��Cž�n�:IЁ��Y.%#�{+o�������~��Č�#��]����=,iW��q��x/Bvb��x�Ǵ6v�:4���@<�q��>
�v����&��	w7�9 �g�f��4����Bk3�֢��.Y����ϡ�րp�Nj?n*�@��f�Y�� :��d�m�$�g �K����1�} �1{��Bۯ��f�i(>
� xm�]���?��׀�)U��iP�>��`�!,FBK��������.Y�F-7�4��[7W�O5�{�Q9#N�S�ŪsZRZ�j�5��>U�fP1z�qDi�)|@�Ќw�s�1E!�(��>xHvE(��H ��3~��9��cX<���j����<-�����:8�k4H�����>9ު�ä��������3n5�RQ���H�w��e��k���F�Hz���L�����7˰��Kv�!�F9h��](d�AHSAX���~o㨢<���̞�KK 6�ׄ
�ۈ3���U�Ӕ}]���ҬG!��-�r:��B���P@j*ka`Pi��OȾNԥ>��cB1��,��5� �(� ���"�9X�u�&�9e"�[,�}㸂���J��Q1K����Fi��'Pj�.�o<���N��8eʆ��=�a�,��/�h��\��*�k٢�T�����O+�W�Z-�1�>d�-k7�0�퇼U��}=�Z��)�-w���7^��)??���AR�2���D�d�,{SQ�z6�_�=��!����y$�w*��	�fDb�A*C
��1��Yp���M��r�,=���pIӽ�/v4d�'+��m�z2ȱS7��\Y//���[���l�j8�A�x�u��KF�"�]0��c{Df,���ɲ
��ţ!�;s%�,����=���{��6�Yug�k�Z��?�ox#�E�E �A��m�vn�o��C���]�&���e�3�$��M=!����U{Ҟ�X����m�2�g��X��g�V˃�����.Ӗ��,���"���rw�o�)�OPŠ ��g��F���4�6l��1�~�@4�C��}�	.Q�K<K��#!Щ�G�w��f�W_F��3�ށ��Հ�D��E_�Q{}���\���s�9Fr�{���p
)}�������1�B
N�ɧ(���֖��˫=��Id���]�<k�D��-����
Q��
����<
4q���1͗-����\Ȥm�#9h����Ѐ�o��E_��Ð��W��y1�qF51Fs���tG�
FHB�O��U'�_K&�k���}�%�ؘ]���#�����nw��u����m~��Nu-n�v�:
��%��k������c@m��4U���L�NP�IP,{�Ng`�n�M��@(��K��x��kr�y���ZW[�V�
�-���׷o�'�}
�KzXÒ�8�Q�J�&@1�*�Q%B��<#�^���)=�'G^��<�󷁟!���@w*��Q�Pnb�?��L+�G��}�8f�A��<����c=��x�w�.��O��'�G���㢺O\���Z��V�\�I��7%���"��
��m��E�T>#E��k`it�}�ߠ,)~����!��3��z�[��@@P����v[��?)O����]�2��1U�wtt�W���&����y��P}a�D��r*J�_���BHb �0n��@͠g�@�2N:�c����b�m9���
%I10g�
�	K7�뜿8��'J�9��G!*�t��S�:�"�֧�Y�֔�f>�c"�WC�\��ҝ����O�<`��lk�цmA�� k4|�I��31c<;6@:��C�o%��R6����uL��-�������bz��+��x	���O�OMug��X��?��b!����n���J��伐�kL�����0�<���-�Ck�|��e�e.;k���<�4!+���
a��
���{�ᵨ]%H�ڻ'C�'�p2����/���[4X�3��|�R��XG<��/L���Hwib��W[0���_iO��\�ỏQ�7aS�5�lg}�)i�]���8���z\
n��.�0�N�bi:Nnp���g�ɬ:XԘ\�vh��e#�=��u;��)��1Z��4����FZ	��d��C{DŒ���`Ȃ��^Q�P���h`�wN"�L� �?T���p�M�1��
��.�YqE��'�X��Y���UV��"�Q�Ҟx4���To��s��f[歏�����W��.*2���	���g����{��wGw4Ey����7n)`8�,�̷1&��׌�m�0��%�]�l3�C���x������5ix���~fFy���0Ѽ[��`\:t�i�(�Ό*r���8&X}�� �t�-�+���yQ�'�x_8;���^�=r"�B��E��E�0"�t�,���>�\ݴ[o5�Q�rO�CM���O���
��Nr�-a�zW9ϛ���v�I��[ݡ��Pn�ˠ��|��
�]>t<ʽ'��m�S���t�K�*Fghp>�;�oz#i�-/I�|����?�t�PE��+b��c���΂�y�~^e�"]��sF�ɺ�#�A�&y��/�~�H�|_��A�~f
�!�%,�EU��n�����?T�$�Q6��
�N�b#1QR�����'Cn��������8����%�Um�|CD��}1�hH��6{¯,�lƣ3�Y(%��>-�i�Y
���I[:�(m�}���=H��E��j�!�Ie�š�k*$��
�l�Ɔ}�ʢ�t�r���?�x@~TbF�xZv��W�
)��z���%t5�_���4qC�'g��&g`:����y#w����ڊ@�&�G�aҡ��7d��a
7�&�0��rY����
$�z��1���Z�Q'B�s-��o_��Ӭkn�n#Yvj��F����mD�/�T��Ƿ�]��Vxv}"R���ٍd�$^�����A�c_U�P#�<0�����n�=�i5��iw�_RN��	��ww7D���-�]�vǸ~����'�2��v��*��j���d�E��al	���U�<���B���E�G�:H�_#E9��5�A���|�]��<$
��y%)�,�nc�%��G|�{���H~qʋ���EjY��eM��.Y�(i y�9�CP����u��Fs��>]}O Ǜ�Vﯣ�6B�O&���g]����+2�&�wF�c�&��>
|��AH���*g����w�~��׈(������/Ҩ�t�~����H�
��<����u΂ͦ�}��o�T�i��Z��3��t��Id%�d�uu
EG���"�i�y:���4b��zўֆr�]ȪTŔ����9H�G��RK�R��k?@�Hb���`��\���#����9ޯ��Vz���5��\&��H���%h�lD{)8o��*�L��Z���3��D��Ͼ>�`�L0�p�\�&C4��B��9��N����5x)��^���#W��r�
U����`+*7��ˏ��ԅ�L1�j>�I�c2]�0j+��ͱz�>B�HȖ��f[���h�ZPy7#6��"֎3�����ִ�ˑ��-����`�M�yG`;�Q�r�5������wQ(+��gf�</������?b�z�9 �ќ�̫M1�Y��~�p\�<��Vq:@�z�6@b>�jڼ��n<��ñ��?Lg
k��I�N��-��	�"i�(�@�4Tե;`�4�����R����k��*w���kr���m��#��MP��遣opr����F����G{T�`�
30$�}+��F籌����L��>G:�!{��}��!qE7e�D����l�1p&^�)v�Bƌ�{�s֢hY�I��c�}��%�Z��w��b;�L�**D=���Z��y���t��𢡄��s�Ѩ��OOn��v���J��+�ȡ��i9.I?�)��z�0{�C$�,s��%�����E<��J�=���G"�8�qM@G(���ׄ�u�
)Ӟ�Zc"���)'ާM͵}~�1�h�W�S}�,\�`A[�4L&�g�X�9����or@�;�%2/�g!̄���w�<����^ݫ��ދ\�O�}řE3�WI~O��h��n%��T�='%�����RP�+��$�2��'Ս�U_;c�?{��/ 6=�B�g@]̂��/�y���z3��
4��s�tQ�匍���
�o ɏ�[,�"
��}:�&|&�I�8)�!��.,)��z)�u3w!�:4�s�ذC��)&=�ޗ�f�1�%o���������O"4!�ካ!��߇�|'������N�$��=`�z\3?�<�Uf

	��Q(��|�ô��<�퐅x�dB!T��rX)�p
�[��ƃ
��u�*o䙀��J��/zcw�ԅ��و�z��0�����.$}0��'��6�2��n(����p����:��{�7G����f�W
<�Ԅ�0��CI�@
�$LHI�K�-��5LJָ��ۛ�,�����<d�<���P
.���?�TQa �0�i�a���Z���!�zcB�5a�ɤ���=]�����nB�j`�zr����16њ����	�A�����ٷ�*����G�u@����k�UB"矰̑�yo	�X�L[#�s�F-���!�cC
��^;Q�I&0혈3����h�JQ{8�8v��$���nR���`H)Y�x*��}k2���+p=�v�w��c�?�8	���+B�r ː@z��Z>.��v�qY��ݝu�᫽�|�W�6U6�a=v��:$ʰ�c��l�y�tx�B8��Obh9����1������3;B�H�g4�������n���	� }G�TU0r6�ȃ����W��D�0�x�؁/�V�%/��G�
<�qE�@IDAT>�3�(�Zr����n@F�<�~:h�V�I���fھ�9��ͬ5�b Fi���:Tm��g�ʤ+����)����;>|c��'c8kh��K�v[�~��湬"ߋ\����?]-������`�;�\�O\�	�=.E>�Y�}�H�l)%('�'��L�2�a^M�x3&�R���G.���l{�h(C��u�`����~��3I9�b�nw𜣱�~�?�ܶ�D�I�YZt�N�
6�{�7�>�a0*�P
��A')��7�{�;�q	#
�L�{��-f_n����m�F|��a}�>�4�y!�*�F��ؽ��{؄�޷j1^"h�)�Qx�-���Sc�;�]'��KW$�6
.'ƀ{"�8�y�0�ݒ�M������~�Cr#�:r�pv9�N�Y*�p*(�*Hn^�j5��\0�_�~�1�/m]��/��bv�������7��k�F�K7v�h�jN7 zP�hS�Ye9�����q3�E���|haQ��1?����8i�P�����>;�j3
�:��E�''jNiZ����c>��o�B���1��g���h�z�gByv:r�/���Nq�"�q�|*�~�=�Js<�' ��'�D�7t�� ڠ+ ��G��z�S�<�ϰ�m�x�y���
8��nX�5��jf�K��R�[�/�����"mDmvҏ���v%/4!�����A����}�\���$Y��?�l�����!�آj�Y9��nn���WC�ް�1HD��K��"R4$`��Q�Rh�:l�O�]�䭧_��eJ��J�ݸ��q�؝��I?�C
"�[���T��6��Q��C��G��{�P�9xNq�%���#E1餸N���Q���ӯ���q_!EFW@��q����ك#�����Z�� u~�����SP�ǂ4�n�$C1����#���nE��c��b��4�c�E��uX�_�Z�����)�Qd�cҴ}�QY���6����}M�N�C[?9��&�c��<�����dI�[�##��́�{�D�%z[�/�%�|KLT�����N`�mg��1�qD,N�܁	�P�QI6Epߚ�3���<KI�
Ir'��Gq<LI���}6#5�)���%^��p
�"�4��?D)�����ԋp�fm@z��o��#��t��de&��H-�V�|�6��dn����f��z��@�E�S�~�]��$��"Vst�b��4��$a�ZW�ߦVWi�40�m�A}�����;���a�TJ�"kx��bE;�G�f~� f�&�4�~E@��B:��
G4�{���lR}bX�+�1��(�H�Y�&�DTa;��득u��}`��|���+�q�-�=�(0u{w�{s���3�X�����=}E���D	$�y�m<�<���и{r�sn^P�`�
�`�������<눚9�O�1��C`i����Lw@,�\�y��n�۲{�"P#�Ep�|����cJ��>�"��RH��<��<5����c+�i�ox��`��ƍ���A�_�,�b%P+2������dX��'�,+�?�.��MWd��]&f���wo�~&'�ƿ����0���T����6R?��f�X���,L���1{�3���­PI�̑}$�$1 �����^��쬬��&e��ߟ��(p��t%��f�L����2���2Rse�ڙ�R�䦦<Z��`������R�\WE��1I)E�ԀgF��(" �5�?���'�;�F��9~T��
d���v�<�%��v�#�9xZ�Gt��;(}=�(���;F&~SO)ȼ����q1���0:�X�ALWoF��Ӹ~i�Bڱ��1V@�h+��Aђ�<8��S�v����O]���@<\G{M�ĉ�q3��(�&��B��Nr8ZB��qJ���r\%i�Mq�{g�[�%Ԇ����/8�P9���:���b����SZ�Rf	XZ�)4=�/��P�|����{%�E�P�-�����&��x�ȴ+�UvY�Zg���+�M�[���3�vˆ����zĪg��OH��8v�1�|���&�y��ZUWo
�M/ቔO�sϺ;v��`@�/�P�ٟ���!��=е[ê���ݮ���5ٶ�$ �z[Z/+�(|-o/c{�{%F~�"��nt:�w���eJ�L,��h������!�꽀�e�@�����)����-n4������pt7le4u.�"5����
�a-�t=C����r�Ong���!_A��)0tAPT�2_���=rKG�yF��+�h�l~Ն�er��z%���m�g�>� c%����7'�g��
�5�w67�H&kk4򅮫_�yM��{���'kFq��zW�196���KR�)Z�CCL���-�خ �a���L���I���Gi_8b�ŁH�]�!��N]ҿ�!��8�A�I)��BjP�H�LO"J�C��o��u�ځȭg�E�x_�}�;��z�5Hr��p��Ns�8h;r�� '7��Zo�U�P���H�}_O>��[����4�c��	�*ۻ�i�f#�|��V�hGw�%�@���	_��֙(��n0
��vOv7��;�ű�p���:X�������̙��I1hå��C�K�� ��S����.�L��7�v!��Z�_%�#9�C]��n�>C�s��FU�wkqz��%Y��=���cb���7��;X�W��H�D�'˂*�u@�y�����E���=�w�z��",��y!�o=&�O��]BI�FBX���H7�:̯PhT�R��O�̼���ш<~gӉ�	X=3%���s%�k��
6� u�<"����s�{)��f4:\q��i�����L6�ڻ�*�4�o�b&�I�ck��J�O�����O7�	(Eї��ER�3����usƓ�r��M�&�����D�?��D���=m��r���m���$�Ҹ)��O)�c6pfZcZ'B:�;����O?D�H5�b�l�Y�??a��b�M�>���^�9a�.k��
RlXV�X
M�r�tD��~�w��-S����y�H�^b�g�,k6�3s�TR�n��=I&�?�`���j�����-�Z��5!A�{�������BZ��8��׶���޵_(��� ��?h68^��	�^��x�Z��J�􍤺��S��N=�2�A���3�d,��tE@�:gb�wmq����kְ��L�-YP<0���⎇e�;��՘4������s���y���wFe�����7~���?����g2���j��SQ7��5�p�
--�Q�ڊ�Ԧ��B���
�m�)���'�1:@|�]�l3��z��+���ߓ�!�[B)"!�C��o_��.�B�BUP<��(�V��SjjjRv�[��)X�D�v�F���k1V;�Qp���4���!�:!�kn�ѐ�?��%m�|>�$<	�WE3HT�]���lO��1�9|�!�����W��c���D<�@�S�m4vZoO4�<`ӿ�T�6�B~�Ѫ�ry�Ū��&[�gx��~op,JF���e|���Ҫ�]R��{��dy��
�e����<b�g����~�dHU�>�4�nJ������#s�f���]�k�?�H;��hE�tC��}"�#KmB�����x�<�مi+ں������v���=��E�N�9���q>G��Z�Ľ�FIff`���z\�/���ه�B�ʥ��Ƶ'&!9%�w��m����!��t�;�7e�<�Ӏ�2#Dj�������ٛZ[�С�5�j
ɡ<
����c&��G��y�ZV園�_�o����%R�<��T4�]�� ��
�Vyz6�F fQC=�
�c��]9=c�ڟ�Ȼ�f���}�
7���=�g]�rހ�F_<�f���q���"�I����=प������}��R�^�
� E�Ʈ�'���Xc�ݨ�EeA�-m{�-��g������D�/ޏrggn9��s���}���ч�q3��(ڧ�����m�q(^U�4��]�Z�c���/ƀj�~�6�w��_��'�E� 	��&>6!a���{�}N��TS�'�>f0�#�n�(��?�1r���EL*L03Wc��{<���|�?����d�F�����K�*NF�oVu~�Rm�;��efFbQ����2�
_��p3�nڋ�1 I��.�na����� ā��:Q�g(��M��HuL(���%�+�_���`��&,En�<�k��"�~x'���d�~ Z�����<jQ�E�m���J�=�c]���g�t�5�s{X3��9�G���_��8V��
(�����OB�L��D?�tz}�u�c�ձ�s����#���Vx5�Q�"�|.�	X�:̭G�\�Ă�6�hL쑺[
K��2GS����?������C�7�N8N�^�_r=�x���m@(�G���yGM�:�R��m7 0s>�^�.D�ߦZr��}�Fhs(B���8�� ��r<}�Ֆ<��c�V89/��݌���ں�N���2�>�
X���؄T��ߺ��ں��Au���^��9J���͵�ڳQ�3�ƪ_��~���ќ�'�-b�~�pJ|��^�`�5��$~oy�*��F�/:j.��7�˯F�W�́�c{9�3
n�ș���;�(����.(�����/IR̳Yq����=rƌ~���j��0�C���
4�?0)�,�~`��.�Hʹ(�W
��x4�^h��n��^7�!Yn#�����d�w�����������#:��Y{�^?`g'G
�m�/��M'#�ܿmGw�� -67J�{�**=CT|��]�>���19�z
Ȇ�aXV�
��cu6�ɣȵki���y!�p�KO�O)�m�R��k���^Ó�C��bYZϝ ��|�d8T,ff �?�K�!�S:����6A۬�������_��_�w�H�dO4�2����}I}K��Q8Ӱ�xe�W{s��{�mۦ�zZ��;1�?UT�>_�yL{�T�H?��~ޯ��^"�(&�v��F�A��&/����
k�趓�륅�,�� *7��y�h߇%��#��C���>�}\(%I#�}����DS^�Ήh5��{�;b����o)
����l�*��f����1��ԱN���7���
^��؉@��y�ɰܬf��4B$]���Ct�]Y�Ņ)R�hQxִ1G�8#�R+�
���Yy��W�:��L)B	���b��Dž���$T���t��]_d�=߭�E�oa�Z�@�@���hn�a/G�
���-��N3ϰ�
:U�ك��L,Jo�y��U�=�;ý��9���=A�1m1��.v8�]uo�Eޭ���pQ�����/"XdLTw�k����# �%ۢ吜�MdKG�֠�F���tC]�Q�B��>FZ�g�i,�l�/�̴�쌏;B��)l�ڰ��羐�F�ܹ~Pnn���Z%���d��b�
j,�A��q}�,a�Xi�<#�6�]�����h/q�=��V���J2�U��3�D���Zh$��[��F�Mr̀�7 �W/Q/x0��ݾ��cڊ+Ϟޥ�����cn�?zL��n��FԙFRڵ�^��90�G�)��hn���&���V\�:�
g,W,�ھ΢�ڲncL~?�z����T��U�����W'ٽ���S�Fk�����{#Y�~��֔w����z��=cdA�Uk��j��-�
�h3&�o:Qƅ�;-�X+H����0v��U�%W&�汞iM 6�&�C�㌠b�F��&ȫw�N"�4����/�gy���x����ߑ���=o�Z���>��?����Ϲt�f��!� �FƓ���U�dm�oMSDG�a>�"�~���!p'�!�Y��!�����*��L��<���rt;��dd�l'�}fv���
jϜ�9�D�t&�\d���:�0kX`��fٿj��ӷ�\64�tV�Re���9`Uc�<��800W�	n�ۍT�QۤEı�h��6�����q�����ȓ6Jl��j	/0+}TItv1$�n✣�4�d�T�m��%�M���!���UD�m���>Ư7s�L��Qj�;~�|S�,xN�8v��7�|p���K�c�	�juȪ�s
o�^�y������Tȶ���V�Sea7�g�9Ė����F��� ��Yw��A��uk?;��[�F�z�d���K����n��
8�@`�����ӟ�"�4V@�(��tׂ>����V�a���0�j�|��X�h���*��5^&4׽�(�D��u��1��4(�V�IҙvJ�C�T�UpT����D[EQ,c
�frb1o
JD����'¾^����z�Iv�ի-ل�٠t�7=���=��R����;,!�iݶ�A5�]�J,*G;d]�I~�BSZ���t,����u�l���}��^�(�9�N$� \j*�Ǻ �40���1
���i�Q��0���"�D��lG���g�Ioa����� �fT"(���|3���͏~���,A�C�Ϣ�߆��������fY��9Hڣ��H�d#:�`!}h_WO���gX텂qSO!Q���&I�h��4��oA��)#zxO"3b�z\9��,+@�2'+(�f�>�dmMMϞ�������ޚ-�ܣ�Ʀ@�{2�,m������ӚpYGkX���5h^�X��ӚYC�mo�M������E|���%0muK�U��#���'�D�]!�����d��珱��*+/��3a��!��đH"A��o�ԁՇ�J~+JN��(ut�I���+.�^z&�b�
��́�kq�N�$�҆�SA��O��pq$A0v��Щ����+Ѵ��}ӑJ|;�݊��[Q��
��W�2�a
�؉'H�m�O�(��	CH�O�����^yŋ6��[����+�o��ut��C�G��z�H]���Gv�c�f�|�״h�b
�b���o�k����
n�&�:LE�f��D?�<���?��z�2JD���q�L&�ٵ!�LS�!V��kJɑ�p��;�q�DF��	�m�m�P�κ�uY��ۺ�'G����jEd�@��|���4�`k�S��ܼ�	��x_���}1.׹8�JpZ�e���m�M��"��h����e����i�F��0MK*x	�RT��mfKǷ�J�@�5��
�ߩ���Tr���e�怶I�*���Ww��	�_����
�1Ђy��3Þ�*��I���a!А5�5):=d)^ԣ*�XRUn�НH���u� ��7���v�}�&N>�^U�E��r>�~�"�V�1�TH%�i�O�Y{5�ʛ_l�l�v!-9B[\
M��B��_��3��9��Q9&�{�]t�z�=1Ü�kn4iv����k���$��fd��I�C���h����4��M*�>��J���݁����˲��^`7@1�a��
0J�QoZ;��P0�B�N�W�#g"����"��9���2�gb�~�;tz�O�1m@����TۈR�ߺ#�����,�"1�[���ąȂh�e\��d˲v���V6�3�ǾR��~�C�>�gX���2���>~�y�$޵���?��Q̯�
��}����F���J
N������}R�",����gN��Xn�3�`˹:���_ь<�Y0���~0�yS'��g�\�L��>!��D�ƈ
O
4ۗRX��A�^�*��J�i0��B� VH�L_
zuXW	R�i�`��1��b����O…�/���!���N�Ei����4��lhf����z�D.���-({��Ԯw�����@��@T[	��o��D�o/@�ɂ��F�ҷ��t���66�GV]MW��G���C9kS��sh�D$+��~�-��=]��?�[�~:��p�]���a֤�,[��#��o�	����oG�2C
����:�m���ߓ����{aV�����GQ2!Y5.2Y�$T�ԭ�^�pi��z%G)IIZZBf$�EUy)�;�h�f.
�6���=!ɘ� �@�y�o�"���	�J)����ē�+�"��˂�'�M!�̎S��ck�Iꤥ��,��`F����
��,m?��62^��=a#=�1�Z;Y~��*�8!�-�K�+���u�0QƱ�eD*) _[9��9��H� n>%\�h+��>���x���;�V��@�>�L:�Gӟ�9f�J���[J���h��822�
;�\�b�=?;�EG@�H��h���ړ��.�A?�}�,gM�T�����k;w'7����l)p��J�A�S�@
�,�`���䕸�Q����z�mo��eg�%�Sg �L-������P��}ͧ'�|h�2T.��Д��|P.?�>�_�_Ua%0T���5�9Lyt+�<(��ؚw"Ԕ9�EY�6i���{���A�f@��I��J���.��w=����o"HW6u��{��c,�2������ԶH�!3pޕ�7�a��¼���;�'Cy9^�/N� /s45�S�K�r�_/H;U�;Iɷ�&j��$PɆ�K�xd�����4;�(�����C�S��?ѡӵ}��2���!I2�☻Qml����"�ԅ�3‰"�Ћ�0��P�`�9�\l�)���t�ɢr����`(K��k��E�s<�{dm2�]���~�n�@]a6B]f�GM�U]�|��IWV�(ZNex�o߼���o��Mc����{�d�=�0�nu���P���{�u1��0/(��ƑID��&Nd�{
9�S�Ó��@���2Zj��Ll�=��ͫ`���Tj���%(1�e���A�:�]s�dh�#�5^o�#��m^Tl6���Y����'�1����6/��Z׭l��!s1��Ǐ�	���l�^�~Nk^�R��#�������^Fޑ��N]GU�}�;�eZ
/�1��+g�ˆ����؏5���Cf�)��
���'lm��
)�=�39
���e *�f�GդO��T������N,XDq(>���vc��To8�Q��gAƔ(�?�\�uAe�p��~��4��.ʮDZ�
`���>lr
�TlK�"���~#H�q��(��5	�����	�I����w�4����S ��x�����q���ٿ_,|�_��n����f����CaINg��]Ӳu�(g��k[BgY�6@ɐ�&�o�F)��r���0`n{j��4����A�@ Ԇ+�5���
x�^�������	��rd�h�źU�X�)�RMN���l�H�{�(�J���}���;-�HoKG��M��T�@����/Ms��I8m�:sQNȍ:l),�>�6x�݆��야e����eh��~�T[Z�}ZA�؃eY6-����e�y���ie^

��Ҫ1�:��m��3,,hvʤ�:��4��O(=m<;T�P��Z��u`q-�<�QE���������m@b����x.�Cc�u�
���0���|D��uu{����}�m@�8���!iVE�.;�8'.	A�˜������P�tC�@$�F�_pQ���}�	}�b�ݣ��bQv��2zl�{����;���IHzE1l�ƶm�*B���=�ep�R���B��/Ñ�=�
���zjEf�H
(R����%�8�`�
�EFG�������?o;�(�ΰ�;;��tO:"M�g��{Z�O���۝��Y,���:�U:!ܶ�m0HѼϬ]Y��aw�}����&ߣ�00����iXSZ&�Hyny�w���&$��~<�z�j>ङ�B��@��edd������3��	GO^���>�ܪJ�¡�*���ECP��x��[�C��c��&��/˄\�+aF��Dç����p�*�UD$�gO�^V1"3�&��R0��z2�8�C�p���#0k>��&�QfѼ�|�'<k�I�k��Вf��WbP�Ɗ2>1�j���lB�㾭�O�;͠���tE)�~-|�k�)��}Q�.��[F�f����d�����B!e�F2����q�K�q�߻o�W|��|z8�A𒤋�0����:�\��&�ő,�����X�)��(��)��`���1�-m�5�({n��\/�:��4�0}�`��9�䂤�����=�a��n��
|�%xɵ3}���7+
�'�]�����K�b�#�$6³�;x3x��21�2�_,��)�G��~�R\�X�����L/�rT0�
ӳ�e�ZM�Q7�|l���'�Qq�=����a�۽�J���|�޿?1	��B�[۸ϋ��Fhϕ�N?�uA&�ڳ���u���6Os�;Z�k�(e9n
�����Ђ���%��?���̓$����Ly(-
��[��)y��23�[r��И��~�O2�m+��5x/y'�1–c8-:������5�����Fh�����@���M�'��px�9�蝲{38���T���L�����8�x���{�F��V\lur�L�]�ַO�0ftפ��6��A�Ÿ���+�|^ލ��X��ݺ6�L��>[�\�+zX}��dh�O
<3��������	M�SތŒQ���3��PM~ߦ��`)�䜃��E�>�1c'I� (�lWN_��O�������qy����]�<�\C��	���߻�h��N2�K�������eg�r<Y<��0B��<����ѵ� �k��;�����_t�Bϰ�Ӣ����C2boP�7�s��Q�,�6���ZXX?���M(�VL����(�N7�l��ѸN��A�s�5��� ��!6���R��f��.�>��Ж�`/�V�ڋ��ᯄu��`]U>�Ɋ��j���5q��Q��v��0�k���1�n�k,�; eƀowa� meb��p�$�"�Jٌr��O��t���R}#^&v��/�/�_Q������c�Hol��V�D6xd��F���I̗D�O��֎�t�\�`�
���J��p�8�T�TS�rX�����M�Vh���p3u"���$Ҟhe*\3�V�J!����9��ݱz���J�(�A�Y��?��?�'�j��g�PzH2ISX���e�T���鶌���Oq�����S��G��$��O�ΐ��,�}|@3()	N�Zc/<:��y��s�jJV�%���
Z�k�����T0�S��64�1k�m��_��Rr�������f�!pnn�%��⴪S��w����kY}��J.k�i�|����##3����^�ۭQ��F���[X�b���|LO���f�ed�w~��sR~q2�]&¥����
����nM{�P(� Q��)�,k�z(�r=����[M���TN�sP%9���W�����j��]��v1�HB��휬>�m���Xl,����)����Z
��Vb��z�������
DZ������=����i�
NM��Ca��
����,���W�R�ӊ�C�bb6�ƃ���S�w[�o9!�a��n��
�� ,�3P-y��F��:dʁ�����>���=՛,U�b�<ٮ�NhT'�U�q��ēJ<Ǟ�J�n��g[���ss���{5�7�E�8K\3�~I���V9�R�v����<C7m6+��y�����N{X��)��WZ��G�}���%�:oh;I �Hl
�mo�7Gi)#@��X{Tu[���a"Z��8,���f]q^{9�)1�]�{��2�a��/�[�� |Ǘ��=�)��'e1�V�jjl��B=~2��|Fe��\;m���ݡSN�C �cYW8�}1��.�A?z�ꃹ�.Vmm�S��D��EE����M�3?�9��I�!�:��i�gj�q*xQ�=�#�&ƭ�_:
]��/��hZ�@x��Ii�n��w��v�]yk@�B�<��dU���:�*�7K�R��RFRv��h�,6��+�;�T��?�<X�9�O��U��'d3��hGpG�I�X/����13T��@���:����J`��%&�������s���>�f.Ou���k
���`�p�1��B����70�\ч6Ҟ�-u"�}��^~1E��c��!ՐQ;8P�r�1R�\)�v���$@��rh��)L��y����h8����EZ
�^��D�H)$�Y���tLYm�qd�^�)���,Tɦё���:]�~�fW��ؒ����/y!�5f�"�DH3�Lnh��g}����
��=n'�v��8;��|x%5�ˢfO74�n���H-��܌*Ο�UvN�@?ʀ�^S�p����a�B|@�O��a��H;���-E�ޑhC�	=�mh�ɋ"���X����CX��E
����XR�)��:ASxDhd��a������:N���?	�s@�<��ޱ`�	'`H�]��,(1&���Q%f�C��F,-�`�Pz���	xtn[�����s��<�>?�p!&L��i��0�J���]půw����Z�`jOnn�UqAϬ݄����@�&���+����o*9�.�7�|��9�g��{�`8j<j&�"<ӂ��{S��@��8�G��H�]7c���mn����.Ց��%��ٛ�,��=0euK�
+~o��i[Ee��� >V�ɉ%��IAL�-HJ��[AW�8dD��h�m����|�	���#��gGf�y[�;�u�w��b6����tS���2�tc4��ؿ0~��'c��9���˜"}��.œ��|��5�ӢO�A@�3�aP���������<
U0��[W�=O�c�����6��&ą8*A^^����.[��x+@ޮj��-�փ��:���Ov�{�s�BB�"(ka�{M�.4�&Yuq��y4��Y��܋��R	�Ȍ���z'] �g�MdNgؤ��
~��M��C2�*�۹����G��IXz�B˔au_�lq[I‹[�hǼ��e�9�$��Ǣ�''f�o�Tl9�8>��<����궋0^���Ҋ�1”x7�\�..8	�ZA���4�T`X#�e��[�H����.�x���w��*(#G���,2�CB)7AO稊Z�+)�����A���������J~{k��DD\����4���nD��P0qb:,	'PJh�E�&���>�/cYI��=.�-�O�A�Q'�5���+a��	�?b�3LnLY�����
�d4jC��T�K�aFY˸k[��{���;.-O�G'���D���࡚uEqWΫ�g�J8S�Ev�3���������i�Ḱ��<��K�V�NW�?\�6щ���pL�?!�7	+��
��#L{�S�W�����.�)��UD8���{��#:���	#V�ƥ����+p.3��И@��ma�KPBg�^�dm�� �Y�](oCe�����Z��_��;���2+�@)�f��9&-}���I��LB�CP��]�T�m ��d�lP�xF0:������-"��l7f��*wh|B`������;�;���`��$HEƍ�s��zkjj��ed���4�
x��ssIJ��6]�ajzmj����c�����
�ˇ +ู���y{�'�i��.З���#ڟ�{_�n������K׺����e���%/>�al�k�d��e�����hऍ,�f ��B��\��D�k�z�|�UU��(�1B>9���{�v][��4���;"�S����˨���>�|�a8v����"���Gm���
���@R�������u�O��G�N�iTv�.����i'�A�R9Q��[���n�A.�T
�NoT5ȲI�C������\]�9Ճ�#���c���y���=u���M���P��KBZhY���P-�k+��$��@[�lЄ�p���_u�l����O�A<���e�l>�,D�э����?+Ҡ́0g9j$�
��2�kz�R�T��tGl�`a0Զ��׷�$	\��[�"�F昬j�C�)��EȖ�N�q��#^"t�Ƌ�gB�v �FP���*�S����w!#�ꔒ��!&�(kЏ(&Ă������.x_a���&*��{	�7x*<����W����>#�?�f�w�'��W��2��F�!E�
���i:ۦHLюN)��q��k�^gD�W	E'`_u1-�>��ʀ����A?
���~s3���+'1��/ߋb�R��8�aÏbqI?YY}_�F_D��7����B���8�~X�:�A������$��0����g�q{��9��~`�+���O@��=�
H�w��q 5ځ�����3<��W<���!�%�,G���OSGMu�g`��������@J��M������vл�c�tY�Zj�����ŪIs�u~�Z3��ɴ;���ƮâW�d����hkͮ#|�Q�ݵ��n�ֵ��XЎ@	���m3����kHn$�1fXq4ҿ�t��0��U�����l��Z�E]5���A���^�'�9ߕ�F�ڴ��
nAS�O��%�0~�Vڴ��O��� ٲDc&�6!��?.�C��?"ꞙ[�J�mj
�g���2�U�B���D�q%{M��K�C��ٌ�@��ib�&�CtE�w�q��b�`���bZS�#��>	f/3�5�m����!�r!P����|R�?�x^ٙ��x��1O?,$�T��fmu`�s�4E����M{�{L�\�j�/�×��hף�XCq�h��hj���ڝ�5�zƵ�u���w*/�D��ljy;AR�
y�C�"oN�ϳ�����e��o��;�V�g��i1�f
c�����M���6ǓE����W
���6�e}��[�eJtv$4O������ج� �d�SO�fMk����@������V%0�
��O?�Z��]w�8 ?��a�5����v����#=����A",™ԫ
-m�4�o0L��&K&�4E��'勂^y��M��=�U�gs�f��	t���f��A+5���i����';)k>� ��~wӽ�2t��ᄁaMS 8�S{���N��Š���C����L�ߌ.�5fL�{���շ��M���B���+��0�N�M��fV0Z�*c� �]@Qa��5��ݶ�פ�V�����b���v�g�˖�������QQ!�#&~#KtdN֑JN�iOʔ�R�+PI`A>`�D������.j��9���Ś/I.�+(��)&y�w���2|t���1T��CbD��dj{E��.++�&!Pfz������	ڿP�aa�65A�#��
S��\'!��	���wue�k�6!XR�� 4�Q���hL�h\IN�8`{g�Ƴ���h��:�|G��`S�Ϙ���-v��{���B[[���J���B�`�cY
�����
UQ��\�6>6  
y�B�\
����Q\��fMqx�$Rd�e��*�J}
Z/�?/���S��S���-"}�L�V'[��:j#��|'�r�z���}܉É�`��7�$'P6$��F��c ����}?���Qh�rX��&c-�~��Y�l1C�P닆�_ :��_����o�	��qy8�yo,\"��gU��x�z��))�`�L��X�H��A�d|�'��Q�-v�պm�=Ѷ��ο"l8�A��#�����$��h9����gW
��D�L�������D�E9�7C�e3śv�#�tw7�aSC ä�e-�Y�eu'���w���Ձ�!�T_Qd���aX-�(�<$j0�(F�e= 0�Zh���!UHZ�,�2M����z�X�x̬n�'�`���l���쵲f���'W"&u���_�����˶{B����U��g��c��������6�P�񒮤W…�Ao^���`´�Ƞ�#̾I�Mt	�8��0���2�[���A�Py��U�����ʬx�y�"j?�˕�b��؅�A�_S��
���Ʒ��0L@IDAT�v|���n�CS��	�UT�d��5u�	�0rC{�ϖ�P~��K֘��	����j]FR�<�=��)��#�6��	�F��hV�4�u-�տ�A�f@�:8���<L��0�膽�8-���
EOv9�2;kV`E�?oo_j�x;a�7�DzYu[��rE��:(�+RT����|W-�vSqN�ĎT�N’8��[^����k���}����37�F[�^ػ����z��:$Τr�1
	�Z�?����&�n;����.C0A�W�@���䓢���	�\�1G�&n8'j,[�0u�Ά�d��(%���P$f<�Qjy�-V��}KA�S�*��!�>0�dOդ/�JK�a��)�g~c�&xp�#�F���珲W�=&�Ȃ��^��u�S����$T⨣mE�����e�wu��!����x����!�LaY~/,��t���5�kА�6��A��)�0��T��N���}���N;I�7ä΅�rz�hI�����kc�-D	 ``���(�W�
��+M	[a�>=(͵����8�g�!˺��Ϻ��e�e&ˏ�K%u��{�i�yq��a�v�:5�q_,��O1h��Ƙ���C����I&m�)�U��v��]�Y��
�Sqܵ��0��������S��	W�m�Y�Q���.�0��K�(�Ԃ������9�t�W�gE0�ކ"/[ۓ�$�zɵ7�Jd�F�SV��
F0����:QQ��ըf�CJc��gz÷���
-%Zf���ڿ�K%Ii�N�oU�ʡEɁ�Ir�
L�೽(�S�Y�*����{��E�_VM�Ů�s�q�H�W#T����>8Vݮ�m��"�%�\�l��AG6�y��n�V8t}K`
�|�EVb�!�*���٤�sq�?Ց�qi��}�bYpR��e�ִxO�����Ì	K[B���Ϙ��̙P~�`4f:��PtI�Ȣ�}��H�74��ֆ�uɹ���fݻ���y�b�<Ngo���r!����u����B^6rp�e"�.?LD�?Q7��
K9��[�~aY�7_m��$}u
>Ɣ�)pʥc�WK1�������D�D����>E��a@2�y�T�܎�Usz�ڗ�c�{B}�F��W��@{�g;�
$M`��, ���_&����n�X���uD�u;���{Qj���4��O�=셺��Q��O��o��ϵ!pr��N�?�%�&�틪��=�U7��16�����0�?��8XN0^Gm����rHy�R�p�Xl��8�!2����U�$�w��\
k���E�C��9A��*�e�H[Bp�$+/�1gkLdeyvv���"V��0�%=А+�MB��T	d���q(��]>�sBap�}/u��u�Y�rƜ�7G6����̅%q��C{Z����&SU����ۼM}yZVV�*�S�CxY:`�D�,��큅����e���T��|�Ҝ�ms�s��m����u6I#{b�YW�	�}!�i�{ՙl��{��I�P�a)������ }%��;��;�P��B�I����7.d�5;7�aź�B%q������mq�G�Lm	ҭ���tc<
�\;�'*='�q��yU��:[QT�1٠ߛ���B%Ɨ�k���ٱgՙX`�Ϸ�`���k7���3p��@| ȨhH"�h��ͽ�K������r|7,�VX�/4u7O�p݋\H�,���Р��n#�_������^�ua�d�$�V
D�x �<�
m�ߛ
���G4�A��Je-�y,�K���=���E�:����.s[m��B|O�k��X�ݒ�/�q���T�����a� �Y����dD��Hϟ3�z 3��c�;��Y��P���9�OA�Y� ��`ɢU���D4ҮO�|*���z��#/�����r'��#d��=t,���j}�F�N/���#�#i;a�Z�򙴓{�?t��S�l0����5����,��,�oV����X�s��M�,���W2%����B.�I<
Ʊ6�˔/�Ր���}B�Ы��?��@�-�~[�@� �HQ����A=@	A���L����WO.�ܙ��/�x�K
m&�3���7��YC�G��ɜ#�'qlB�"�9�����P�w�0{�ep �g?��2qwN�����&k��M���7B�+~2P��Ɖ�'�1��OVa0xs32B�k|#���Ӧ�UEE
�u�{I�s��%�F��K�Gp?$�=Q��2�OZ��'�<����� ��8�2��*�v� |��@>S3zۻTF}�`[�*����8�#�T�cA���1��;���r\4�8���LB��ţ����#vE�P���X��$I���H#����8��=v�xz��4x
8Ĕ�;��PU��Y�P4��������z�i�Oi���	͕�$�"�6�ţ0�Q���G��]`�ܸ7�:�-�������{9)���9���c��/��>��r
���YR�N���-�^3�I�>����#5g��S������E6�
MZ�'��x���*��K[���`��B����=����5p������i84z�۵���X�`��y��"��4�_G��~9����#�@ea>�d�;���sM���*�(8j�k�Jh��F��a]�g��t����߶z��i~
Y�o�'|W�Ed&t"��h������3���F�4~�d>b
{ P89�^Y�SA�?F€�E�Bн�!��v3��v��*S��EY��c�~�o��7��=EA,gt16j,c��
U�nEA�^�U�yG�V��D]2��������-h�E|��p�1��3b�T�iɱ��oa��mv�}6����g@�J����)�	�*Q&�N:}(�ބ�94�!PT����K��p;���ڰ1#[�ko)��UVfߪls^
?�2Y�>E�uv��JSO�h�%�cO���]�ss.�hz�����Y�M@v�bJ��x�F2�`�H?f���Mut�]���
�L8��!9�ZDa\^Z\t�^o�Sm��dL��P�s
����&viݏM|>��0����s,�倿������5nk�k&��c}�����/z�8Q�]8��h��n���d�lq;q^b�����_�?���3j"�6~��EWd�Sv�^V�u��h��]'�*r���%�N'#��L�`�t��l(;�8P�u{khA���H�.����~�����,.
���H�
�!��-�>B%�����T�({���q�j6����<��S6$��n
D���z��s� o�4z��a��M
%�#}����p���䋑,q^�������|� TaAy�S���D��\�z\C&�E�����B�e
y�bј�nw��CjC�]��%7��m��h:�C� qŽ�j��3����iiCW��&�:�)ZogaRZk�7��ꐆ>���c؈dp
����)�as�����>��,��Z�
�m��Vd���$�ypI�,�+�6SX�a�A�0he�g/��ᶁ�Ƒ�~:���#m`��d����D��*JT�f�0�s@۶�m��-SQ}D�c7�,[a�Z�q����ѡ�F
���՝n�MV�ıdJ|&�w�y&�#�`���}92����ź�u�*�RY��
�k�P�u�[jCʏ���o!�'ϥ+)���{�{�E�|�yC�V��#:�����W��= �L�5%%� Ǔ�^�!��2ׂ�����Gc�v3����߄�������?:�7ʼnOvY�g8"��1o�;� ��~4�Ϋ���z�Ōn-?��
��-��|��J��Xa��u�T�2�[v�񗫼w��3��7[�J&�D
��@E�#
I+�֪�pw	wҷ��t���C�w���^�
��s(�?��近��>�A.��S�<;O&H�{}I�6��(aN���32�&�'iO h�g|��3_>�7������)S��I�$ͼoP��3+�����m8��7 �̹ ž�t���Y��w�����CG�v��h��#�{&���Q�g��	.�wc�L�D�����჆�mE�67fGm�G��1����E�x-X��?0l��=���oa�H����?CA�?��E����A��tSP���F޷�nT���
�	����?�?�tL�����G��MAg,����33{6ך_�d!�Ru��u	��UT�3��S��& ��e�+ˋ�V��Pz��󶴇�']r���h��R�;��>��)I��҄��JN-��+A|�1�,����S�7�Z(�2o�=@$ڗ6n��Pj�C[�#]�`�ۥ�X���0�[���E��*:�x�\�%'���N@`�rHv�S�T5�ֈlצ���K�R�c�I��\b����%qoX�MF�B�a����KK�mk�n4�U�E+P~����(��a�'��w1�K:<D��v���T��"S��sc,,��z��p۶98�9P�Z�wa�P����<�{_ű�Փ�]y0نZ.�a��	�[A�a2��c�$A�ý���	;����4T�u��Y�2r��Y��%�`
�3�OIJ���T`�uٳ�V��h|��~A`p�6,���z{�|��	�ۃ�=��~l'�˗����g��K����9&o�rd���y'�q/��ySȔ�u�>��)
	NZ�/,�&���?P+i5J
0�Cϸ���R[hZq�����E��@��w��S��6,���Ή:8?�nRɅ�h�����Z-�e��1S�@gtd�y*��K�E�����I��s�]/�Ͻ���Gة`�,A��A��	�_D��+�Cx)]=,e��N�A�����b�J�B���"K�]("H�,u%f@Yk�����3x�.Ol"�?�p3PQ��5��C
0[��� T��(.���0��?&� ՔY�,G���wH"�K�{`44�'��������N��j��z�G7\2��Kk'5Ґ�n_����X� V"�,"]G�:�ep*���X��}�Ɲ��4M�lbP)�� 7J���i��\o�y�)�7\{ۙ�N��:w�-�iXXݖ���[F\�0.�EV����privW;��D���C
�k�I�m���o���+?�ۮ�Z��MǼa���RlI�*}AP˺ؿ�M룀?էX-+�#�X��k@�T��٦�:2��=lE��X��'y��z:
A�+���*ΑS�VYaP�����g�pvk��~�
Jw�f�yݱ7����+������m�`��/4E*CgiQ�*1����[����!�<��<�DY�6��o5x&����Ui*�y&t:��$�ҟ�Զ�9ݬ��N�==�"��C�@(v}�t��Pw�5�B���SP~���}u邳&�xn�K�v�a��s~���p\n?vsb�:S\��d:�Z�&P/���#%N�<#3�2�iIW����9��#eb��@��!~U9�x�~��TS�p�ۓ��0�qjB�9wk�o���`�f�"?S���������
Q����d"�뽈��T� �!e|��S�c�A0�@����S�!�%r�G�s��x���,<�#5�!�cx�ڟ���m���{�!g�(��B������]#`�$��~�'�-V�2\�b����Hۺo�-�܁��n��2V	�D�s�j���-)�huݟ��D`� V�,Q���>0���?���}Nr�����U���˞|��U�����.)�	
��o>8��ԉ�"��� �T��N��m�[\�6ۚ�+=����OP�ⶕ;H ��Ӓ�w}�ZWM��S�]���QM9�F�'?�i�>-#�]�3�L�,e��=e��_?^�؉����'�{cG�"��$E�jyV��v�>AיhYę�����S���f�̯�o&�"� @2Te�ʳ�5j�3,RLj�\�hʉ���`0US�3�?2��]��"�8nn��yt���2"�x)<H����P%MS�j�/|�TL�u��X�~y�OƪKC�O�o�!A��_1�e4�6�պI��'�ׯ���Ť-�D}�c(���w��Q���^24���樿…�-p.��:�x�%[��#�D�%u�4&O��̭�ٌ5����G�绦�QK]��SA�D��QfNNW���8/D������,��\��oV�fb�-x���Đ$#UwO$n�WG^r�2kH�"��o��B|�7�[��tmY(Ho6�!F��g�j��F�ݸ����H[좾U��}`�0������
P?E4�⒒-�d�mh
�ac[��
��7w�[��l�N��R����F��G
��,+|8����~X����ߺ�S�V�q�%���?Cd�)�=��W�``�Ɲ8�2C&%���Pn�\�l��{���n���w��,|IBPh+ȱ	���{׻���M2ؾ�t})��8<���>��XD���˹���o`#��1I��xh^�fu����/�&Y�\Vnr��di���U��K"��!���-�h>�N�<o뻺14aɒ%�&�>�����s!-�y�f2/q���IT���3��
J~���x�d�N3�Cg�V̛CQ�"�`u~8-��p�vB�D��gKk��u����鲞Vǂ9����O��W&&����v����-��Q��F7�4qY�a"G%)6&�p���ƿ@4��YD����T����ȸ�i�|�����핝�J���x�r�#H8Qu�o,���qL�6����Z
^�(�y���y�A*q���e�H���6�R�Ù�H�l�g���i��i��J��΄���T�M͏O�y'-AQѣ�KH�q?0�!�27��'h�s�{]X��9�%vA|����Yw�E`���%Lw2���ڊ�6��mj\0}����N��ns��A~#B���8��S��l���G�&o=\����솆��X(�u��j��@��ʻ�s�ϼi��b�����G���g�fl=Z�h�6�w�n"j0�P(�A�&3s'�vI�I��D�Ϟ=�dj��_��E���g�1�E8�%�NF��o�^�j��g��ӏ52�N&Ra"�̀Pܕ6~����'��$�]��X�~�L�m�X��K���I,wt��+�JJ��O!�1�%��q=�
Hs�%DZd�RU3���Or�$����D��9�Q��:
���ˉᑊ��Şr�44��a~Z��d�kTU?>�6>w�_J4��̗L�����7�Vq��i*��ṋ@~�l�3��@��=�%:����mN
��{��I0��hCK�Y�L��V���h���جx���p��*��⨌`lC�P�Bqĵ'2�׹}�o	�#�O���ϒj4�a��H���O��������!�@9�t�h-��AF�nc�Z���O;���YΜw�u�5��[�1��ީ�f�P|yLSnJ��]4/��p*���EODc�K�A�@��A�8���/�I�����Xi�;,Ͻ�S�k�݁{׸��M��'-�ߵ�"4�g׷G} ��h]���ǀ�7&R�#榯9�W|��k>��Ψ.(��4��`�;�����[�S�u�5{�94���m�
Wr2�o0����of�c;|��I�K�mO�o��A��⢫��?V�!�f�U�R�}
�~�T���2ɑw߿��H�r�
����솵*0��I��~����c]���a�/�;�߇5U����wtJ��Ƞ(m�.�[U�|
�;1_�U�5��K�Ay�G�i�ĢQ2~�v��YW8�*i'�*�1�*�B�E��=�Y�]����ᘮ��c``Q/�!�/�!�v��$)�p+�s��i���B0{	>�.�����K�5����Q�� "b��c���9��};�q��C�h�ckN����C� ��v���h�i.ǕhQ9�jeC{�q(�}V'�{l�Ͱ�X�~$͚q���]7��D0m\��R�9�����`5��>��&z�6l����&~ߤ̤���7펲Z_h0^ 
�[s#3=d1g�ik�e~h�I�N	�ʼn/��}!/�(h�
mɂ{g&��B�о���6 �����Iϴ�����~4FPV��[�0ܵe������L3���k�������Rr{u�(Y�H�j�-��^��R�4
�Qhtb#�"/��z��\1f�̘KX���nn"��uX�wߓ�BJkkl lcz��k�yu6��=ȋɀB$[��q�����zȽ�4x�[Y�^d��h��d�G��͘���S�Kl���q��PvR�CSt7^�4���r��$8����r�c��{$k[K,��~���N�!<'��0������c����|ܽ-Z�
g�vȳ��{������q�p�,4]��&)۵����Җ���0�ҥ鐴Zd��D��Q�H�J{fw�\�,�p+ʢ�Zk��>Sk����v{�����'�%o�z];:����F���]R� 勎�&N(̪�x�qU��C
��;>�2���3>Pu揌���m�
 k�dϺ�ɨq%���60�b��h;��@�^WVV\���P�}
�F	(,�ͱ�>��1821a{��!���b/4��S�������.?��������MϤ'$B�Ҥ!(�`��bA׾��{A�#v]�ED��R�ׄH/�L2}��n`b���vq&3o޻��{�=�;�|G��7N���)�>G5�
h�+��AP>`��ϠJ:��,��0�_���w�8�KD
.�S�4f�8���$&diP�Z
�ӂ��&��4���6i�=xZ{\	���hk#��C��f��g[��%Mq�#\�ЏAG����ᠼt�/ nwes,"��Þ�Ċ�%�~�<l>��a�`�`=g���<�T��6��M�2�:�a5+�??��yk�6K*'�9ʺ0��_��Y8-/C���P_`3��vՌ�{h˖{����N܂*�P(D����CB��[�|��L��	E?�BҀ��7ۼ�.	��e�d�B�U)��%pF����7�N��n��
Ѩ�a>�j��Q�hw�L���a��ƌ�M��kA%���6�
�� !	#yOKS�tY���,�G��@��w������m�If~�YNhS��:�-2�A՝��5�W��D���R���P��xJ��#�'sB�-�&���wT�Q᭞S�Zg�W�S�&毧��p�]���`
N�1ܣ=��K�$;���ĉ�N�V������9+�,�>�8���ě6�NR�Qd�.�P��E�u+(�K�BN0�O7Ŋ!�Ϙ1>5s0��@�8h���2���އ�y�i��%/#��^���t�B:�!A����k�Ra0&��ࣝ��*(޵>�*��(��p�o���N���٩5�b3I2�C{81QcM�� `H�p.�j�Ӑ��X�/<����<��x�a���u����5�4'+Cm�
n� Dl�qn����H|���=YI\�PĠ�,��;��e؇��,�&�y0F"Q��)8�.�Qh��&�`�(B��A�(΅�꫗��P��M�c�CxB�z���hG��G3u"rxS]�6�Uj
�O�s���6{�Xm9p>k���L�s����H�IR���{�>>75�j`��k��a�Ʌ���Qt-I`C��w�Ǐo�;t�i�M�.c�%nĸ����Ƒ��0"!vQ�i
>�AY��՟i��
+ ��c]7F; 3�rTޙ��‘�I\���dP���X��G�XvpgwG0�QC��ԣ����W�>�/�	��y_2�fD��7.��xZe�U�CT�կ�Q�\��f�
]�, �e��-��2�$�m�����HE��Ú2	~�9,#����-��K�����W��|�L���3�w8��aR��M�m���v`���C��'�1��"f�na��Q3Zw�!Io�'�nWS܅��@�2�-R���U�;�7N;�D�L��İނ�`s�X��hhe�-���ga�O^�.d�J\~���T���0k�2�/���+���=ܦ`߂�dM�@�'m%t���{5����q����~��D�x��C�hx�������{����p0��JKb?Qm�{��+���ˆ����ǀ�F{ �(�ٌ�"���ezc��[�
��5U}NI8�̉.9������zI�cc:��$��w6Յ���Ѭ�+������k�6��+ �TO��&�E�+�J�a��Ӯ#�;}�y��B�g&u�p�G(i3���2�p��=���s�G_�$kSP�4	sS�u�l[mm3�
H�As�a��NHR���V_Rr�L �<��!I9��g�N�����K���k����a��|qu\�f�jƤOd,P
�Z�GcOm���-��|O�!� fr2d@U^��z����G
��q�QZIE�wO���O��#�ˏ ��t��
V�$e��0V��GĢ�V����߈�E
���e�
3�EhS��7��[�~B���*Kk�x�
!�.�0�$R���p�P����SYU�Dk��D%G�;brm�
�܌�V�4�^�8�2z�[_V��t�yuB�dž`FM��idl@2v�i_�)�#J��6�.�y�S�Vv{}x���E[�Cg� �op��X��Ց��f$&=���Y�d@,H����e�^�]��������aW�e5f��v�>7-�K��8�9���өx�Θ�Q�CY���_��݇�Q�;݄/��ץ��(&��"$ݱ�"�3=);�T�'�=����L��M�i���r��Ȓ���&���%U�f<��a�����%��E�{�`}���	��2��y���D?Ƃ��h\}P��h
`r�!�>:�@D�w*��t(���&r�z�Ǜ��c7F���8Wu���;r!c�7�}���gY�]5͋�f��l�+,��q {e��s��M��#������S�Pr6�v�Wl���'��c};�c��1&�|��ӡ�``�i��*X�m��.�q��GD�L~b�_ۍ����t��p�A�R��e �z��W]I��D���ݗa�Ay2����Q"n���<Wi���Tp�#�e.�;�?�iđ�#-��מ,=��i�?��0��Lht�k��;�2&E�����#�?��;g&Aӳ!���"��X�����m}ժ�{ p�	>���JE������H���GB>}�aD򛵨q�Ʊ:͌F������sy�m3_zn��q2���r
Ȗ����B�<{�7�<u
�U�!��UovR����:��ԻAT2
euX�K�˷y#s������K�_2U���c@��G"Ez����o���;	X��4�h�w��h���jq �]Q��%��O4A��D0n�]63�&.�5;��trY�ؿ�V�z��&C��z�$��.!!5��b~�SH����gr�p�o�pp����T2V���.Jym&�偳ڰ��w`�Iv]�����)$”�J�U�9�����;�����Z=c�L���w}�~<5���ʨ5��42��gc?�һ�7=HF'<e]m�k�Z���a2f?;����X4B�~<���h���b�y7�q;}�.YY����C��>�"t'���(�O�����`S.��zD傻a�Aui�I�a����܅R]��X�،Uڥ"��?蠾���}��z]�.�Y�N�8]�p�=g����CA���Ξ�E0��Gxb!��U�M�O��%�8���^�e���~=��].� ��(�o��z;��I�8Cꪲ�%��6�>�XYpm�X��v�C�?����p#`c����]�n4��hk�R�3=}<��G�-
�G06���.U�i@VV|�?ғ����Yq,�#̋�NJ��9�#\�O�R��7�Y�Y��\`qR�9��|���c������6w-��ig�Б:"�rO��+@�0��-�K���|���|a
/�Q��$)8.�W��R�=G���K�yx���+�Wp�C،iD'88^���F|e3Kv랧�fM̀�.�r�,�w�9�*�<�����=�Z�ֺ�s4�+q.��;����t��N��_:H�r�������]�`��l�O�,K_���C�>���6��v�o8Jy�d��nR �!Y��Y)�P䳋���a��ա����4��yn8,"fPl:���4�7X�\"�����.�-V��K����:�<�8�n��</2��6|.v�[�0my�)�}!��B�i޼�w&Ե�SY�Ԛ�:�_�1�1�|��c4;�5�5�S���}�@>��?�����B���+e	�X�IU��[��x�h�´t;
��0��pQke�E����&�8ܷD@�ᕙ��kP��YQ��Y���^
��~
�����4(D��"W��`�*��D���+�A�,�.I��tL���
����4���#`<Y�G�"0	��fL�g1@Y�xo#`
]��\�d�E��Eѿ;h�w�@�Z̜XCd�Z���q��Z^�4Ne��$,�c��=��ѱ��S���>���y��/E*��4��l^��z�QX�`�7vc��Q)�#�	��!���䕄���軸�d�'��t��t�F�K�i|���-8�̻��tU{��7�KN�`o�-�7�r����F���uŘ��Z�:ߑ�Μ���:��|�5G�~z�Q��L���'.U�7�As
<�(�L̔_FYpBM)0{�ŗB��[�?�����_���Yq��|���rΓ�X����A
�]��Ȑ�ބ8zZ0a�*���ްtųB3�-�t�8?�?�
P�{L�������G����/�,�grF�����34Ϯ=����������,���>1��V8*���y.kҗC��c�E��y�9�V��lFƂ����6��F�H<�t�S��9>"s�3��˾aP��!f]<���_=eʔ�2�{��5�w��s%�ͳ#u�%�Ͷ��-�N��v�ȳ'Y®h|��gê�&�0�ٲ�q�Ҧ/Ej���4C��Mz�ϋXGЉ��{|�fS'��h�h�!�C_�9�}���a~��k�ʳD�..k��")�ksD�O�����H�=6����ٝS�#��ݱ�C`�Dc����%Sy�i�۱����W�$1��,<��F��D}o�6��S�3�
��P��i]ݧN�N3��&d����=(Tՠ������UՆ��H��u�#U�\���L�3k�!P>^��l)����Fݕ���)R/X�w�6m�C�#;�=��f��jk�L��;�az0i'����ߏ�מ�'���ِ��H
��f-�P�S?�sݰЏ��h�	��.�fY����?#6����be<Ժ���fD�twR�,�߱���H�#��=�S3��F�M2E/B�zu��X� wt��U��\7�Lnm~Jsٓ�4�#x7�eZ�x��'E�3l�1��U���a*�W����-���p_��bT%��i9'K���{��`ckC$"�tC���n(���A6��S�+a��ƲP����.fW��º/�0!����C[�0%�ll�=�/@�j>�j�D�o�6.u旙���,<�Q�E�O2RrN�kֺ�>��;풾G<K�vgh��L$�l�w�����Cڶb/Sp�m���
��^<�T֚y�:',|�Z���������g%[�S�ܶ���ƣ��Dg��P��q'}7�GL���t1�b�z�Ǒ���a����yC�,"sb����	�
��Uh�3��$l
ׂ�=c��nz��r�(�X����IJ�3P�[tsB!��^-$�yc�f</g!��
Q(ljH�:2G�P͗h�̴ǖ�QV�(#-:#���F��K��x9���'�Y��d�m�S?������X,I�!1P��]9,\���ʊP>�ZL��௼Yj��#��[�NE_�c�gPݷX7u�Cf��g^p��|
w�ʒ9�S����!����`͊��J��?��BP���t�֠4ͳ�;��y�•
��j�/�2��g~8�!i�=qO��t�i����;r_�66�n��l���qC��>��NCѹŨ�{H�2a��r��r�fa��Z_���尥���V���D:���W�"$?�p�M偼��[���È�/�!�o�2������FD=��YH:鏶���4�"�#��y[��iH���H�u�)��x(`��s��&��ߘˣ/P��(�o�^%�΂��Q�N-�y�Qc�ew�1i�V//��y��f[�p�L}sE0��{p��
,��;�F9���]�?�l�����Lc���Y�� �/)��4���L���)�������N �ı���
��UR��0o�iƾ���^D�6� tQ��N�|0(k�>U���Pc���H���^w65���c(���Q>��g��X&�6k�F�
$�8qB��?���w�J�}�}���`��L�����/-���D��{�m��O�Uՠ�^�D�$��{^O���Kx�A��ev<�R�K�[��wFȵ�i0�7�à|���%��z�{mcu�O��X�{�2�"\
����C����vb>�����K���ei�R�B��������b0�5�h�#�sN{��3w~��
�l���D`���ўL�1��7�Fr��H�&4s
�=�MXb�{&�--"��3���5k��Ǭ�ǹ�#z�yd�ϘaZ9vL蝆�>�j��/���IP��̡O��B@Z����}$P����{���ސhɟ�6"�^��l�q�r�z�S�E��}�؋c��e�/|'4�f3�p��/��v��'�@@:������in
G_s!�w6�u.�ǚ>

���*�l�k;p�]aot�_�/��A���hM�[��L���n��[L�Z�T0V�1XY3v�Gk����a����$�:�:kH�~�뇗.(��j 8�V0��ټ��>Qe?V@��g�r�IH-o��RDNlF���ݒ�����JL�.�9*�\�M0�������%M=�>&�1g��������;�F�s�<\�᫇����	hڅ�J��|�$�E;^|0 ������6W5֬i�[l*��H_����+��Os�|�Q�!���o0�h)�l-(6Q'��1�G��V@�w��8���f��l�hr��.��6����P2��ON�x��R_Hy�m#���求�}��g�
���xL~J���9Z�#;��A[c�*R�c;Lpp2�)��KRR� ������r�2�򩼠��OZ8�$*�
MD�菪��&�+�X�e�I<`��;�>�o�Y���2�'��+q���={��R<�(�i�\4]�5�Ydqˤ΁��L�������w�
��=���So�O���F����}K��u��{	vN��"���.���B��������6nW�5Qj"�R$UT�\#Jܷ�WҮM

�&��C�dh��H�����`�\����l��T��$�5�6��ƱIp/�R��̋�e�5djr��~J*X���#���v/bg�Qw3��H6�Ӑ*�"��Nk�\�rٲJ+�O��u4i6���u��ߗ?�!�� H�";�j��!)������
�ʥKa�ݺY����$:�/h���l�"Ƚ����v�ƞ+�)������&��ӯ�6�o�2���Ygne��a��V�o�Ӯ`УQ�Y�����=��+%i�吵�RƓ�
���H����d����Q���7�l��!�&�4�sR��цխ��]�b����~��w�	,'(\,�E�S�[����,O�c'�z@IDAT�V�W��$Z�V�lT�0M;�L��{���!<�f@�C8	VTW�����Cݳ<7����%��x%^K`��e���ak��t0{�p��&0�T�����v�=P��0�<&Jr h�A��(�Pm���%�l|��&�R=��Y�iK1e*	M!Ss�y���)���o+߷�h�D���C��M2l)Y���`��u,������<I�;�@{`���^����Np̽�p�f>F�W>�F�*2�Ġ&@�n��p��>@.@�#%E*��K��J�ׯ�����q�1�I*�@a�*��Ջۺ��s�-vI0lq��dY�غh4|Y(W��LJ�t��$���}�jĀ��!�j��&�3�۹W���	�1���v�R����8�Yu�{[
Y#��2�bT1�C��4cd�r�E ����{����� ��hH�}��o��?�g��T"�H�J;W^�~k���V]�\p�7���#7U��S/}���A�_T�
�]��d}#j�sG߼����|R�����@Wq�a��I;A��9`��f0.@i����	>I5�[O�8^�ϴ���r…��K,Se��U�xzo�:�7�caa��7��ь�EJ��� S
�΁���ҴkBY���X������
<9/�P��0\ nTw����Ÿ�p�{\��p
��/(�
%������[��!�`��wt�~ǂT%�U}�w���2�s;h�_��B������Ӣ��ڻ��M�$2`SYC&�?���x.J�<p$��ڀX]��_ "��iPsѸw�������u�9}�6�^����~II�hW��$�{�w�L���F���ۖ�v��W��)�/Bs���-^6kԃQA�<v[;��^FV�C��
j�C$>��
`EE}���Y��z��͇lfj�N�y�-���W�IQK�M�mۏ=�MaP��<�U[��Ţ�J�M��
�m����}��R�%���,������T$}TK��)�5����L_
�3V`�D�ݦ&�o����d;[�ݝ�y�8�f6��Q��qp�{�2ο��'���HaՙEq���AG�e}�4��\Oq�����-�(��|���Wj�|�������!_Pw.kjb��6��#��ͧ�5��|j�Z��3r��p�RQ���M����3�%�(��fZq����H�څj�v��ݟȆ���Q�?���;>޹������F��I�O��L��D�ephnoK��E9��܇]�NNVa�z�V� ��s��4Aћ#rpW!���z�O<m�ZY�x���@Lr��a5=<PK��)�;�kJ�L��.(�z�`=���AAՃ=���ۼ�����N��-a%��D2�L"X�S�}H�I��F�u�L��Ƨ�|��tvݨQ��#�n��4��Z4
^80�ݷ".��9r�.=�?�K	�p+d"�eʃ	@C�ے8������cξZ�K��ʩ��ꨱIG	p�F �pyy�MS,�q�ڌ��1"�)�j�9�g)u�$���[V��Nۏ�=�邞��okk���zq�a��p��HB����k�	�2qB�_g�{6�d�Ʀ��dk������)�Q�$}"Z��^!球X7��Q�x��W�6�O�R����M*;h����h�vɫN4��������8(V5�Mՙ�:�|u��dX��O=�E��1~�~wJ�*���%
����.�(����e�M"a���⑳�L�h1�%lܬ��js!�?K��<:?s?SkQ��m���|�-7j���6�0k��T
���WYӒ�s���}VR/y�MiX�kϼ�;����KdŜ&e�^_�ݷ	��ʕ++�����\B{���`�*�!�J#�*`�$����>�A�w���k�\���r���愔�_UHbD�<NH������(x��M��pL�aҊ�
%�LϺN!�k�Ĺt8�&Ҍ���	{��e#:���:�|�_F���6T��ې��U���Hw;)�Z���qP���2�Y��D@XLc��궯A�+��MyG&��g�+�\�x���"������z�U`8d?Vu�l>B�;6Xv�����W�%��y����K��(��#ze���X����)�;o�Dh\JS��o'Y��<cB�E��>�n2g�f'��J�rp�W^������4�ad�l�Ҧ���o�$���)�1�#!����ߢ�tK�2��2���)
e<<"/e?�oM��m�-[����
�Ά��5z)��pړ���^;
����#g;�l+%wJN��s�Mo<�lˆC�E�ڝ��~�>����n;}�=�R��(qU�Y�R��p(���L_�,f�e��ύ�̌�9���5��ۯ��W�e'����j�߻LcY��1��*5��4�'��U��Y(�0+��Y�CUX�
�|�����x���37W��tr�SABg��PI�Bb�����}
�^��&�"W>��@������
�,T�@Pn�T�S1ʢf����G=��8���s|@1�w
��o%k�����~9��lN�(w��p8R�j�v�Nٺ6Fb�:�m����z%��*�ސ{��k����}�	1h뛀z�B^q�7��+W�yyyF^�(��
�8��f��f�Wd�B����Y�Z�R�c�r�7 �`��vW��jA��b���¯�W���Ǟ"��ݰk���
���n���h!��bUڡ���;���2�>*��Lk�Z՘�82�4
g��*Yn,+<��K�%m��r%;('����aƪ�,���Z�tN����qMRU[�i}mb�uqẅ�䗘xZ��	�L����XĎ��V�:��y�i�������ޯh���.�P��� ��Z�H���Tl���to��[kpȒ3�LhrN�T��)�==i�0���cgC�:�3��(z�ij3c��M�\LNO��m�~=�P1�PqǙȊO������v����F�0+tM�Ƴ�t��mA��,0F_��"�f!O�Rܢ��p������.�,� �hQ�*e�x�{ּ3�K�;wT\�b��R���D`im��R���0B�!0��=���X��3:9ꏽy�_��X�u�X����E�)9��M
��#Q�e�829P�Դ"[p遆�'��
IG4hE^�aP�f�l���RQ޳�G��H�ɘ%�'�к�4��b�Py����� m��V�19oe���ʸ�b��vB6�D��H���'J�o�>S�)�d�,���@s���U�n�-#AL�����}��<�t�锶h@Z���g1���kIS�G̠?`�/�'�Aė�
x���k�8�>B��y6�~��)�w�ʴ��	�l�fW�&`��ýu��K#��z�S�]/����>,�.��������h�'�2$O�#H�3����鷯�z�x���0��9yk�CV?Ij��Y/*��q�ذ)�g�/q �hb��`�`�IL�"�����QAfæ7��<�<�v��߿>mʯ
^r]b�����qH2 ���C{����nN��d� �g\�	�[�c(<�Ս�[p����l࿳Y�����H��"�|X����@��]s�d0��Ml��,��T��;�=YXMQ�\�
�48����n�	t0 ���|-0��(4��9VW����ݠ�'K�ĝM�7-;iE�2�X��
�VĂ�1]�@:j"��t�Uԫ��з9|�������Ҩ78�\��YF�<Te���Qz��E�o 6Y�Z�/L�E���`>,����0-���껲NO��B��j�L��7�ԝ�mQ��1Č�0��VI�>���lղ]������"��e���
��c�z�n�p�����AZ"�ƒ��[[4�6��h@2:�W~}B��W\}ڜ"�$�"�!��׸�	�:8d��տ�i0�p$6��6�^#+��6�Gl&�YM����%�b@���ˆ�/k��^���D{?�
��"�ql������<�J܏��1rl
a�u][C�Ïeu��1M"�6B1C����8qtvzْ}����"�X�#��+�z�1�5F�̰��ǵ����.a4)���;W.�v��%��ڑ!�P��HH[��"�p>[WV#�mz RO6�?�ݚ/iY��O�9҄K-��;�͡�k‘�=9��C�Rݐ�0��c��?	��|����_�O�g�^V�(��x�Y�u�L^(��"_
M{d�c�\�����`F'[��H��٣���W^I�]wg���W?�~oS+%�m��
�"@c����Ô��~��W�$�P��Bà��a�HF|���ɲ�3�];�}�\��SuC���ى�3
�h�
>u�[`K\�y���W�aL@��PL�Hu��t���%_�
���_]9��p�n�F������Ą-'�@F�u°\i�Κ��0����돲W�LuI(X��h��Zm���I�+�/}�ʖi"�fDc=��M�H�
Ќ��"0�,��`�#+}UU}2�eEh����|ZO�|�G��ӏ����}m�E��J��2qCeH�p��UUa�(���uR]�Ji���G�"��9s�c�;H;�~����'��3$�H#��\�y�!/���7yƶ,q�b�E��xf
���b��e�zq��,�l�jTb^��g�a~j̻`�S�cl�*x��N/�Ѽ��"�k�
g���P���ļ#B�ð��b���ℋJ`���	�|��y��Y�­�Y��_����	�Ms�N1�N���?�`*�2���Y"��'��C�H�G�φ?,*�_as9VaT��p��F �mnF
G�1���B�o�qP�bg�1��G���}�I���`B���Q_������� Ue�׏k�S-EGhK@�s�]`l�B	"4i>�F�g�Q�5��u���qL#*=�@�x$�W՛aEǀ�@��#�eY�grbC0
�t���ITѪxkM��������'�!��jVv��e�$��s�6j�EN�!Ɂ��ݻ��ә	�6�ĵ�+�
g�	��<��{���Ǔ�v�6x22��E��r_͞�y�q��S��Q�v�Ԙt�@�ǀ������1�����vC��PZ�3�'��

yg8o�F5/$r>��v)f�Z%"n/��
�{$���f@�Oo��v���L�u�~h��B��ٗ���6$��Ք70�xTz셽3��lx|���}���<��0M�����_�;�Ɏ�p,߄r7�*&��`bQ`h�i,��;4�Ayp¶1wz#'Ѣ��w�� x������gc��<�e����C��E��,�z��>qÜ����u&C�rr܏��52��@5�ij%��|ӑ;��O���V��S��9���?"�i��H��&����<���VB��ܽ_.$�hp���[=B0�oC�^	~��u
�>��,J���XQ�z5�cGd=�<�X��D�����ܘKD��f�1�꯻��I�}IyJã���m7�ʙ�M���u�W�J�u����>���'T�&:F ����lyji�h�(��V��@k+���v�UO������N�d羡C�Ʒ�����C���	g��9�3�Xne�<�w1�g�%ݭW�@���0f�a��E0=��$�dZ0�5�<1*vv�%� ��qc�Wb��$�f}K�'��lo��7�j��a}�,�Y^@��/N��=�������Xt5H�[��1l���!�2~�"�q����[�I ŵ��HL�b�%��X��	��6��q��L""8%��3��C��_!�>�<=���;��АL��5��xr��v3�g��B�F߸*'U��2�[�ϊ���E�zZ�8����$Y�]����	>��=�u+���&�����
�$c��n�u�U���`J�Թ�%U��9��r<�y��&k6'i4„��J�֯�6���:�<9��%6�c���}�|M\]S�6�Z��m�#�^u�����a��GΜ\���{hoB�{�5&���$G#"er�UQ��i�ե���%H`au6v�“���/c��B{#���
=@����QY{�%0�Ej�!�iq��V��ZD��1Y>i�QG�S�Þ
2������������iI�9}�{p�Ϭ>�f�����(�(H�w�3P�,6^ծ/@)x�7r���ME5�s�%%��'dMv)�1$%�n
�3�4�b������f��l���_d
�
,�I,�E�"�yx����T�6o�����K����w�>-��fK�,fb���9���b�G$�/�5X�A�_���J��1�i-@=yR~���w��Q�D�ȇ#�����>�$�7`7|IΈ@�n^x�q���<�M&?��Gq�iC��h��w@U"d�Z�
kB&����Q�h�<�2X8� +�u�%.q�`#}<�؆����G��碪�UĹ`��c���7�&Ն*�i�=��󢼖ޛ�����N��$��L��IE�qH�;��6��ˊS͐�a���L��d���g�*>��{��d�a_��M���c�y��?TO���X'�!U?�#p�=i]^�����\�aI
�eA�p��~��:xdI��tS�ق��k�$�܃<g�F���h;~	_����v3�#F+y�1���Þ
��M���;ДDXAO��O��8<�_ֿ�.o<n*�Jw����5�\3�v'�Ԕ�2",[���?h���xܬ]�PO(ہ�̹(���6�����`��|�KW!��������_.)�3)]D9�;�{��O�{O��9S>%��[\v��Ⱥ��$Y�٣G�J<�P�Bq�Wun%Ϩ�C�v-]�=qn붶~O�FzϞ"R�v��y���D��y�+o��ZS
�<���ŒAd��Ė^�3g��C�tQ��BI*�
$Lm;Ym��q"ߟp�K���]� �A����us�M]]�[m�XE���;Q�1i�U`��+����h7�|�� �9X0�
��<�2�磄O�J�תf,Dn9h5�ѤTvb0�F����5�kbڃZL�8̖V�������Y]_��H�|UG��9L�-19|���C� <D1�$���G��w���%#mG_A�Z<�^�dtNY��~ţ��l��a��+����j�
�ѡ4S9)�c]��63�H{�3hI�>�������cGyތ!q8Dі���[Jq�Q�	����h���A�Hm�y�={�z44�iii��Ϡ�P�q��=�S�E]�;eR�ɽ����B�ysE�_��&��)�p�QPR�{��'Q��0���L>[[+�/i
�D&�|{�A8/[kZd��s����u��.z�@s�H�.D��Yѯ��9��%�띍�K�,<Ƃ��ä����Ο���X����_?�ຩ�b{���J!s44�3�h��Ri�o��W4������I�v3��P]���f�a�̥�M�º�eD5RY��L{��J!N����
q��pȆY�k�>���%�Lԓ#cH�f�='�B��&���<�,����
#z?9�x㏄�v��K����5���ȇ\<}�&��dNRw��EF��A�.�)���X��{Jk�}�{���C&�؃�۲���)���?�
�
\�,<��2I�L�5}f��!d�(��G�ԽD�n�I�?뀿�6y 	K<�CFm�$p�2	A�9hp��kr�Dz��R��t
0:8��7c��&�KU�_;��h��61��@��1�����
�G<M���FRRTQ��UY�=ᨍ�A��Bl*2—���d��	�8�YB(���(T�5�;X�t8�nB��Q� ��36���*�S�����BW�4��Miӓ_]}�k���VU&/����-σ�℠�=�l.���Lt���x�kO�ú�eb�6��-�"�ۻ�+�~nڅ໵ʚ����ݻ�
"�,ڴBR�+�1�Xf��,Ǯ�
϶��P����U�Y�����ZŔ�k�W��^����Q������ �f<F�Y3g��ւ���݄�m��.�p��@'�`�nA��CEӏ�d~�·��^��m����*��w�
��V� ����כ�����iA��d{"��\��x�y������j��9�\��l�)��z{��#�Ea�Ν�`ꨣfߐ�b��K���|�r�)
m��\�:� N5��'�Ӣ�-5��;
�:�ӭp�E���bϓO�om��A��e�RR��B�_�Z��������ذ�j\��>;�p6�K�"�
����Ev!�j-��˜��fdfC���N-���Pg�uQי�W���G��D�۸�	��k��uFM�j��k�!sE�˂J��$x�o	J
��5-��_KJ�{�����XqX�(�GT�`(�|}lnT�Ō�R��nY`|���n�|�v%���u@	�Qx-Â�v��,�|gm����z�VV��CI���}S��3� e&8	�"�n"�����`p��B�M�n�{N����C�M���
�*���pV�k33�~I�9tTO�!�0ܴ�c�w4+w�q�'�ZtTM�>��cG�]���	M���zl<�1�LH������?";��2'C�N���TYUF��r�FŮ){?(��3�y(���ÂG�b �%�/�G}��.���=\��|G4������p9n������e��3�􃑸�eB�C&;��|��1�.��k��{8���|K���k���a
���F��7E�u[8_L�'�Ɍ�V(�Ď�v]��.���'{�Tνk��\���w�	*Ѯ&KY��D��~/��5��͌�?�+�]z"�sbF��^�X��,OJE�;��ɡ�
P.C�{#�&ԃh*#+f�V)��ȲS+�gd4�+�o��F5�iC��٬�9�Z��������`����
�7Mb���Kt��q
�x`
?�^֟w�8��A���+:�5�D!x.oXNB
�8T�����8��<vT>�[7
�.�v�ڳi�v��kmDꈟ�V|�����*z;T�ዅ��B,6*-M�����w�,>��t�c��G�}B�/��8S��Zy)BO��Зm�r����:����r�w!�����U��'bC�~�-��cl�����:��վ+�h_��$�5~~�w���#�{�H��C��,i(<���Z����XU�?�~��q���r�M/���E9!��3��J����؃hC�%e�U�і)a:�R�|Ѯ
I��	C1
`�k�8%���슆��ɵ4k֍��G���^`�O���]X�35S]�bP旾2�z�"L��s2�l4�L�.7j���x'L���\��ԽH�@.�Y�q�p�{�tٌӔu�]%D�%����?�Ӊ����Q�as���S,��w��Y<q�t���B�C�yTS���}�7x)/p/@��Tt�>�1@�ر=C��4~X}D���n�)}����4h�r��)�('���m�����(������B�a��?���;�Uۏ7N'�����XS�88b2�������	�D��M���=E�C#�~J�X_\����O²62��������O/�i��(�1�� �Ë�dnn-|[��8Te��Ĥ���#�_�NY6�:��N���oH<n�N�ځxxW��cC�`�t�����T��˙y%�{��&��,7��-X���I,��iOύkR�a��Yԃ5Յ��l�Ō��h1s�=��6�5X����8�SN�M�DH�v�{p-��kQ�d���� ��/1�V�u*+XnWy&��/�9vmL�R{B'ڄ�a��8���p����=��Fc���zN� ��-f�+�����D�ip��,rZ34q�Y?�����K�vmꈈ�B9��$B;�3�����S�\4J��'��o�~j�$�I&�K�&�R���6!	��$%�O$���3����!�|�k��`�5��Gh2�������ZO����Mgb`_E�$©��2��Qߍa����,Ť��4w����W��j(�xգ�q�HL�5_]�s�#H⛄MsW\
'��>����u��6Cо���ddA��݀m�TTik�#H�ͬ�Ձ��~������dn��m춻	�")!F�3�6~ ����J7��Ce:�X����L��d� �q�x�Y�xxO]LK*�
7.�ٵu�r��~�'�Y�n3e�u�X$��F��C��>s����<���ir1�_!d�Xً@A9��2ߧ~�HH���u�<(=��%J��y���b ��ea�i��]B�>W�[w3�C��O�Ғ�^�0����� �#;ϵ�*p2�p�����w�1����,7�Yz�Ƞ��"��Wŗ�aڬ�Y�����_u����9p„/=�ԇ����9�bprY
�Ե+��S�����1�W���獪h.uV�����g����!��f��#Zz6�W���Ѐ%�O<�w���S�UD�z`ˍA���?�r�f�52HL��? ���~�TM؛�
n��W\����萊	�o�?NoLd�xl�]M
Oֆ
%�"�`�FX�r�����\��a��6�l��;*�j
����"z(*S3�K�}�B�WxP9r&?0�Vhx'Q��MY�V�œ'C�Գ��U�Pl��ٝ��iLJ�x�5K5S���'̜�l_��oX���-m.7��p5���1Y}����;DBRuI(X���n�����X�V���y�󖓉�g{c�ڈ̴����no�6F���kM�8+;�(��a�KP�w-C��&#Lsp�H�^N�Y�
�fFb��Ҁ�%�9+VBˍ�������V�ZdP���A�S�s�=��v�����{�j�vK}h�+�^Ki%v���0�Ü�Ђ"��R���%�&��A,�:Ƹܺc!�	?��q:���^yB�]�`��Pb�u�����:!P���fkPx.���y1l̿3!�8G`?A�0�1�9h�#�Q�Zkl
E���{NS����Gz
B�v��n��^�8�����&|�ҹ��IC��v��E���,��ΉN�U����U�
1j����Ƥ��y~1�y_��Y��b�o+(䀓v�����V��8j�躜
͆���PlsX�v�C����$��q��Wk���i�^fĔ8��C�G(;�����{����KH�X�d��߲�_�,�7�/>NvnX
�8�<v�yy�+�F�,$��ٿec��ˏ� �M$�����Ϛ_Z�.�&����O��P�%L�|wkm�!A07#���؞���a�v[X�8�5��"�����)�~I�$B�d
��D�䬆���#���- ��$�!'�������QIm����V�������2hE��LƵ���w��"Z#�YX�"d�o`�_鵻!r�v_�����'�?Kp�˸����⹖�n݁%N���-X�p�:*���sx�n��x.T�f��g܉D�����;^E�8X�s6��
��i'H~<��<�����"�-$Rk?�U���9
�9��9�ir�]w���O�	���ջ��%s�G`��U�4ރ�� J_����SP�wͯ�F^
��&���y<m�z%�wO�sY��(Q�
!c�Gh�G��C�x����댺z�˯j�2:�	�$UgG�r?omYu�sT�z��T;Mߦ�kwO�0��6��[�3
�W����`љ���G��?��	�l?2C9m�Y@eg�<�D_t�g34WZ�U&�O��W �Ʉ?������W�i�A�_���T��Oy���;V�̑L���*��*�5�{�8�v$H��}[�B�EJ!;h<s�&9�<�)��1a��&͘>�g�4�?82!��|;��翄�"V�E6﵊��iiQ�%�ܜ9
��
h��T�y��鷑�>��,��݁�����E��QONb�.X��~hV3'1Y0��1ɪ���O��`���j �;![_��Bp�l"$�[}�vՇ��� &}��}�G�Ppt�Ǟ�����	Z�^N�g�(�Y��;���ŒƲ�G�~#T?mH�5�/n��'$H�6\V�,X��1�;@�4�N3��9�E�G�]'��o��B�����+���cL08A�
M�YO�Iur`9��ွ��X�h2W�R����.-�Z��o<�'��K���ߛ8pȿ^y�F���5�SY��U�d�#A*�7��m�U�S��c&����@L{�S]�:]����5��@0��\UZ����xOe�����E�3ݿ.���t��!�m+�f��1�@w�GXU3Q�<����;��Qk8(G�_DȠ���D�|fC��b<���|���R�w9�S8����Ȇ	�2�� 
N�̂a�EuͿ���>�ykH�H3��/'L�V�ja�_���:��jE�Bz���ޏD���Ʌ�-��@hU���+�i�!eg{�tJ�9�8�#��?��=0)B ���m�E�'h~�}�~o�Lk���9��0�&�p�`�
��g	�"n;���'�gA��b9B��3a��'yB�����L&3A���A�����}W��t��PW���B��_b����Ih�L"\��e[AD~�<��F���sL�{�&9p�<8��M�34Z/)mrv�Nف\L|��+hA
��xl��b�5Ɔ��9�����[v6���SPGgBǺ�[|�,�H��Oף��Q�Ȃ!d=<d��Z�Y������l��Zk�n�a��j:`��^�x�1�{s`6���L!�#aM
��[��¡ib��|_D��`a�+��F�Quv�(᤼�Q5�h�^�*�,�&]��И���C���)�J���kя�ʼ9�"e��#ُ1�;�J�]w9;u0:u� �bj2�F�
��σ����SQ#�c���ض���ߓ�"�����'�oʰ
�DQ��mHc�:�Ǖu�Z��Ă���u=z4];<5|<aFJX!��)X��MoD(��U{�)M#
Ά�YV~��d��,���W�š �	����Ӎ��U��rV�+���e1�z���~T�ֲ���7$����T����0����
Q�I?�o��0�{vN��<�~���o'5Do!���(����i����+�U�p��눂���U����I<������rN�N^$�ѿ�>ej��/�y�lE��{<J����!��pn=	
z9���FH;X�bb����eM�(���z�ۘ*������0������ G��]pU�?��s����4@y�
�j�dɬӮ�n����.ڝ��u;��l���t�meU�j��u�Sug���
Bl$D!R!���\�Inr��}��O�r
�`'�6gnrs�9�~�;���?���)B����w
g;�+�{�Ӗ�3�^�z�������;A<C��B7t�(t��	wu
?���`�:,qT~P����x}���h|mZW��mO���'<��RV	�������(�0�O)
x���Mj�j��.�	��@K-Nx�	�+��\4�0�F�HV�0��3�
ڣVz[�`���ܛ4�O�u�j��}�tB2'�����4P��F�¶����?�-E�O��.�	�%tͯ>��]���L���یz���jۊ++��r܄`	�GQ�6^��ŋ^���x�Tp��ȮlA#���@xne0vK8�E$Z��CI���g����U)k2��޴���CY�Ӓ"�Z�󇼒�$�S#�:]ߟ�F�Kv�aDs�
�~X�W.��e��ر�g>zB��^��˗���*��o�d�1��>���h:ӻ��y�t�0�̀<ƍ�
�/`��Kܚ��y
�r��Dz�C��w"C^��E'��7���;)�l}�E�?��6�P3*�����.�Y�f:"���A�n�Ҧ啞n@�n�tn�#��h��|��u�-�ΑaP���̋�҅�?�2R����# h�A���ʛ�T�,��E�S�N6?�~����.d~lIY-�N�+��E9X�*tHR<�/ƶ��w%�)�ͩ¢��a
��=ﮞM�j�0�YUӹ�}�_�>s9)���q$	��=���Qʥ4Pv�Ή�	�����R��W�;��bu\�Aފ�]�jn��_i�f�__�*)O�p�d엨��=�KA�ǜ�����
2�˴�c&o�l�l����=`X����a���;���z�nX!�h�a
�=�dJc�ԟ+��u��€މ�k�ߏ%�WN�7�AEW�ns��b �G��T�^��vʌ�7�ܟZm�~��f��o;��)�™�jN'�N�C�R_�֓+��݆��k��=�4͏7ڣ��!��n �o�	.m�� ����e����F��d���sc}��R|�O+0��gA�hB��2%��]���H�C��@�Z
��
(����4���]��=�b[��0ǹM����",�<DV�]^k���b�/9Z�	y�p��!�ET�Q0G�{v��XO��/��H%��
ѧ��G�C�,�kA���瞈�W���zXܛ%���܎�9�"zP�����"��cVݶn�w[��Rc))\U�::�lTȕR1eJXI�5��F��ί}MiI(�p�y��'b(Y&d�UL�����؝H#�m8�t��3V��L�G�W�G
*\ȵt
�
1�o"�4m�*��� 'na��>�xs�}т���Ŀ��̀�<��;��
lV��p#�a�)j��@g�>T<�VTXu:k,��+�vʩ��,
F�7����$t��Ӹ�
�mCC����N�Y��b?:�`�-:�P:kE�.��7a�ے�Ǽ���W��^�1�	cY+�x0(�B���oy7�&�7�n�njڀ^1K=
�����+ԵHߑT+\���9�)K������`��f�U3���"d��E��[HC܏Ż�u��6ԀWt<jH=?v��m�F�<2�|@=�Nt/�H����ѩ�?�`�Xu)�J���r�@�OnG��.�Fc��+Z#*J5�>�{NZS��[�)��h�̽T�G���1�����C����L�O>oφw�$,y�̄�:,�Z!��"�������2�Ώ�����+�܎���7C9��o��,"��@�‡�kn�q-^'�җ�F��YM�!9�}���D��4����J�/�}<�d�V=�kG��I�
S�r� q�6��;YBw��Ÿ�4]���H��׿�[6w�y�AT���u�>��_p��&J|b˜D��
Ͽ���6�%*�e��!ǻ�`j�__W<G��h_�<�($q'
n0�'`�����ؗ�]?��-8��K�;��2I���]�&���k;ڱ^<�`>����/t[��������	���D�&��G����?g
Y;gM�Ar�ʕ�@g����\��v���h���0�%���SQ::8�<sx%�3OJ���p��²���dy�%T��*�Eх!'c���r�lw� &���B�=��a�z�Pd�ZQ 2�a�sO��]�Io���s��a� oZ��G�����Ezm��"\w�
��K��c}��F�:O�F��y�e�Gn�$j,�_i%�ݜ��U���:piT]�����b�Ɖ,��3��}ݱ�/Wkf�C
�Ј~�`�ou�:��8ڗ��lZ��DZ��B]���>�H�scH��O�Dwg��d�����b�6f^��8�X�J�I`Z��F;ER�FY�3K���OOq,��`t�	K�����[�M)	�*K�Q�rs#w�k��1�W�R�{S_�[2��A�U� ��
�\��B
J�=��[ ~E%n^A���hr���YX��fuP��hL<�ү����u\��i��q#cA[�s���N1i�b0�ϼ�>xflhF�	?Ǿ��ȥ�߇kcbBT��y>��<��؞Ht�k���	h���+�)L�����p�)�e�K���2`�v�/������|IDAT�:�E��ہ��]s�&g�X���rZ����n3������&4i�� rT�jA�ԛ�샢�Ø���©w���(�����y��H��KE�j�ÃoE�����k�$�[����cn���t�DJ'��X�r5�y����^�Vۧ[~ΏGǖ\��pP��� �SF9/�Svȹ�B���^�T<��w�eG$E�a�/�̢�%/��C���?"��}��W��4��%�Ri�2�	���N8���؎�B�����F���p���H�Q@�پ��ge�	>J��Mk��Z�h��-��
�]Ӯә��V�Rc�ζ�ǎeɈ�t
����%�3�ɾ]ɂ)�E�
�\/"��H�5�'���>{9y�kb|w �t��0\(�hf��#+��ҙ�|��V������r&g̅>4B���9�FJ-�{NZ�1�7��$ϫRe�v�-,	����D�x���On_J},��?���0��v>�d�>���S�//����'���ڵ�!S0γ��ۥ���W�0�4���~�8�;�7C�YrO�_)ɮ��>��:��2
�PV��eA�k�W*�9�4OM�ޟ?
r�ėdg�#�M��HVBw�Lp����浊EE!�7M�Պ)�U�v�p/Ptl�����s2Y��0�dԀC�xՊŊ\��Z�W4���D�5���VR�rR@��*ք̘x�)�b�k��!UG�G�[Xp�zZ[�Cye�Zݎ�K�f��wP�uȷ�����\!'���?���oC�.1��+�X�G�[�Q�@�@�y�^�,�R�}o<����&�+k�2�CR�|��l_��X-]�Z�z~��n61��Aӝ�7 ���qCKu�I�ߏ���r�s��+�oۨ�@�B��<wK��r���<��]�{���h��#%�?��r2(욐�̯�R�lF�'6�����֎�ʼ�
3	�m1BF*�X6r<�
U�4�M.+���&^_�܅��мs�U�3����dv�kQR?�S���
�X>��D�h�(0��r̈́����������hY����"��G�h���s����B%����5b���jGxT�K���� gr}������(���j�;�2*K��*S�f�FŊ���oC�eh��F{u��"��i�}�>l��)4ʤ�ZEd?���M���#7tb�FRt��łm6ٸq�Ǩ!Z|kV��:�H����
$��afvZ�S�	���I�O�c�"8�1ޡ�Γ�#*��]�Po���s=ߧI�{=ߝ�k��N^�^.y���%$���:a?�9�`t���Ƴ%ŕ�5�﷋j�#��=فH��,T�n�żN��D���Ĉ5�+��i�6p��1U���H�L{&�Ӄ�P�tڦvw�;�I�5�vJ��I?�-:sQ��*=��f(�tF>͊45�^�x�9ܛX���Y3v\M���y�$-�h��=w��K���;��������u|=d��P���e
`W�ljt�}V�Z���ż��>��;�Q\�i�ɽG��ϱ�??��Z��
�
r��ӗ�M�5TT���=/�s���H�����<ݱ�i�����'G`r&d�Fr�?�����1�=��IEND�B`��PNG


IHDR�&��bKGD���̿	pHYsg��RtIME�,�B��IDAT8˕��K�e���x4�ljs���N��
���ƊQD�"�^n���џ0��.�#X/x�6���E
�Z�3_[f:���<GQ�����U�ˇ_�Ϗ����I���R)�`T��2���	�Tf޲�f#����MI�(��ڶ݇���L��Z8I�4�ex�<���Ng8$c|R��EG��6���v�A���b�o��j1��cvm�I�n�K##U�n�%���c����p�Zx��W�'lǭe@���Ky	�#�2�P�$$,�;b�D_��C��r%<o�{4�)��W�� �4o{Q��R�Y	s��VeM�5e�e�'��>�[���,j6/�K����,��p.|z���R�H�zG-��q��pْJ�|�'���7�3�^��
	g��	kY)q,�5$�1��פ��Q����f�9wt�wB�%9�2����:<hg��K��a}Z�.�Y����r����W�k�i�i���>"���R2qZ5�qK.�@��A�9�/.%�=r��y�b"	
�]|�pUgx���K��M_�S.nUZ(3�i;4gŐr�s>�4�^^ܰ��`����n�N���}��YI5��vP����k��.	Þ�gu�XW~0��1�ɤc
�tYP0i�8hRz$��k�$�+��„1u�[��ᴣn1�fL���[6�h��7D��؈jg����e��g��(=IEND�B`�===========================
Unit Testing Guzzle clients
===========================

Guzzle provides several tools that will enable you to easily unit test your web service clients.

* PHPUnit integration
* Mock responses
* node.js web server for integration testing

PHPUnit integration
-------------------

Guzzle is unit tested using `PHPUnit <http://www.phpunit.de/>`_.  Your web service client's unit tests should extend
``Guzzle\Tests\GuzzleTestCase`` so that you can take advantage of some of the built in helpers.

In order to unit test your client, a developer would need to copy phpunit.xml.dist to phpunit.xml and make any needed
modifications.  As a best practice and security measure for you and your contributors, it is recommended to add an
ignore statement to your SCM so that phpunit.xml is ignored.

Bootstrapping
~~~~~~~~~~~~~

Your web service client should have a tests/ folder that contains a bootstrap.php file. The bootstrap.php file
responsible for autoloading and configuring a ``Guzzle\Service\Builder\ServiceBuilder`` that is used throughout your
unit tests for loading a configured client. You can add custom parameters to your phpunit.xml file that expects users
to provide the path to their configuration data.

.. code-block:: php

    Guzzle\Tests\GuzzleTestCase::setServiceBuilder(Aws\Common\Aws::factory($_SERVER['CONFIG']));

    Guzzle\Tests\GuzzleTestCase::setServiceBuilder(Guzzle\Service\Builder\ServiceBuilder::factory(array(
        'test.unfuddle' => array(
            'class' => 'Guzzle.Unfuddle.UnfuddleClient',
            'params' => array(
                'username' => 'test_user',
                'password' => '****',
                'subdomain' => 'test'
            )
        )
    )));

The above code registers a service builder that can be used throughout your unit tests.  You would then be able to
retrieve an instantiated and configured Unfuddle client by calling ``$this->getServiceBuilder()->get('test.unfuddle)``.
The above code assumes that ``$_SERVER['CONFIG']`` contains the path to a file that stores service description
configuration.

Unit testing remote APIs
------------------------

Mock responses
~~~~~~~~~~~~~~

One of the benefits of unit testing is the ability to quickly determine if there are errors in your code.  If your
unit tests run slowly, then they become tedious and will likely be run less frequently.  Guzzle's philosophy on unit
testing web service clients is that no network access should be required to run the unit tests.  This means that
responses are served from mock responses or local servers.  By adhering to this principle, tests will run much faster
and will not require an external resource to be available.  The problem with this approach is that your mock responses
must first be gathered and then subsequently updated each time the remote API changes.

Integration testing over the internet
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can perform integration testing with a web service over the internet by making calls directly to the service. If
the web service you are requesting uses a complex signing algorithm or some other specific implementation, then you
may want to include at least one actual network test that can be run specifically through the command line using
`PHPUnit group annotations <http://www.phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.group>`_.

@group internet annotation
^^^^^^^^^^^^^^^^^^^^^^^^^^

When creating tests that require an internet connection, it is recommended that you add ``@group internet`` annotations
to your unit tests to specify which tests require network connectivity.

You can then `run PHPUnit tests <http://www.phpunit.de/manual/current/en/textui.html>`_ that exclude the @internet
group by running ``phpunit --exclude-group internet``.

API credentials
^^^^^^^^^^^^^^^

If API  credentials are required to run your integration tests, you must add ``<php>`` parameters to your
phpunit.xml.dist file and extract these parameters in your bootstrap.php file.

.. code-block:: xml

    <?xml version="1.0" encoding="UTF-8"?>
    <phpunit bootstrap="./tests/bootstrap.php" colors="true">
        <php>
            <!-- Specify the path to a service configuration file -->
            <server name="CONFIG" value="test_services.json" />
            <!-- Or, specify each require parameter individually -->
            <server name="API_USER" value="change_me" />
            <server name="API_PASSWORD" value="****" />
        </php>
        <testsuites>
            <testsuite name="guzzle-service">
                <directory suffix="Test.php">./Tests</directory>
            </testsuite>
        </testsuites>
    </phpunit>

You can then extract the ``server`` variables in your bootstrap.php file by grabbing them from the ``$_SERVER``
superglobal: ``$apiUser = $_SERVER['API_USER'];``

Further reading
^^^^^^^^^^^^^^^

A good discussion on the topic of testing remote APIs can be found in Sebastian Bergmann's
`Real-World Solutions for Developing High-Quality PHP Frameworks and Applications <http://www.amazon.com/dp/0470872497>`_.

Queueing Mock responses
-----------------------

Mock responses can be used to test if requests are being generated correctly and responses and handled correctly by
your client.  Mock responses can be queued up for a client using the ``$this->setMockResponse($client, $path)`` method
of your test class.  Pass the client you are adding mock responses to and a single path or array of paths to mock
response files relative to the ``/tests/mock/ folder``.  This will queue one or more mock responses for your client by
creating a simple observer on the client.  Mock response files must contain a full HTTP response message:

.. code-block:: none

    HTTP/1.1 200 OK
    Date: Wed, 25 Nov 2009 12:00:00 GMT
    Connection: close
    Server: AmazonS3
    Content-Type: application/xml

    <?xml version="1.0" encoding="UTF-8"?>
    <LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">EU</LocationConstraint>

After queuing mock responses for a client, you can get an array of the requests that were sent by the client that
were issued a mock response by calling ``$this->getMockedRequests()``.

You can also use the ``Guzzle\Plugin\Mock\MockPlugin`` object directly with your clients.

.. code-block:: php

    $plugin = new Guzzle\Plugin\Mock\MockPlugin();
    $plugin->addResponse(new Guzzle\Http\Message\Response(200));
    $client = new Guzzle\Http\Client();
    $client->addSubscriber($plugin);

    // The following request will get the mock response from the plugin in FIFO order
    $request = $client->get('http://www.test.com/');
    $request->send();

    // The MockPlugin maintains a list of requests that were mocked
    $this->assertContainsOnly($request, $plugin->getReceivedRequests());

node.js web server for integration testing
------------------------------------------

Using mock responses is usually enough when testing a web service client.  If your client needs to add custom cURL
options to requests, then you should use the node.js test web server to ensure that your HTTP request message is
being created correctly.

Guzzle is based around PHP's libcurl bindings.  cURL sometimes modifies an HTTP request message based on
``CURLOPT_*`` options.  Headers that are added to your request by cURL will not be accounted for if you inject mock
responses into your tests.  Additionally, some request entity bodies cannot be loaded by the client before transmitting
it to the sever (for example, when using a client as a sort of proxy and streaming content from a remote server). You
might also need to inspect the entity body of a ``multipart/form-data`` POST request.

.. note::

    You can skip all of the tests that require the node.js test web server by excluding the ``server`` group:
    ``phpunit --exclude-group server``

Using the test server
~~~~~~~~~~~~~~~~~~~~~

The node.js test server receives requests and returns queued responses.  The test server exposes a simple API that is
used to enqueue responses and inspect the requests that it has received.

Retrieve the server object by calling ``$this->getServer()``.  If the node.js server is not running, it will be
started as a forked process and an object that interfaces with the server will be returned.  (note: stopping the
server is handled internally by Guzzle.)

You can queue an HTTP response or an array of responses by calling ``$this->getServer()->enqueue()``:

.. code-block:: php

    $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");

The above code queues a single 200 response with an empty body.  Responses are queued using a FIFO order; this
response will be returned by the server when it receives the first request and then removed from the queue. If a
request is received by a server with no queued responses, an exception will be thrown in your unit test.

You can inspect the requests that the server has retrieved by calling ``$this->getServer()->getReceivedRequests()``.
This method accepts an optional ``$hydrate`` parameter that specifies if you are retrieving an array of string HTTP
requests or an array of ``Guzzle\Http\RequestInterface`` subclassed objects.  "Hydrating" the requests will allow
greater flexibility in your unit tests so that you can  easily assert the state of the various parts of a request.

You will need to modify the base_url of your web service client in order to use it against the test server.

.. code-block:: php

    $client = $this->getServiceBuilder()->get('my_client');
    $client->setBaseUrl($this->getServer()->getUrl());

After running the above code, all calls made from the ``$client`` object will be sent to the test web server.
.. title:: Guzzle | PHP HTTP client and framework for consuming RESTful web services

====================
Guzzle Documentation
====================

Getting started
---------------

.. toctree::
   :maxdepth: 1

   getting-started/overview
   getting-started/installation
   getting-started/faq

The HTTP client
---------------

.. toctree::
   :maxdepth: 2

   http-client/client
   http-client/request
   http-client/response
   http-client/entity-bodies
   http-client/http-redirects
   http-client/uri-templates

Plugins
-------

.. toctree::
   :maxdepth: 1

   plugins/plugins-overview
   plugins/creating-plugins
   plugins/async-plugin
   plugins/backoff-plugin
   plugins/cache-plugin
   plugins/cookie-plugin
   plugins/curl-auth-plugin
   plugins/history-plugin
   plugins/log-plugin
   plugins/md5-validator-plugin
   plugins/mock-plugin
   plugins/oauth-plugin

The web service client
----------------------

.. toctree::
   :maxdepth: 1

   webservice-client/webservice-client
   webservice-client/using-the-service-builder
   webservice-client/guzzle-service-descriptions
   batching/batching
   iterators/resource-iterators
   iterators/guzzle-iterators

Testing
-------

.. toctree::
   :maxdepth: 2

   testing/unit-testing

API Docs
--------

`Read the API docs <http://guzzlephp.org/api/index.html>`_
=================
Welcome to Guzzle
=================

What is Guzzle?
~~~~~~~~~~~~~~~

Guzzle is a PHP HTTP client and framework for building web service clients. Guzzle takes the pain out of sending HTTP
requests and the redundancy out of creating web service clients.

Features at a glance
--------------------

- All the power of cURL with a simple interface.
- Persistent connections and parallel requests.
- Streams request and response bodies
- Service descriptions for quickly building clients.
- Powered by the Symfony2 EventDispatcher.
- Use all of the code or only specific components.
- Plugins for caching, logging, OAuth, mocks, and more
- Includes a custom node.js webserver to test your clients.
- Service descriptions for defining the inputs and outputs of an API
- Resource iterators for traversing paginated resources
- Batching for sending a large number of requests as efficiently as possible

.. code-block:: php

    // Really simple using a static facade
    Guzzle\Http\StaticClient::mount();
    $response = Guzzle::get('http://guzzlephp.org');

    // More control using a client class
    $client = new \Guzzle\Http\Client('http://guzzlephp.org');
    $request = $client->get('/');
    $response = $request->send();

License
-------

Licensed using the `MIT license <http://opensource.org/licenses/MIT>`_.

    Copyright (c) 2013 Michael Dowling <https://github.com/mtdowling>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.

Contributing
------------

Guidelines
~~~~~~~~~~

This is still a work in progress, but there are only a few rules:

1. Guzzle follows PSR-0, PSR-1, and PSR-2
2. All pull requests must include unit tests to ensure the change works as expected and to prevent future regressions

Reporting a security vulnerability
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We want to ensure that Guzzle is a secure HTTP client library for everyone. If you've discovered a security
vulnerability in Guzzle, we appreciate your help in disclosing it to us in a
`responsible manner <http://en.wikipedia.org/wiki/Responsible_disclosure>`_.

Publicly disclosing a vulnerability can put the entire community at risk. If you've discovered a security concern,
please email us at security@guzzlephp.org. We'll work with you to make sure that we understand the scope of the issue,
and that we fully address your concern. We consider correspondence sent to security@guzzlephp.org our highest priority,
and work to address any issues that arise as quickly as possible.

After a security vulnerability has been corrected, a security hotfix release will be deployed as soon as possible.
============
Installation
============

Requirements
------------

#. PHP 5.3.3+ compiled with the cURL extension
#. A recent version of cURL 7.16.2+ compiled with OpenSSL and zlib

Installing Guzzle
-----------------

Composer
~~~~~~~~

The recommended way to install Guzzle is with `Composer <http://getcomposer.org>`_. Composer is a dependency
management tool for PHP that allows you to declare the dependencies your project needs and installs them into your
project.

.. code-block:: bash

    # Install Composer
    curl -sS https://getcomposer.org/installer | php

    # Add Guzzle as a dependency
    php composer.phar require guzzle/guzzle:~3.9

After installing, you need to require Composer's autoloader:

.. code-block:: php

    require 'vendor/autoload.php';

You can find out more on how to install Composer, configure autoloading, and other best-practices for defining
dependencies at `getcomposer.org <http://getcomposer.org>`_.

Using only specific parts of Guzzle
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

While you can always just rely on ``guzzle/guzzle``, Guzzle provides several smaller parts of Guzzle as individual
packages available through Composer.

+-----------------------------------------------------------------------------------------------+------------------------------------------+
| Package name                                                                                  | Description                              |
+===============================================================================================+==========================================+
| `guzzle/common <https://packagist.org/packages/guzzle/common>`_                               | Provides ``Guzzle\Common``               |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/http <https://packagist.org/packages/guzzle/http>`_                                   | Provides ``Guzzle\Http``                 |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/parser <https://packagist.org/packages/guzzle/parser>`_                               | Provides ``Guzzle\Parser``               |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/batch <https://packagist.org/packages/guzzle/batch>`_                                 | Provides ``Guzzle\Batch``                |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/cache <https://packagist.org/packages/guzzle/cache>`_                                 | Provides ``Guzzle\Cache``                |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/inflection <https://packagist.org/packages/guzzle/inflection>`_                       | Provides ``Guzzle\Inflection``           |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/iterator <https://packagist.org/packages/guzzle/iterator>`_                           | Provides ``Guzzle\Iterator``             |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/log <https://packagist.org/packages/guzzle/log>`_                                     | Provides ``Guzzle\Log``                  |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin <https://packagist.org/packages/guzzle/plugin>`_                               | Provides ``Guzzle\Plugin`` (all plugins) |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-async <https://packagist.org/packages/guzzle/plugin-async>`_                   | Provides ``Guzzle\Plugin\Async``         |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-backoff <https://packagist.org/packages/guzzle/plugin-backoff>`_               | Provides ``Guzzle\Plugin\BackoffPlugin`` |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-cache <https://packagist.org/packages/guzzle/plugin-cache>`_                   | Provides ``Guzzle\Plugin\Cache``         |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-cookie <https://packagist.org/packages/guzzle/plugin-cookie>`_                 | Provides ``Guzzle\Plugin\Cookie``        |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-error-response <https://packagist.org/packages/guzzle/plugin-error-response>`_ | Provides ``Guzzle\Plugin\ErrorResponse`` |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-history <https://packagist.org/packages/guzzle/plugin-history>`_               | Provides ``Guzzle\Plugin\History``       |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-log <https://packagist.org/packages/guzzle/plugin-log>`_                       | Provides ``Guzzle\Plugin\Log``           |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-md5 <https://packagist.org/packages/guzzle/plugin-md5>`_                       | Provides ``Guzzle\Plugin\Md5``           |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-mock <https://packagist.org/packages/guzzle/plugin-mock>`_                     | Provides ``Guzzle\Plugin\Mock``          |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/plugin-oauth <https://packagist.org/packages/guzzle/plugin-oauth>`_                   | Provides ``Guzzle\Plugin\Oauth``         |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/service <https://packagist.org/packages/guzzle/service>`_                             | Provides ``Guzzle\Service``              |
+-----------------------------------------------------------------------------------------------+------------------------------------------+
| `guzzle/stream <https://packagist.org/packages/guzzle/stream>`_                               | Provides ``Guzzle\Stream``               |
+-----------------------------------------------------------------------------------------------+------------------------------------------+

Bleeding edge
^^^^^^^^^^^^^

During your development, you can keep up with the latest changes on the master branch by setting the version
requirement for Guzzle to ``dev-master``.

.. code-block:: js

   {
      "require": {
         "guzzle/guzzle": "dev-master"
      }
   }

PEAR
~~~~

Guzzle can be installed through PEAR:

.. code-block:: bash

    pear channel-discover guzzlephp.org/pear
    pear install guzzle/guzzle

You can install a specific version of Guzzle by providing a version number suffix:

.. code-block:: bash

    pear install guzzle/guzzle-3.9.0

Contributing to Guzzle
----------------------

In order to contribute, you'll need to checkout the source from GitHub and install Guzzle's dependencies using
Composer:

.. code-block:: bash

    git clone https://github.com/guzzle/guzzle.git
    cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev

Guzzle is unit tested with PHPUnit. You will need to create your own phpunit.xml file in order to run the unit tests
(or just copy phpunit.xml.dist to phpunit.xml). Run the tests using the vendored PHPUnit binary:

.. code-block:: bash

    vendor/bin/phpunit

You'll need to install node.js v0.5.0 or newer in order to test the cURL implementation.

Framework integrations
----------------------

Using Guzzle with Symfony
~~~~~~~~~~~~~~~~~~~~~~~~~

Bundles are available on GitHub:

- `DdeboerGuzzleBundle <https://github.com/ddeboer/GuzzleBundle>`_ for Guzzle 2
- `MisdGuzzleBundle <https://github.com/misd-service-development/guzzle-bundle>`_ for Guzzle 3

Using Guzzle with Silex
~~~~~~~~~~~~~~~~~~~~~~~

A `Guzzle Silex service provider <https://github.com/guzzle/guzzle-silex-extension>`_ is available on GitHub.
===
FAQ
===

What should I do if I get this error: Fatal error: Maximum function nesting level of '100' reached, aborting!
-------------------------------------------------------------------------------------------------------------

You could run into this error if you have the XDebug extension installed and you execute a lot of requests in
callbacks.  This error message comes specifically from the XDebug extension. PHP itself does not have a function
nesting limit. Change this setting in your php.ini to increase the limit::

    xdebug.max_nesting_level = 1000

[`source <http://stackoverflow.com/a/4293870/151504>`_]

How can I speed up my client?
-----------------------------

There are several things you can do to speed up your client:

1. Utilize a C based HTTP message parser (e.g. ``Guzzle\Parser\Message\PeclHttpMessageParser``)
2. Disable operation validation by setting the ``command.disable_validation`` option to true on a command

Why am I getting a 417 error response?
--------------------------------------

This can occur for a number of reasons, but if you are sending PUT, POST, or PATCH requests with an
``Expect: 100-Continue`` header, a server that does not support this header will return a 417 response. You can work
around this by calling ``$request->removeHeader('Expect');`` after setting the entity body of a request.
========
Batching
========

Guzzle provides a fairly generic and very customizable batching framework that allows developers to efficiently
transfer requests in parallel.

Sending requests and commands in parallel
-----------------------------------------

You can send HTTP requests in parallel by passing an array of ``Guzzle\Http\Message\RequestInterface`` objects to
``Guzzle\Http\Client::send()``:

.. code-block:: php

    $responses = $client->send(array(
        $client->get('http://www.example.com/foo'),
        $client->get('http://www.example.com/baz')
        $client->get('http://www.example.com/bar')
    ));

You can send commands in parallel by passing an array of ``Guzzle\Service\Command\CommandInterface`` objects
``Guzzle\Service\Client::execute()``:

.. code-block:: php

    $commands = $client->execute(array(
        $client->getCommand('foo'),
        $client->getCommand('baz'),
        $client->getCommand('bar')
    ));

These approaches work well for most use-cases.  When you need more control over the requests that are sent in
parallel or you need to send a large number of requests, you need to use the functionality provided in the
``Guzzle\Batch`` namespace.

Batching overview
-----------------

The batch object, ``Guzzle\Batch\Batch``, is a queue.  You add requests to the queue until you are ready to transfer
all of the requests.  In order to efficiently transfer the items in the queue, the batch object delegates the
responsibility of dividing the queue into manageable parts to a divisor (``Guzzle\Batch\BatchDivisorInterface``).
The batch object then iterates over each array of items created by the divisor and sends them to the batch object's
``Guzzle\Batch\BatchTransferInterface``.

.. code-block:: php

    use Guzzle\Batch\Batch;
    use Guzzle\Http\BatchRequestTransfer;

    // BatchRequestTransfer acts as both the divisor and transfer strategy
    $transferStrategy = new BatchRequestTransfer(10);
    $divisorStrategy = $transferStrategy;

    $batch = new Batch($transferStrategy, $divisorStrategy);

    // Add some requests to the batch queue
    $batch->add($request1)
        ->add($request2)
        ->add($request3);

    // Flush the queue and retrieve the flushed items
    $arrayOfTransferredRequests = $batch->flush();

.. note::

    You might find that your transfer strategy will need to act as both the divisor and transfer strategy.

Using the BatchBuilder
----------------------

The ``Guzzle\Batch\BatchBuilder`` makes it easier to create batch objects.  The batch builder also provides an easier
way to add additional behaviors to your batch object.

Transferring requests
~~~~~~~~~~~~~~~~~~~~~

The ``Guzzle\Http\BatchRequestTransfer`` class efficiently transfers HTTP requests in parallel by grouping batches of
requests by the curl_multi handle that is used to transfer the requests.

.. code-block:: php

    use Guzzle\Batch\BatchBuilder;

    $batch = BatchBuilder::factory()
        ->transferRequests(10)
        ->build();

Transferring commands
~~~~~~~~~~~~~~~~~~~~~

The ``Guzzle\Service\Command\BatchCommandTransfer`` class efficiently transfers service commands by grouping commands
by the client that is used to transfer them.  You can add commands to a batch object that are transferred by different
clients, and the batch will handle the rest.

.. code-block:: php

    use Guzzle\Batch\BatchBuilder;

    $batch = BatchBuilder::factory()
        ->transferCommands(10)
        ->build();

    $batch->add($client->getCommand('foo'))
        ->add($client->getCommand('baz'))
        ->add($client->getCommand('bar'));

    $commands = $batch->flush();

Batch behaviors
---------------

You can add various behaviors to your batch that allow for more customizable transfers.

Automatically flushing a queue
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use the ``Guzzle\Batch\FlushingBatch`` decorator when you want to pump a large number of items into a batch queue and
have the queue automatically flush when the size of the queue reaches a certain threshold.

.. code-block:: php

    use Guzzle\Batch\BatchBuilder;

    $batch = BatchBuilder::factory()
        ->transferRequests(10)
        ->autoFlushAt(10)
        ->build();

Batch builder method: ``autoFlushAt($threshold)``

Notifying on flush
~~~~~~~~~~~~~~~~~~

Use the ``Guzzle\Batch\NotifyingBatch`` decorator if you want a function to be notified each time the batch queue is
flushed.  This is useful when paired with the flushing batch decorator.  Pass a callable to the ``notify()`` method of
a batch builder to use this decorator with the builder.

.. code-block:: php

    use Guzzle\Batch\BatchBuilder;

    $batch = BatchBuilder::factory()
        ->transferRequests(10)
        ->autoFlushAt(10)
        ->notify(function (array $transferredItems) {
            echo 'Transferred ' . count($transferredItems) . "items\n";
        })
        ->build();

Batch builder method:: ``notify(callable $callback)``

Keeping a history
~~~~~~~~~~~~~~~~~

Use the ``Guzzle\Batch\HistoryBatch`` decorator if you want to maintain a history of all the items transferred with
the batch queue.

.. code-block:: php

    use Guzzle\Batch\BatchBuilder;

    $batch = BatchBuilder::factory()
        ->transferRequests(10)
        ->keepHistory()
        ->build();

After transferring items, you can use the ``getHistory()`` of a batch to retrieve an array of transferred items.  Be
sure to periodically clear the history using ``clearHistory()``.

Batch builder method: ``keepHistory()``

Exception buffering
~~~~~~~~~~~~~~~~~~~

Use the ``Guzzle\Batch\ExceptionBufferingBatch`` decorator to buffer exceptions during a transfer so that you can
transfer as many items as possible then deal with the errored batches after the transfer completes.  After transfer,
use the ``getExceptions()`` method of a batch to retrieve an array of
``Guzzle\Batch\Exception\BatchTransferException`` objects.  You can use these exceptions to attempt to retry the
failed batches.  Be sure to clear the buffered exceptions when you are done with them by using the
``clearExceptions()`` method.

Batch builder method: ``bufferExceptions()``
======================
Using Response objects
======================

Sending a request will return a ``Guzzle\Http\Message\Response`` object. You can view the raw  HTTP response message by
casting the Response object to a string. Casting the response to a string will return the entity body of the response
as a string too, so this might be an expensive operation if the entity body is stored in a file or network stream. If
you only want to see the response headers, you can call ``getRawHeaders()``.

Response status line
--------------------

The different parts of a response's `status line <http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1>`_
(the first line of the response HTTP message) are easily retrievable.

.. code-block:: php

    $response = $client->get('http://www.amazon.com')->send();

    echo $response->getStatusCode();      // >>> 200
    echo $response->getReasonPhrase();    // >>> OK
    echo $response->getProtocol();        // >>> HTTP
    echo $response->getProtocolVersion(); // >>> 1.1

You can determine the type of the response using several helper methods:

.. code-block:: php

    $response->isSuccessful(); // true
    $response->isInformational();
    $response->isRedirect();
    $response->isClientError();
    $response->isServerError();

Response headers
----------------

The Response object contains helper methods for retrieving common response headers. These helper methods normalize the
variations of HTTP response headers.

.. code-block:: php

    $response->getCacheControl();
    $response->getContentType();
    $response->getContentLength();
    $response->getContentEncoding();
    $response->getContentMd5();
    $response->getEtag();
    // etc... There are methods for every known response header

You can interact with the Response headers using the same exact methods used to interact with Request headers. See
:ref:`http-message-headers` for more information.

.. code-block:: php

    echo $response->getHeader('Content-Type');
    echo $response->getHeader('Content-Length');
    echo $response->getHeaders()['Content-Type']; // PHP 5.4

Response body
-------------

The entity body object of a response can be retrieved by calling ``$response->getBody()``. The response EntityBody can
be cast to a string, or you can pass ``true`` to this method to retrieve the body as a string.

.. code-block:: php

    $request = $client->get('http://www.amazon.com');
    $response = $request->send();
    echo $response->getBody();

See :doc:`/http-client/entity-bodies` for more information on entity bodies.

JSON Responses
~~~~~~~~~~~~~~

You can easily parse and use a JSON response as an array using the ``json()`` method of a response. This method will
always return an array if the response is valid JSON or if the response body is empty. You will get an exception if you
call this method and the response is not valid JSON.

.. code-block:: php

    $data = $response->json();
    echo gettype($data);
    // >>> array

XML Responses
~~~~~~~~~~~~~

You can easily parse and use a XML response as SimpleXMLElement object using the ``xml()`` method of a response. This
method will always return a SimpleXMLElement object if the response is valid XML or if the response body is empty. You
will get an exception if you call this method and the response is not valid XML.

.. code-block:: php

    $xml = $response->xml();
    echo $xml->foo;
    // >>> Bar!

Streaming responses
-------------------

Some web services provide streaming APIs that allow a client to keep a HTTP request open for an extended period of
time while polling and reading. Guzzle provides a simple way to convert HTTP request messages into
``Guzzle\Stream\Stream`` objects so that you can send the initial headers of a request, read the response headers, and
pull in the response body manually as needed.

Here's an example using the Twitter Streaming API to track the keyword "bieber":

.. code-block:: php

    use Guzzle\Http\Client;
    use Guzzle\Stream\PhpStreamRequestFactory;

    $client = new Client('https://stream.twitter.com/1');

    $request = $client->post('statuses/filter.json', null, array(
        'track' => 'bieber'
    ));

    $request->setAuth('myusername', 'mypassword');

    $factory = new PhpStreamRequestFactory();
    $stream = $factory->fromRequest($request);

    // Read until the stream is closed
    while (!$stream->feof()) {
        // Read a line from the stream
        $line = $stream->readLine();
        // JSON decode the line of data
        $data = json_decode($line, true);
    }

You can use the ``stream`` request option when using a static client to more easily create a streaming response.

.. code-block:: php

    $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true));
    while (!$stream->feof()) {
        echo $stream->readLine();
    }
=============
URI templates
=============

The ``$uri`` passed to one of the client's request creational methods or the base URL of a client can utilize URI
templates. Guzzle supports the entire `URI templates RFC <http://tools.ietf.org/html/rfc6570>`_. URI templates add a
special syntax to URIs that replace template place holders with user defined variables.

Every request created by a Guzzle HTTP client passes through a URI template so that URI template expressions are
automatically expanded:

.. code-block:: php

    $client = new Guzzle\Http\Client('https://example.com/', array('a' => 'hi'));
    $request = $client->get('/{a}');

Because of URI template expansion, the URL of the above request will become ``https://example.com/hi``. Notice that
the template was expanded using configuration variables of the client. You can pass in custom URI template variables
by passing the URI of your request as an array where the first index of the array is the URI template and the second
index of the array are template variables that are merged into the client's configuration variables.

.. code-block:: php

    $request = $client->get(array('/test{?a,b}', array('b' => 'there')));

The URL for this request will become ``https://test.com?a=hi&b=there``. URI templates aren't limited to just simple
variable replacements;  URI templates can provide an enormous amount of flexibility when creating request URIs.

.. code-block:: php

    $request = $client->get(array('http://example.com{+path}{/segments*}{?query,data*}', array(
        'path'     => '/foo/bar',
        'segments' => array('one', 'two'),
        'query'    => 'test',
        'data'     => array(
            'more' => 'value'
        )
    )));

The resulting URL would become ``http://example.com/foo/bar/one/two?query=test&more=value``.

By default, URI template expressions are enclosed in an opening and closing brace (e.g. ``{var}``). If you are working
with a web service that actually uses braces (e.g. Solr), then you can specify a custom regular expression to use to
match URI template expressions.

.. code-block:: php

    $client->getUriTemplate()->setRegex('/\<\$(.+)\>/');
    $client->get('/<$a>');

You can learn about all of the different features of URI templates by reading the
`URI templates RFC <http://tools.ietf.org/html/rfc6570>`_.
==============
HTTP redirects
==============

By default, Guzzle will automatically follow redirects using the non-RFC compliant implementation used by most web
browsers. This means that redirects for POST requests are followed by a GET request. You can force RFC compliance by
enabling the strict mode on a request's parameter object:

.. code-block:: php

    // Set per request
    $request = $client->post();
    $request->getParams()->set('redirect.strict', true);

    // You can set globally on a client so all requests use strict redirects
    $client->getConfig()->set('request.params', array(
        'redirect.strict' => true
    ));

By default, Guzzle will redirect up to 5 times before throwing a ``Guzzle\Http\Exception\TooManyRedirectsException``.
You can raise or lower this value using the ``redirect.max`` parameter of a request object:

.. code-block:: php

    $request->getParams()->set('redirect.max', 2);

Redirect history
----------------

You can get the number of redirects of a request using the resulting response object's ``getRedirectCount()`` method.
Similar to cURL's ``effective_url`` property, Guzzle provides the effective URL, or the last redirect URL that returned
the request, in a response's ``getEffectiveUrl()`` method.

When testing or debugging, it is often useful to see a history of redirects for a particular request. This can be
achieved using the HistoryPlugin.

.. code-block:: php

    $request = $client->get('/');
    $history = new Guzzle\Plugin\History\HistoryPlugin();
    $request->addSubscriber($history);
    $response = $request->send();

    // Get the last redirect URL or the URL of the request that received
    // this response
    echo $response->getEffectiveUrl();

    // Get the number of redirects
    echo $response->getRedirectCount();

    // Iterate over each sent request and response
    foreach ($history->getAll() as $transaction) {
        // Request object
        echo $transaction['request']->getUrl() . "\n";
        // Response object
        echo $transaction['response']->getEffectiveUrl() . "\n";
    }

    // Or, simply cast the HistoryPlugin to a string to view each request and response
    echo $history;

Disabling redirects
-------------------

You can disable redirects on a client by passing a configuration option in the client's constructor:

.. code-block:: php

    $client = new Client(null, array('redirect.disable' => true));

You can also disable redirects per request:

.. code-block:: php

    $request = $client->get($url, array(), array('allow_redirects' => false));

Redirects and non-repeatable streams
------------------------------------

If you are redirected when sending data from a non-repeatable stream and some of the data has been read off of the
stream, then you will get a ``Guzzle\Http\Exception\CouldNotRewindStreamException``. You can get around this error by
adding a custom rewind method to the entity body object being sent in the request.

.. code-block:: php

    $request = $client->post(
        'http://httpbin.com/redirect/2',
        null,
        fopen('http://httpbin.com/get', 'r')
    );

    // Add a custom function that can be used to rewind the stream
    // (reopen in this example)
    $request->getBody()->setRewindFunction(function ($body) {
        $body->setStream(fopen('http://httpbin.com/get', 'r'));
        return true;
    );

    $response = $client->send();
=====================
Using Request objects
=====================

HTTP request messages
---------------------

Request objects are all about building an HTTP message. Each part of an HTTP request message can be set individually
using methods on the request object or set in bulk using the ``setUrl()`` method. Here's the format of an HTTP request
with each part of the request referencing the method used to change it::

    PUT(a) /path(b)?query=123(c) HTTP/1.1(d)
    X-Header(e): header
    Content-Length(e): 4

    data(f)

+-------------------------+---------------------------------------------------------------------------------+
| a. **Method**           | The request method can only be set when instantiating a request                 |
+-------------------------+---------------------------------------------------------------------------------+
| b. **Path**             | ``$request->setPath('/path');``                                                 |
+-------------------------+---------------------------------------------------------------------------------+
| c. **Query**            | ``$request->getQuery()->set('query', '123');``                                  |
+-------------------------+---------------------------------------------------------------------------------+
| d. **Protocol version** | ``$request->setProtocolVersion('1.1');``                                        |
+-------------------------+---------------------------------------------------------------------------------+
| e. **Header**           | ``$request->setHeader('X-Header', 'header');``                                  |
+-------------------------+---------------------------------------------------------------------------------+
| f. **Entity Body**      |  ``$request->setBody('data'); // Only available with PUT, POST, PATCH, DELETE`` |
+-------------------------+---------------------------------------------------------------------------------+

Creating requests with a client
-------------------------------

Client objects are responsible for creating HTTP request objects.

GET requests
~~~~~~~~~~~~

`GET requests <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3>`_ are the most common form of HTTP
requests. When you visit a website in your browser, the HTML of the website is downloaded using a GET request. GET
requests are idempotent requests that are typically used to download content (an entity) identified by a request URL.

.. code-block:: php

    use Guzzle\Http\Client;

    $client = new Client();

    // Create a request that has a query string and an X-Foo header
    $request = $client->get('http://www.amazon.com?a=1', array('X-Foo' => 'Bar'));

    // Send the request and get the response
    $response = $request->send();

You can change where the body of a response is downloaded on any request using the
``$request->setResponseBody(string|EntityBodyInterface|resource)`` method of a request. You can also set the ``save_to``
option of a request:

.. code-block:: php

    // Send the response body to a file
    $request = $client->get('http://test.com', array(), array('save_to' => '/path/to/file'));

    // Send the response body to an fopen resource
    $request = $client->get('http://test.com', array(), array('save_to' => fopen('/path/to/file', 'w')));

HEAD requests
~~~~~~~~~~~~~

`HEAD requests <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4>`_ work exactly like GET requests except
that they do not actually download the response body (entity) of the response message. HEAD requests are useful for
retrieving meta information about an entity identified by a Request-URI.

.. code-block:: php

    $client = new Guzzle\Http\Client();
    $request = $client->head('http://www.amazon.com');
    $response = $request->send();
    echo $response->getContentLength();
    // >>> Will output the Content-Length header value

DELETE requests
~~~~~~~~~~~~~~~

A `DELETE method <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7>`_ requests that the origin server
delete the resource identified by the Request-URI.

.. code-block:: php

    $client = new Guzzle\Http\Client();
    $request = $client->delete('http://example.com');
    $response = $request->send();

POST requests
~~~~~~~~~~~~~

While `POST requests <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5>`_ can be used for a number of
reasons, POST requests are often used when submitting HTML form data to a website. POST requests can include an entity
body in the HTTP request.

POST requests in Guzzle are sent with an ``application/x-www-form-urlencoded`` Content-Type header if POST fields are
present but no files are being sent in the POST. If files are specified in the POST request, then the Content-Type
header will become ``multipart/form-data``.

The ``post()`` method of a client object accepts four arguments: the URL, optional headers, post fields, and an array of
request options. To send files in the POST request, prepend the ``@`` symbol to the array value (just like you would if
you were using the PHP ``curl_setopt`` function).

Here's how to create a multipart/form-data POST request containing files and fields:

.. code-block:: php

    $request = $client->post('http://httpbin.org/post', array(), array(
        'custom_field' => 'my custom value',
        'file_field'   => '@/path/to/file.xml'
    ));

    $response = $request->send();

.. note::

    Remember to **always** sanitize user input when sending POST requests:

    .. code-block:: php

        // Prevent users from accessing sensitive files by sanitizing input
        $_POST = array('firstname' => '@/etc/passwd');
        $request = $client->post('http://www.example.com', array(), array (
            'firstname' => str_replace('@', '', $_POST['firstname'])
        ));

You can alternatively build up the contents of a POST request.

.. code-block:: php

    $request = $client->post('http://httpbin.org/post')
        ->setPostField('custom_field', 'my custom value')
        ->addPostFile('file', '/path/to/file.xml');

    $response = $request->send();

Raw POST data
^^^^^^^^^^^^^

POST requests can also contain raw POST data that is not related to HTML forms.

.. code-block:: php

    $request = $client->post('http://httpbin.org/post', array(), 'this is the body');
    $response = $request->send();

You can set the body of POST request using the ``setBody()`` method of the
``Guzzle\Http\Message\EntityEnclosingRequest`` object. This method accepts a string, a resource returned from
``fopen``, or a ``Guzzle\Http\EntityBodyInterface`` object.

.. code-block:: php

    $request = $client->post('http://httpbin.org/post');
    // Set the body of the POST to stream the contents of /path/to/large_body.txt
    $request->setBody(fopen('/path/to/large_body.txt', 'r'));
    $response = $request->send();

PUT requests
~~~~~~~~~~~~

The `PUT method <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6>`_ requests that the enclosed entity be
stored under the supplied Request-URI. PUT requests are similar to POST requests in that they both can send an entity
body in the request message.

The body of a PUT request (any any ``Guzzle\Http\Message\EntityEnclosingRequestInterface`` object) is always stored as
a ``Guzzle\Http\Message\EntityBodyInterface`` object. This allows a great deal of flexibility when sending data to a
remote server. For example, you can stream the contents of a stream returned by fopen, stream the contents of a
callback function, or simply send a string of data.

.. code-block:: php

    $request = $client->put('http://httpbin.org/put', array(), 'this is the body');
    $response = $request->send();

Just like with POST, PATH, and DELETE requests, you can set the body of a PUT request using the ``setBody()`` method.

.. code-block:: php

    $request = $client->put('http://httpbin.org/put');
    $request->setBody(fopen('/path/to/large_body.txt', 'r'));
    $response = $request->send();

PATCH requests
~~~~~~~~~~~~~~

`PATCH requests <http://tools.ietf.org/html/rfc5789>`_ are used to modify a resource.

.. code-block:: php

    $request = $client->patch('http://httpbin.org', array(), 'this is the body');
    $response = $request->send();

OPTIONS requests
~~~~~~~~~~~~~~~~

The `OPTIONS method <http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2>`_ represents a request for
information about the communication options available on the request/response chain identified by the Request-URI.

.. code-block:: php

    $request = $client->options('http://httpbin.org');
    $response = $request->send();

    // Check if the PUT method is supported by this resource
    var_export($response->isMethodAllows('PUT'));

Custom requests
~~~~~~~~~~~~~~~

You can create custom HTTP requests that use non-standard HTTP methods using the ``createRequest()`` method of a
client object.

.. code-block:: php

    $request = $client->createRequest('COPY', 'http://example.com/foo', array(
        'Destination' => 'http://example.com/bar',
        'Overwrite'   => 'T'
    ));
    $response = $request->send();

Query string parameters
-----------------------

Query string parameters of a request are owned by a request's ``Guzzle\Http\Query`` object that is accessible by
calling ``$request->getQuery()``. The Query class extends from ``Guzzle\Common\Collection`` and allows you to set one
or more query string parameters as key value pairs. You can set a parameter on a Query object using the
``set($key, $value)`` method or access the query string object like an associative array. Any previously specified
value for a key will be overwritten when using ``set()``. Use ``add($key, $value)`` to add a value to query string
object, and in the event of a collision with an existing value at a specific key, the value will be converted to an
array that contains all of the previously set values.

.. code-block:: php

    $request = new Guzzle\Http\Message\Request('GET', 'http://www.example.com?foo=bar&abc=123');

    $query = $request->getQuery();
    echo "{$query}\n";
    // >>> foo=bar&abc=123

    $query->remove('abc');
    echo "{$query}\n";
    // >>> foo=bar

    $query->set('foo', 'baz');
    echo "{$query}\n";
    // >>> foo=baz

    $query->add('foo', 'bar');
    echo "{$query}\n";
    // >>> foo%5B0%5D=baz&foo%5B1%5D=bar

Whoah! What happened there? When ``foo=bar`` was added to the existing ``foo=baz`` query string parameter, the
aggregator associated with the Query object was used to help convert multi-value query string parameters into a string.
Let's disable URL-encoding to better see what's happening.

.. code-block:: php

    $query->useUrlEncoding(false);
    echo "{$query}\n";
    // >>> foo[0]=baz&foo[1]=bar

.. note::

    URL encoding can be disabled by passing false, enabled by passing true, set to use RFC 1738 by passing
    ``Query::FORM_URLENCODED`` (internally uses PHP's ``urlencode`` function), or set to RFC 3986 by passing
    ``Query::RFC_3986`` (this is the default and internally uses PHP's ``rawurlencode`` function).

As you can see, the multiple values were converted into query string parameters following the default PHP convention of
adding numerically indexed square bracket suffixes to each key (``foo[0]=baz&foo[1]=bar``). The strategy used to convert
multi-value parameters into a string can be customized using the ``setAggregator()`` method of the Query class. Guzzle
ships with the following query string aggregators by default:

1. ``Guzzle\Http\QueryAggregator\PhpAggregator``: Aggregates using PHP style brackets (e.g. ``foo[0]=baz&foo[1]=bar``)
2. ``Guzzle\Http\QueryAggregator\DuplicateAggregator``: Performs no aggregation and allows for key value pairs to be
   repeated in a URL (e.g. ``foo=baz&foo=bar``)
3. ``Guzzle\Http\QueryAggregator\CommaAggregator``: Aggregates using commas (e.g. ``foo=baz,bar``)

.. _http-message-headers:

HTTP Message Headers
--------------------

HTTP message headers are case insensitive, multiple occurrences of any header can be present in an HTTP message
(whether it's valid or not), and some servers require specific casing of particular headers. Because of this, request
and response headers are stored in ``Guzzle\Http\Message\Header`` objects. The Header object can be cast as a string,
counted, or iterated to retrieve each value from the header. Casting a Header object to a string will return all of
the header values concatenated together using a glue string (typically ", ").

A request (and response) object have several methods that allow you to retrieve and modify headers.

* ``getHeaders()``: Get all of the headers of a message as a ``Guzzle\Http\Message\Header\HeaderCollection`` object.
* ``getHeader($header)``: Get a specific header from a message. If the header exists, you'll get a
  ``Guzzle\Http\Message\Header`` object. If the header does not exist, this methods returns ``null``.
* ``hasHeader($header)``: Returns true or false based on if the message has a particular header.
* ``setHeader($header, $value)``: Set a header value and overwrite any previously set value for this header.
* ``addHeader($header, $value)``: Add a header with a particular name. If a previous value was already set by the same,
  then the header will contain multiple values.
* ``removeHeader($header)``: Remove a header by name from the message.

.. code-block:: php

    $request = new Request('GET', 'http://httpbin.com/cookies');
    // addHeader will set and append to any existing header values
    $request->addHeader('Foo', 'bar');
    $request->addHeader('foo', 'baz');
    // setHeader overwrites any existing values
    $request->setHeader('Test', '123');

    // Request headers can be cast as a string
    echo $request->getHeader('Foo');
    // >>> bar, baz
    echo $request->getHeader('Test');
    // >>> 123

    // You can count the number of headers of a particular case insensitive name
    echo count($request->getHeader('foO'));
    // >>> 2

    // You can iterate over Header objects
    foreach ($request->getHeader('foo') as $header) {
        echo $header . "\n";
    }

    // You can get all of the request headers as a Guzzle\Http\Message\Header\HeaderCollection object
    $headers = $request->getHeaders();

    // Missing headers return NULL
    var_export($request->getHeader('Missing'));
    // >>> null

    // You can see all of the different variations of a header by calling raw() on the Header
    var_export($request->getHeader('foo')->raw());

Setting the body of a request
-----------------------------

Requests that can send a body (e.g. PUT, POST, DELETE, PATCH) are instances of
``Guzzle\Http\Message\EntityEnclosingRequestInterface``. Entity enclosing requests contain several methods that allow
you to specify the body to send with a request.

Use the ``setBody()`` method of a request to set the body that will be sent with a request. This method accepts a
string, a resource returned by ``fopen()``, an array, or an instance of ``Guzzle\Http\EntityBodyInterface``. The body
will then be streamed from the underlying ``EntityBodyInterface`` object owned by the request. When setting the body
of the request, you can optionally specify a Content-Type header and whether or not to force the request to use
chunked Transfer-Encoding.

.. code-block:: php

    $request = $client->put('/user.json');
    $request->setBody('{"foo":"baz"}', 'application/json');

Content-Type header
~~~~~~~~~~~~~~~~~~~

Guzzle will automatically add a Content-Type header to a request if the Content-Type can be guessed based on the file
extension of the payload being sent or the file extension present in the path of a request.

.. code-block:: php

    $request = $client->put('/user.json', array(), '{"foo":"bar"}');
    // The Content-Type was guessed based on the path of the request
    echo $request->getHeader('Content-Type');
    // >>> application/json

    $request = $client->put('/user.json');
    $request->setBody(fopen('/tmp/user_data.json', 'r'));
    // The Content-Type was guessed based on the path of the entity body
    echo $request->getHeader('Content-Type');
    // >>> application/json

Transfer-Encoding: chunked header
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When sending HTTP requests that contain a payload, you must let the remote server know how to determine when the entire
message has been sent. This usually is done by supplying a ``Content-Length`` header that tells the origin server the
size of the body that is to be sent. In some cases, the size of the payload being sent in a request cannot be known
before initiating the transfer. In these cases (when using HTTP/1.1), you can use the ``Transfer-Encoding: chunked``
header.

If the Content-Length cannot be determined (i.e. using a PHP ``http://`` stream), then Guzzle will automatically add
the ``Transfer-Encoding: chunked`` header to the request.

.. code-block:: php

    $request = $client->put('/user.json');
    $request->setBody(fopen('http://httpbin.org/get', 'r'));

    // The Content-Length could not be determined
    echo $request->getHeader('Transfer-Encoding');
    // >>> chunked

See :doc:`/http-client/entity-bodies` for more information on entity bodies.

Expect: 100-Continue header
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``Expect: 100-Continue`` header is used to help a client prevent sending a large payload to a server that will
reject the request. This allows clients to fail fast rather than waste bandwidth sending an erroneous payload. Guzzle
will automatically add the ``Expect: 100-Continue`` header to a request when the size of the payload exceeds 1MB or if
the body of the request is not seekable (this helps to prevent errors when a non-seekable body request is redirected).

.. note::

    If you find that your larger requests are taking too long to complete, you should first check if the
    ``Expect: 100-Continue`` header is being sent with the request. Some servers do not respond well to this header,
    which causes cURL to sleep for `1 second <http://curl.haxx.se/mail/lib-2010-01/0182.html>`_.

POST fields and files
~~~~~~~~~~~~~~~~~~~~~

Any entity enclosing request can send POST style fields and files. This includes POST, PUT, PATCH, and DELETE requests.
Any request that has set POST fields or files will use cURL's POST message functionality.

.. code-block:: php

    $request = $client->post('/post');
    // Set an overwrite any previously specified value
    $request->setPostField('foo', 'bar');
    // Append a value to any existing values
    $request->getPostFields()->add('foo', 'baz');
    // Remove a POST field by name
    $request->removePostField('fizz');

    // Add a file to upload (forces multipart/form-data)
    $request->addPostFile('my_file', '/path/to/file', 'plain/text');
    // Remove a POST file by POST key name
    $request->removePostFile('my_other_file');

.. tip::

    Adding a large number of POST fields to a POST request is faster if you use the ``addPostFields()`` method so that
    you can add and process multiple fields with a single call. Adding multiple POST files is also faster using
    ``addPostFiles()``.

Working with cookies
--------------------

Cookies can be modified and retrieved from a request using the following methods:

.. code-block:: php

    $request->addCookie($name, $value);
    $request->removeCookie($name);
    $value = $request->getCookie($name);
    $valueArray = $request->getCookies();

Use the :doc:`cookie plugin </plugins/cookie-plugin>` if you need to reuse cookies between requests.

.. _request-set-response-body:

Changing where a response is downloaded
----------------------------------------

When a request is sent, the body of the response will be stored in a PHP temp stream by default. You can change the
location in which the response will be downloaded using ``$request->setResponseBody($body)`` or the ``save_to`` request
option. This can be useful for downloading the contents of a URL to a specific file.

Here's an example of using request options:

.. code-block:: php

    $request = $this->client->get('http://example.com/large.mov', array(), array(
        'save_to' => '/tmp/large_file.mov'
    ));
    $request->send();
    var_export(file_exists('/tmp/large_file.mov'));
    // >>> true

Here's an example of using ``setResponseBody()``:

.. code-block:: php

    $body = fopen('/tmp/large_file.mov', 'w');
    $request = $this->client->get('http://example.com/large.mov');
    $request->setResponseBody($body);

    // You can more easily specify the name of a file to save the contents
    // of the response to by passing a string to ``setResponseBody()``.

    $request = $this->client->get('http://example.com/large.mov');
    $request->setResponseBody('/tmp/large_file.mov');

Custom cURL options
-------------------

Most of the functionality implemented in the libcurl bindings has been simplified and abstracted by Guzzle. Developers
who need access to `cURL specific functionality <http://www.php.net/curl_setopt>`_ can still add cURL handle
specific behavior to Guzzle HTTP requests by modifying the cURL options collection of a request:

.. code-block:: php

    $request->getCurlOptions()->set(CURLOPT_LOW_SPEED_LIMIT, 200);

Other special options that can be set in the ``curl.options`` array include:

+-------------------------+---------------------------------------------------------------------------------+
| debug                   | Adds verbose cURL output to a temp stream owned by the cURL handle object       |
+-------------------------+---------------------------------------------------------------------------------+
| progress                | Instructs cURL to emit events when IO events occur. This allows you to be       |
|                         | notified when bytes are transferred over the wire by subscribing to a request's |
|                         | ``curl.callback.read``, ``curl.callback.write``, and ``curl.callback.progress`` |
|                         | events.                                                                         |
+-------------------------+---------------------------------------------------------------------------------+

Request options
---------------

Requests options can be specified when creating a request or in the ``request.options`` parameter of a client. These
options can control various aspects of a request including: headers to send, query string data, where the response
should be downloaded, proxies, auth, etc.

.. code-block:: php

    $request = $client->get($url, $headers, array('proxy' => 'http://proxy.com'));

See :ref:`Request options <request-options>` for more information.

Working with errors
-------------------

HTTP errors
~~~~~~~~~~~

Requests that receive a 4xx or 5xx response will throw a ``Guzzle\Http\Exception\BadResponseException``. More
specifically, 4xx errors throw a ``Guzzle\Http\Exception\ClientErrorResponseException``, and 5xx errors throw a
``Guzzle\Http\Exception\ServerErrorResponseException``. You can catch the specific exceptions or just catch the
BadResponseException to deal with either type of error. Here's an example of catching a generic BadResponseException:

.. code-block:: php

    try {
        $response = $client->get('/not_found.xml')->send();
    } catch (Guzzle\Http\Exception\BadResponseException $e) {
        echo 'Uh oh! ' . $e->getMessage();
        echo 'HTTP request URL: ' . $e->getRequest()->getUrl() . "\n";
        echo 'HTTP request: ' . $e->getRequest() . "\n";
        echo 'HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n";
        echo 'HTTP response: ' . $e->getResponse() . "\n";
    }

Throwing an exception when a 4xx or 5xx response is encountered is the default behavior of Guzzle requests. This
behavior can be overridden by adding an event listener with a higher priority than -255 that stops event propagation.
You can subscribe to ``request.error`` to receive notifications any time an unsuccessful response is received.

You can change the response that will be associated with the request by calling ``setResponse()`` on the
``$event['request']`` object passed into your listener, or by changing the ``$event['response']`` value of the
``Guzzle\Common\Event`` object that is passed to your listener. Transparently changing the response associated with a
request by modifying the event allows you to retry failed requests without complicating the code that uses the client.
This might be useful for sending requests to a web service that has expiring auth tokens. When a response shows that
your token has expired, you can get a new token, retry the request with the new token, and return the successful
response to the user.

Here's an example of retrying a request using updated authorization credentials when a 401 response is received,
overriding the response of the original request with the new response, and still allowing the default exception
behavior to be called when other non-200 response status codes are encountered:

.. code-block:: php

    // Add custom error handling to any request created by this client
    $client->getEventDispatcher()->addListener('request.error', function(Event $event) {

        if ($event['response']->getStatusCode() == 401) {

            $newRequest = $event['request']->clone();
            $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // You can also change the response and fire the normal chain of
            // events by calling $event['request']->setResponse($newResponse);

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }

    });

cURL errors
~~~~~~~~~~~

Connection problems and cURL specific errors can also occur when transferring requests using Guzzle. When Guzzle
encounters cURL specific errors while transferring a single request, a ``Guzzle\Http\Exception\CurlException`` is
thrown with an informative error message and access to the cURL error message.

A ``Guzzle\Http\Exception\MultiTransferException`` exception is thrown when a cURL specific error occurs while
transferring multiple requests in parallel. You can then iterate over all of the exceptions encountered during the
transfer.

Plugins and events
------------------

Guzzle request objects expose various events that allow you to hook in custom logic. A request object owns a
``Symfony\Component\EventDispatcher\EventDispatcher`` object that can be accessed by calling
``$request->getEventDispatcher()``. You can use the event dispatcher to add listeners (a simple callback function) or
event subscribers (classes that listen to specific events of a dispatcher). You can add event subscribers to a request
directly by just calling ``$request->addSubscriber($mySubscriber);``.

.. _request-events:

Events emitted from a request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A ``Guzzle\Http\Message\Request`` and ``Guzzle\Http\Message\EntityEnclosingRequest`` object emit the following events:

+------------------------------+--------------------------------------------+------------------------------------------+
| Event name                   | Description                                | Event data                               |
+==============================+============================================+==========================================+
| request.before_send          | About to send request                      | * request: Request to be sent            |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.sent                 | Sent the request                           | * request: Request that was sent         |
|                              |                                            | * response: Received response            |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.complete             | Completed a full HTTP transaction          | * request: Request that was sent         |
|                              |                                            | * response: Received response            |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.success              | Completed a successful request             | * request: Request that was sent         |
|                              |                                            | * response: Received response            |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.error                | Completed an unsuccessful request          | * request: Request that was sent         |
|                              |                                            | * response: Received response            |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.exception            | An unsuccessful response was               | * request: Request                       |
|                              | received.                                  | * response: Received response            |
|                              |                                            | * exception: BadResponseException        |
+------------------------------+--------------------------------------------+------------------------------------------+
| request.receive.status_line  | Received the start of a response           | * line: Full response start line         |
|                              |                                            | * status_code: Status code               |
|                              |                                            | * reason_phrase: Reason phrase           |
|                              |                                            | * previous_response: (e.g. redirect)     |
+------------------------------+--------------------------------------------+------------------------------------------+
| curl.callback.progress       | cURL progress event (only dispatched when  | * handle: CurlHandle                     |
|                              | ``emit_io`` is set on a request's curl     | * download_size: Total download size     |
|                              | options)                                   | * downloaded: Bytes downloaded           |
|                              |                                            | * upload_size: Total upload bytes        |
|                              |                                            | * uploaded: Bytes uploaded               |
+------------------------------+--------------------------------------------+------------------------------------------+
| curl.callback.write          | cURL event called when data is written to  | * request: Request                       |
|                              | an outgoing stream                         | * write: Data being written              |
+------------------------------+--------------------------------------------+------------------------------------------+
| curl.callback.read           | cURL event called when data is written to  | * request: Request                       |
|                              | an incoming stream                         | * read: Data being read                  |
+------------------------------+--------------------------------------------+------------------------------------------+

Creating a request event listener
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here's an example that listens to the ``request.complete`` event of a request and prints the request and response.

.. code-block:: php

    use Guzzle\Common\Event;

    $request = $client->get('http://www.google.com');

    // Echo out the response that was received
    $request->getEventDispatcher()->addListener('request.complete', function (Event $e) {
        echo $e['request'] . "\n\n";
        echo $e['response'];
    });
===========================
Request and response bodies
===========================

`Entity body <http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html>`_ is the term used for the body of an HTTP
message. The entity body of requests and responses is inherently a
`PHP stream <http://php.net/manual/en/book.stream.php>`_ in Guzzle. The body of the request can be either a string or
a PHP stream which are converted into a ``Guzzle\Http\EntityBody`` object using its factory method. When using a
string, the entity body is stored in a `temp PHP stream <http://www.php.net/manual/en/wrappers.php.php>`_. The use of
temp PHP streams helps to protect your application from running out of memory when sending or receiving large entity
bodies in your messages. When more than 2MB of data is stored in a temp stream, it automatically stores the data on
disk rather than in memory.

EntityBody objects provide a great deal of functionality: compression, decompression, calculate the Content-MD5,
calculate the Content-Length (when the resource is repeatable), guessing the Content-Type, and more. Guzzle doesn't
need to load an entire entity body into a string when sending or retrieving data; entity bodies are streamed when
being uploaded and downloaded.

Here's an example of gzip compressing a text file then sending the file to a URL:

.. code-block:: php

    use Guzzle\Http\EntityBody;

    $body = EntityBody::factory(fopen('/path/to/file.txt', 'r+'));
    echo $body->read(1024);
    $body->seek(0, SEEK_END);
    $body->write('foo');
    echo $body->ftell();
    $body->rewind();

    // Send a request using the body
    $response = $client->put('http://localhost:8080/uploads', null, $body)->send();

The body of the request can be specified in the ``Client::put()`` or ``Client::post()``  method, or, you can specify
the body of the request by calling the ``setBody()`` method of any
``Guzzle\Http\Message\EntityEnclosingRequestInterface`` object.

Compression
-----------

You can compress the contents of an EntityBody object using the ``compress()`` method. The compress method accepts a
filter that must match to one of the supported
`PHP stream filters <http://www.php.net/manual/en/filters.compression.php>`_ on your system (e.g. `zlib.deflate`,
``bzip2.compress``, etc). Compressing an entity body will stream the entire entity body through a stream compression
filter into a temporary PHP stream. You can uncompress an entity body using the ``uncompress()`` method and passing
the PHP stream filter to use when decompressing the stream (e.g. ``zlib.inflate``).

.. code-block:: php

    use Guzzle\Http\EntityBody;

    $body = EntityBody::factory(fopen('/tmp/test.txt', 'r+'));
    echo $body->getSize();
    // >>> 1048576

    // Compress using the default zlib.deflate filter
    $body->compress();
    echo $body->getSize();
    // >>> 314572

    // Decompress the stream
    $body->uncompress();
    echo $body->getSize();
    // >>> 1048576

Decorators
----------

Guzzle provides several EntityBody decorators that can be used to add functionality to an EntityBody at runtime.

IoEmittingEntityBody
~~~~~~~~~~~~~~~~~~~~

This decorator will emit events when data is read from a stream or written to a stream. Add an event subscriber to the
entity body's ``body.read`` or ``body.write`` methods to receive notifications when data data is transferred.

.. code-block:: php

    use Guzzle\Common\Event;
    use Guzzle\Http\EntityBody;
    use Guzzle\Http\IoEmittingEntityBody;

    $original = EntityBody::factory(fopen('/tmp/test.txt', 'r+'));
    $body = new IoEmittingEntityBody($original);

    // Listen for read events
    $body->getEventDispatcher()->addListener('body.read', function (Event $e) {
        // Grab data from the event
        $entityBody = $e['body'];
        // Amount of data retrieved from the body
        $lengthOfData = $e['length'];
        // The actual data that was read
        $data = $e['read'];
    });

    // Listen for write events
    $body->getEventDispatcher()->addListener('body.write', function (Event $e) {
        // Grab data from the event
        $entityBody = $e['body'];
        // The data that was written
        $data = $e['write'];
        // The actual amount of data that was written
        $data = $e['read'];
    });

ReadLimitEntityBody
~~~~~~~~~~~~~~~~~~~

The ReadLimitEntityBody decorator can be used to transfer a subset or slice of an existing EntityBody object. This can
be useful for breaking a large file into smaller pieces to be sent in chunks (e.g. Amazon S3's multipart upload API).

.. code-block:: php

    use Guzzle\Http\EntityBody;
    use Guzzle\Http\ReadLimitEntityBody;

    $original = EntityBody::factory(fopen('/tmp/test.txt', 'r+'));
    echo $original->getSize();
    // >>> 1048576

    // Limit the size of the body to 1024 bytes and start reading from byte 2048
    $body = new ReadLimitEntityBody($original, 1024, 2048);
    echo $body->getSize();
    // >>> 1024
    echo $body->ftell();
    // >>> 0

CachingEntityBody
~~~~~~~~~~~~~~~~~

The CachingEntityBody decorator is used to allow seeking over previously read bytes on non-seekable read streams. This
can be useful when transferring a non-seekable entity body fails due to needing to rewind the stream (for example,
resulting from a redirect). Data that is read from the remote stream will be buffered in a PHP temp stream so that
previously read bytes are cached first in memory, then on disk.

.. code-block:: php

    use Guzzle\Http\EntityBody;
    use Guzzle\Http\CachingEntityBody;

    $original = EntityBody::factory(fopen('http://www.google.com', 'r'));
    $body = new CachingEntityBody($original);

    $body->read(1024);
    echo $body->ftell();
    // >>> 1024

    $body->seek(0);
    echo $body->ftell();
    // >>> 0
======================
The Guzzle HTTP client
======================

Guzzle gives PHP developers complete control over HTTP requests while utilizing HTTP/1.1 best practices. Guzzle's HTTP
functionality is a robust framework built on top of the `PHP libcurl bindings <http://www.php.net/curl>`_.

The three main parts of the Guzzle HTTP client are:

+--------------+-------------------------------------------------------------------------------------------------------+
| Clients      | ``Guzzle\Http\Client`` (creates and sends requests, associates a response with a request)             |
+--------------+-------------------------------------------------------------------------------------------------------+
| Requests     | ``Guzzle\Http\Message\Request`` (requests with no body),                                              |
|              | ``Guzzle\Http\Message\EntityEnclosingRequest`` (requests with a body)                                 |
+--------------+-------------------------------------------------------------------------------------------------------+
| Responses    | ``Guzzle\Http\Message\Response``                                                                      |
+--------------+-------------------------------------------------------------------------------------------------------+

Creating a Client
-----------------

Clients create requests, send requests, and set responses on a request object. When instantiating a client object,
you can pass an optional "base URL" and optional array of configuration options. A base URL is a
:doc:`URI template <uri-templates>` that contains the URL of a remote server. When creating requests with a relative
URL, the base URL of a client will be merged into the request's URL.

.. code-block:: php

    use Guzzle\Http\Client;

    // Create a client and provide a base URL
    $client = new Client('https://api.github.com');

    $request = $client->get('/user');
    $request->setAuth('user', 'pass');
    echo $request->getUrl();
    // >>> https://api.github.com/user

    // You must send a request in order for the transfer to occur
    $response = $request->send();

    echo $response->getBody();
    // >>> {"type":"User", ...

    echo $response->getHeader('Content-Length');
    // >>> 792

    $data = $response->json();
    echo $data['type'];
    // >>> User

Base URLs
~~~~~~~~~

Notice that the URL provided to the client's ``get()`` method is relative. Relative URLs will always merge into the
base URL of the client. There are a few rules that control how the URLs are merged.

.. tip::

    Guzzle follows `RFC 3986 <http://tools.ietf.org/html/rfc3986#section-5.2>`_ when merging base URLs and
    relative URLs.

In the above example, we passed ``/user`` to the ``get()`` method of the client. This is a relative URL, so it will
merge into the base URL of the client-- resulting in the derived URL of ``https://api.github.com/users``.

``/user`` is a relative URL but uses an absolute path because it contains the leading slash. Absolute paths will
overwrite any existing path of the base URL. If an absolute path is provided (e.g. ``/path/to/something``), then the
path specified in the base URL of the client will be replaced with the absolute path, and the query string provided
by the relative URL will replace the query string of the base URL.

Omitting the leading slash and using relative paths will add to the path of the base URL of the client. So using a
client base URL of ``https://api.twitter.com/v1.1`` and creating a GET request with ``statuses/user_timeline.json``
will result in a URL of ``https://api.twitter.com/v1.1/statuses/user_timeline.json``. If a relative path and a query
string are provided, then the relative path will be appended to the base URL path, and the query string provided will
be merged into the query string of the base URL.

If an absolute URL is provided (e.g. ``http://httpbin.org/ip``), then the request will completely use the absolute URL
as-is without merging in any of the URL parts specified in the base URL.

Configuration options
~~~~~~~~~~~~~~~~~~~~~

The second argument of the client's constructor is an array of configuration data. This can include URI template data
or special options that alter the client's behavior:

+-------------------------------+-------------------------------------------------------------------------------------+
| ``request.options``           | Associative array of :ref:`Request options <request-options>` to apply to every     |
|                               | request created by the client.                                                      |
+-------------------------------+-------------------------------------------------------------------------------------+
| ``redirect.disable``          | Disable HTTP redirects for every request created by the client.                     |
+-------------------------------+-------------------------------------------------------------------------------------+
| ``curl.options``              | Associative array of cURL options to apply to every request created by the client.  |
|                               | if either the key or value of an entry in the array is a string, Guzzle will        |
|                               | attempt to find a matching defined cURL constant automatically (e.g.                |
|                               | "CURLOPT_PROXY" will be converted to the constant ``CURLOPT_PROXY``).               |
+-------------------------------+-------------------------------------------------------------------------------------+
| ``ssl.certificate_authority`` | Set to true to use the Guzzle bundled SSL certificate bundle (this is used by       |
|                               | default, 'system' to use the bundle on your system, a string pointing to a file to  |
|                               | use a specific certificate file, a string pointing to a directory to use multiple   |
|                               | certificates, or ``false`` to disable SSL validation (not recommended).             |
|                               |                                                                                     |
|                               | When using  Guzzle inside of a phar file, the bundled SSL certificate will be       |
|                               | extracted to your system's temp folder, and each time a client is created an MD5    |
|                               | check will be performed to ensure the integrity of the certificate.                 |
+-------------------------------+-------------------------------------------------------------------------------------+
| ``command.params``            | When using a ``Guzzle\Service\Client`` object, this is an associative array of      |
|                               | default options to set on each command created by the client.                       |
+-------------------------------+-------------------------------------------------------------------------------------+

Here's an example showing how to set various configuration options, including default headers to send with each request,
default query string parameters to add to each request, a default auth scheme for each request, and a proxy to use for
each request. Values can be injected into the client's base URL using variables from the configuration array.

.. code-block:: php

    use Guzzle\Http\Client;

    $client = new Client('https://api.twitter.com/{version}', array(
        'version'        => 'v1.1',
        'request.options' => array(
            'headers' => array('Foo' => 'Bar'),
            'query'   => array('testing' => '123'),
            'auth'    => array('username', 'password', 'Basic|Digest|NTLM|Any'),
            'proxy'   => 'tcp://localhost:80'
        )
    ));

Setting a custom User-Agent
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The default Guzzle User-Agent header is ``Guzzle/<Guzzle_Version> curl/<curl_version> PHP/<PHP_VERSION>``. You can
customize the User-Agent header of a client by calling the ``setUserAgent()`` method of a Client object.

.. code-block:: php

    // Completely override the default User-Agent
    $client->setUserAgent('Test/123');

    // Prepend a string to the default User-Agent
    $client->setUserAgent('Test/123', true);

Creating requests with a client
-------------------------------

A Client object exposes several methods used to create Request objects:

* Create a custom HTTP request: ``$client->createRequest($method, $uri, array $headers, $body, $options)``
* Create a GET request: ``$client->get($uri, array $headers, $options)``
* Create a HEAD request: ``$client->head($uri, array $headers, $options)``
* Create a DELETE request: ``$client->delete($uri, array $headers, $body, $options)``
* Create a POST request: ``$client->post($uri, array $headers, $postBody, $options)``
* Create a PUT request: ``$client->put($uri, array $headers, $body, $options)``
* Create a PATCH request: ``$client->patch($uri, array $headers, $body, $options)``

.. code-block:: php

    use Guzzle\Http\Client;

    $client = new Client('http://baseurl.com/api/v1');

    // Create a GET request using Relative to base URL
    // URL of the request: http://baseurl.com/api/v1/path?query=123&value=abc)
    $request = $client->get('path?query=123&value=abc');
    $response = $request->send();

    // Create HEAD request using a relative URL with an absolute path
    // URL of the request: http://baseurl.com/path?query=123&value=abc
    $request = $client->head('/path?query=123&value=abc');
    $response = $request->send();

    // Create a DELETE request using an absolute URL
    $request = $client->delete('http://www.example.com/path?query=123&value=abc');
    $response = $request->send();

    // Create a PUT request using the contents of a PHP stream as the body
    // Specify custom HTTP headers
    $request = $client->put('http://www.example.com/upload', array(
        'X-Header' => 'My Header'
    ), fopen('http://www.test.com/', 'r'));
    $response = $request->send();

    // Create a POST request and add the POST files manually
    $request = $client->post('http://localhost:8983/solr/update')
        ->addPostFiles(array('file' => '/path/to/documents.xml'));
    $response = $request->send();

    // Check if a resource supports the DELETE method
    $supportsDelete = $client->options('/path')->send()->isMethodAllowed('DELETE');
    $response = $request->send();

Client objects create Request objects using a request factory (``Guzzle\Http\Message\RequestFactoryInterface``).
You can inject a custom request factory into the Client using ``$client->setRequestFactory()``, but you can typically
rely on a Client's default request factory.

Static clients
--------------

You can use Guzzle's static client facade to more easily send simple HTTP requests.

.. code-block:: php

    // Mount the client so that you can access it at \Guzzle
    Guzzle\Http\StaticClient::mount();
    $response = Guzzle::get('http://guzzlephp.org');

Each request method of the static client (e.g. ``get()``, ``post()`, ``put()``, etc) accepts an associative array of request
options to apply to the request.

.. code-block:: php

    $response = Guzzle::post('http://test.com', array(
        'headers' => array('X-Foo' => 'Bar'),
        'body'    => array('Test' => '123'),
        'timeout' => 10
    ));

.. _request-options:

Request options
---------------

Request options can be specified when creating a request or in the ``request.options`` parameter of a client. These
options can control various aspects of a request including: headers to send, query string data, where the response
should be downloaded, proxies, auth, etc.

headers
~~~~~~~

Associative array of headers to apply to the request. When specified in the ``$options`` argument of a client creational
method (e.g. ``get()``, ``post()``, etc), the headers in the ``$options`` array will overwrite headers specified in the
``$headers`` array.

.. code-block:: php

    $request = $client->get($url, array(), array(
        'headers' => array('X-Foo' => 'Bar')
    ));

Headers can be specified on a client to add default headers to every request sent by a client.

.. code-block:: php

    $client = new Guzzle\Http\Client();

    // Set a single header using path syntax
    $client->setDefaultOption('headers/X-Foo', 'Bar');

    // Set all headers
    $client->setDefaultOption('headers', array('X-Foo' => 'Bar'));

.. note::

    In addition to setting request options when creating requests or using the ``setDefaultOption()`` method, any
    default client request option can be set using a client's config object:

    .. code-block:: php

        $client->getConfig()->setPath('request.options/headers/X-Foo', 'Bar');

query
~~~~~

Associative array of query string parameters to the request. When specified in the ``$options`` argument of a client
creational method, the query string parameters in the ``$options`` array will overwrite query string parameters
specified in the `$url`.

.. code-block:: php

    $request = $client->get($url, array(), array(
        'query' => array('abc' => '123')
    ));

Query string parameters can be specified on a client to add default query string parameters to every request sent by a
client.

.. code-block:: php

    $client = new Guzzle\Http\Client();

    // Set a single query string parameter using path syntax
    $client->setDefaultOption('query/abc', '123');

    // Set an array of default query string parameters
    $client->setDefaultOption('query', array('abc' => '123'));

body
~~~~

Sets the body of a request. The value supplied to the body option can be a ``Guzzle\Http\EntityBodyInterface``, string,
fopen resource, or array when sending POST requests. When a ``body`` request option is supplied, the option value will
overwrite the ``$body`` argument of a client creational method.

auth
~~~~

Specifies and array of HTTP authorization parameters parameters to use with the request. The array must contain the
username in index [0], the password in index [1], and can optionally contain the authentication type in index [2].
The available authentication types are: "Basic" (default), "Digest", "NTLM", or "Any".

.. code-block:: php

    $request = $client->get($url, array(), array(
        'auth' => array('username', 'password', 'Digest')
    ));

    // You can add auth headers to every request of a client
    $client->setDefaultOption('auth', array('username', 'password', 'Digest'));

cookies
~~~~~~~

Specifies an associative array of cookies to add to the request.

allow_redirects
~~~~~~~~~~~~~~~

Specifies whether or not the request should follow redirects. Requests will follow redirects by default. Set
``allow_redirects`` to ``false`` to disable redirects.

save_to
~~~~~~~

The ``save_to`` option specifies where the body of a response is downloaded. You can pass the path to a file, an fopen
resource, or a ``Guzzle\Http\EntityBodyInterface`` object.

See :ref:`Changing where a response is downloaded <request-set-response-body>` for more information on setting the
`save_to` option.

events
~~~~~~

The `events` option makes it easy to attach listeners to the various events emitted by a request object. The `events`
options must be an associative array mapping an event name to a Closure or array the contains a Closure and the
priority of the event.

.. code-block:: php

    $request = $client->get($url, array(), array(
        'events' => array(
            'request.before_send' => function (\Guzzle\Common\Event $e) {
                echo 'About to send ' . $e['request'];
            }
        )
    ));

    // Using the static client:
    Guzzle::get($url, array(
        'events' => array(
            'request.before_send' => function (\Guzzle\Common\Event $e) {
                echo 'About to send ' . $e['request'];
            }
        )
    ));

plugins
~~~~~~~

The `plugins` options makes it easy to attach an array of plugins to a request.

.. code-block:: php

    // Using the static client:
    Guzzle::get($url, array(
        'plugins' => array(
            new Guzzle\Plugin\Cache\CachePlugin(),
            new Guzzle\Plugin\Cookie\CookiePlugin()
        )
    ));

exceptions
~~~~~~~~~~

The `exceptions` option can be used to disable throwing exceptions for unsuccessful HTTP response codes
(e.g. 404, 500, etc). Set `exceptions` to false to not throw exceptions.

params
~~~~~~

The `params` options can be used to specify an associative array of data parameters to add to a request.  Note that
these are not query string parameters.

timeout / connect_timeout
~~~~~~~~~~~~~~~~~~~~~~~~~

You can specify the maximum number of seconds to allow for an entire transfer to take place before timing out using
the `timeout` request option. You can specify the maximum number of seconds to wait while trying to connect using the
`connect_timeout` request option. Set either of these options to 0 to wait indefinitely.

.. code-block:: php

    $request = $client->get('http://www.example.com', array(), array(
        'timeout'         => 20,
        'connect_timeout' => 1.5
    ));

verify
~~~~~~

Set to true to enable SSL certificate validation (the default), false to disable SSL certificate validation, or supply
the path to a CA bundle to enable verification using a custom certificate.

cert
~~~~

The `cert` option lets you specify a PEM formatted SSL client certificate to use with servers that require one. If the
certificate requires a password, provide an array with the password as the second item.

This would typically be used in conjunction with the `ssl_key` option.

.. code-block:: php

    $request = $client->get('https://www.example.com', array(), array(
        'cert' => '/etc/pki/client_certificate.pem'
    )

    $request = $client->get('https://www.example.com', array(), array(
        'cert' => array('/etc/pki/client_certificate.pem', 's3cr3tp455w0rd')
    )

ssl_key
~~~~~~~

The `ssl_key` option lets you specify a file containing your PEM formatted private key, optionally protected by a password.
Note: your password is sensitive, keep the PHP script containing it safe.

This would typically be used in conjunction with the `cert` option.

.. code-block:: php

    $request = $client->get('https://www.example.com', array(), array(
        'ssl_key' => '/etc/pki/private_key.pem'
    )

    $request = $client->get('https://www.example.com', array(), array(
        'ssl_key' => array('/etc/pki/private_key.pem', 's3cr3tp455w0rd')
    )

proxy
~~~~~

The `proxy` option is used to specify an HTTP proxy (e.g. `http://username:password@192.168.16.1:10`).

debug
~~~~~

The `debug` option is used to show verbose cURL output for a transfer.

stream
~~~~~~

When using a static client, you can set the `stream` option to true to return a `Guzzle\Stream\Stream` object that can
be used to pull data from a stream as needed (rather than have cURL download the entire contents of a response to a
stream all at once).

.. code-block:: php

    $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true));
    while (!$stream->feof()) {
        echo $stream->readLine();
    }

Sending requests
----------------

Requests can be sent by calling the ``send()`` method of a Request object, but you can also send requests using the
``send()`` method of a Client.

.. code-block:: php

    $request = $client->get('http://www.amazon.com');
    $response = $client->send($request);

Sending requests in parallel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The Client's ``send()`` method accept a single ``Guzzle\Http\Message\RequestInterface`` object or an array of
RequestInterface objects. When an array is specified, the requests will be sent in parallel.

Sending many HTTP requests serially (one at a time) can cause an unnecessary delay in a script's execution. Each
request must complete before a subsequent request can be sent. By sending requests in parallel, a pool of HTTP
requests can complete at the speed of the slowest request in the pool, significantly reducing the amount of time
needed to execute multiple HTTP requests. Guzzle provides a wrapper for the curl_multi functions in PHP.

Here's an example of sending three requests in parallel using a client object:

.. code-block:: php

    use Guzzle\Common\Exception\MultiTransferException;

    try {
        $responses = $client->send(array(
            $client->get('http://www.google.com/'),
            $client->head('http://www.google.com/'),
            $client->get('https://www.github.com/')
        ));
    } catch (MultiTransferException $e) {

        echo "The following exceptions were encountered:\n";
        foreach ($e as $exception) {
            echo $exception->getMessage() . "\n";
        }

        echo "The following requests failed:\n";
        foreach ($e->getFailedRequests() as $request) {
            echo $request . "\n\n";
        }

        echo "The following requests succeeded:\n";
        foreach ($e->getSuccessfulRequests() as $request) {
            echo $request . "\n\n";
        }
    }

If the requests succeed, an array of ``Guzzle\Http\Message\Response`` objects are returned. A single request failure
will not cause the entire pool of requests to fail. Any exceptions thrown while transferring a pool of requests will
be aggregated into a ``Guzzle\Common\Exception\MultiTransferException`` exception.

Plugins and events
------------------

Guzzle provides easy to use request plugins that add behavior to requests based on signal slot event notifications
powered by the
`Symfony2 Event Dispatcher component <http://symfony.com/doc/2.0/components/event_dispatcher/introduction.html>`_. Any
event listener or subscriber attached to a Client object will automatically be attached to each request created by the
client.

Using the same cookie session for each request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Attach a ``Guzzle\Plugin\Cookie\CookiePlugin`` to a client which will in turn add support for cookies to every request
created by a client, and each request will use the same cookie session:

.. code-block:: php

    use Guzzle\Plugin\Cookie\CookiePlugin;
    use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

    // Create a new cookie plugin
    $cookiePlugin = new CookiePlugin(new ArrayCookieJar());

    // Add the cookie plugin to the client
    $client->addSubscriber($cookiePlugin);

.. _client-events:

Events emitted from a client
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A ``Guzzle\Http\Client`` object emits the following events:

+------------------------------+--------------------------------------------+------------------------------------------+
| Event name                   | Description                                | Event data                               |
+==============================+============================================+==========================================+
| client.create_request        | Called when a client creates a request     | * client: The client                     |
|                              |                                            | * request: The created request           |
+------------------------------+--------------------------------------------+------------------------------------------+

.. code-block:: php

    use Guzzle\Common\Event;
    use Guzzle\Http\Client;

    $client = new Client();

    // Add a listener that will echo out requests as they are created
    $client->getEventDispatcher()->addListener('client.create_request', function (Event $e) {
        echo 'Client object: ' . spl_object_hash($e['client']) . "\n";
        echo "Request object: {$e['request']}\n";
    });
==================
Resource iterators
==================

Web services often implement pagination in their responses which requires the end-user to issue a series of consecutive
requests in order to fetch all of the data they asked for. Users of your web service client should not be responsible
for implementing the logic involved in iterating through pages of results. Guzzle provides a simple resource iterator
foundation to make it easier on web service client developers to offer a useful abstraction layer.

Getting an iterator from a client
---------------------------------

    ResourceIteratorInterface Guzzle\Service\Client::getIterator($command [, array $commandOptions, array $iteratorOptions ])

The ``getIterator`` method of a ``Guzzle\Service\ClientInterface`` object provides a convenient interface for
instantiating a resource iterator for a specific command. This method implicitly uses a
``Guzzle\Service\Resource\ResourceIteratorFactoryInterface`` object to create resource iterators. Pass an
instantiated command object or the name of a command in the first argument. When passing the name of a command, the
command factory of the client will create the command by name using the ``$commandOptions`` array. The third argument
may be used to pass an array of options to the constructor of the instantiated ``ResourceIteratorInterface`` object.

.. code-block:: php

    $iterator = $client->getIterator('get_users');

    foreach ($iterator as $user) {
        echo $user['name'] . ' age ' . $user['age'] . PHP_EOL;
    }

The above code sample might execute a single request or a thousand requests. As a consumer of a web service, I don't
care. I just want to iterate over all of the users.

Iterator options
~~~~~~~~~~~~~~~~

The two universal options that iterators should support are ``limit`` and ``page_size``. Using the ``limit`` option
tells the resource iterator to attempt to limit the total number of iterated resources to a specific amount. Keep in
mind that this is not always possible due to limitations that may be inherent to a web service. The ``page_size``
option is used to tell a resource iterator how many resources to request per page of results. Much like the ``limit``
option, you can not rely on getting back exactly the number of resources your specify in the ``page_size`` option.

.. note::

    The ``limit`` and ``page_size`` options can also be specified on an iterator using the ``setLimit($limit)`` and
    ``setPageSize($pageSize)`` methods.

Resolving iterator class names
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The default resource iterator factory of a client object expects that your iterators are stored under the ``Model``
folder of your client and that an iterator is names after the CamelCase name of a command followed by the word
"Iterator". For example, if you wanted to create an iterator for the ``get_users`` command, then your iterator class
would be ``Model\GetUsersIterator`` and would be stored in ``Model/GetUsersIterator.php``.

Creating an iterator
--------------------

While not required, resource iterators in Guzzle typically iterate using a ``Guzzle\Service\Command\CommandInterface``
object. ``Guzzle\Service\Resource\ResourceIterator``, the default iterator implementation that you should extend,
accepts a command object and array of iterator options in its constructor. The command object passed to the resource
iterator is expected to be ready to execute and not previously executed. The resource iterator keeps a reference of
this command and clones the original command each time a subsequent request needs to be made to fetch more data.

Implement the sendRequest method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The most important thing (and usually the only thing) you need to do when creating a resource iterator is to implement
the ``sendRequest()`` method of the resource iterator. The ``sendRequest()`` method is called when you begin
iterating or if there are no resources left to iterate and it you expect to retrieve more resources by making a
subsequent request. The ``$this->command`` property of the resource iterator is updated with a cloned copy of the
original command object passed into the constructor of the iterator. Use this command object to issue your subsequent
requests.

The ``sendRequest()`` method must return an array of the resources you retrieved from making the subsequent call.
Returning an empty array will stop the iteration. If you suspect that your web service client will occasionally return
an empty result set but still requires further iteration, then you must implement a sort of loop in your
``sendRequest()`` method that will continue to issue subsequent requests until your reach the end of the paginated
result set or until additional resources are retrieved from the web service.

Update the nextToken property
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Beyond fetching more results, the ``sendRequest()`` method is responsible for updating the ``$this->nextToken``
property of the iterator. Setting this property to anything other than null tells the iterator that issuing a
subsequent request using the nextToken value will probably return more results. You must continually update this
value in your ``sendRequest()`` method as each response is received from the web service.

Example iterator
----------------

Let's say you want to implement a resource iterator for the ``get_users`` command of your web service. The
``get_users`` command receives a response that contains a list of users, and if there are more pages of results to
retrieve, returns a value called ``next_user``. This return value is known as the **next token** and should be used to
issue subsequent requests.

Assume the response to a ``get_users`` command returns JSON data that looks like this:

.. code-block:: javascript

    {
        "users": [
            { "name": "Craig Johnson", "age": 10 },
            { "name": "Tom Barker", "age": 20 },
            { "name": "Bob Mitchell", "age": 74 }
        ],
        "next_user": "Michael Dowling"
    }

Assume that because there is a ``next_user`` value, there will be more users if a subsequent request is issued. If the
``next_user`` value is missing or null, then we know there are no more results to fetch. Let's implement a resource
iterator for this command.

.. code-block:: php

    namespace MyService\Model;

    use Guzzle\Service\Resource\ResourceIterator;

    /**
     * Iterate over a get_users command
     */
    class GetUsersIterator extends ResourceIterator
    {
        protected function sendRequest()
        {
            // If a next token is set, then add it to the command
            if ($this->nextToken) {
                $this->command->set('next_user', $this->nextToken);
            }

            // Execute the command and parse the result
            $result = $this->command->execute();

            // Parse the next token
            $this->nextToken = isset($result['next_user']) ? $result['next_user'] : false;

            return $result['users'];
        }
    }

As you can see, it's pretty simple to implement an iterator. There are a few things that you should notice from this
example:

1. You do not need to create a new command in the ``sendRequest()`` method. A new command object is cloned from the
   original command passed into the constructor of the iterator before the ``sendRequest()`` method is called.
   Remember that the resource iterator expects a command that has not been executed.
2. When the ``sendRequest()`` method is first called, you will not have a ``$this->nextToken`` value, so always check
   before setting it on a command. Notice that the next token is being updated each time a request is sent.
3. After fetching more resources from the service, always return an array of resources.
================
Guzzle iterators
================

Guzzle provides several SPL iterators that can be used with other SPL iterators, including Guzzle resource iterators.
Guzzle's ``guzzle/iterator`` component can also be used independently of the rest of Guzzle through Packagist and
Composer: https://packagist.org/packages/guzzle/iterator

ChunkedIterator
---------------

Pulls out multiple values from an inner iterator and yields and array of values for each outer iteration -- essentially
pulling out chunks of values from the inner iterator.

.. code-block:: php

    use Guzzle\Iterator\ChunkedIterator;

    $inner = new ArrayIterator(range(0, 8));
    $chunkedIterator = new ChunkedIterator($inner, 2);

    foreach ($chunkedIterator as $chunk) {
        echo implode(', ', $chunk) . "\n";
    }

    // >>> 0, 1
    // >>> 2, 3
    // >>> 4, 5
    // >>> 6, 7
    // >>> 8

FilterIterator
--------------

This iterator is used to filter values out of the inner iterator. This iterator can be used when PHP 5.4's
CallbackFilterIterator is not available.

.. code-block:: php

    use Guzzle\Iterator\FilterIterator;

    $inner = new ArrayIterator(range(1, 10));
    $filterIterator = new FilterIterator($inner, function ($value) {
        return $value % 2;
    });

    foreach ($filterIterator as $value) {
        echo $value . "\n";
    }

    // >>> 2
    // >>> 4
    // >>> 6
    // >>> 8
    // >>> 10

MapIterator
-----------

This iterator modifies the values of the inner iterator before yielding.

.. code-block:: php

    use Guzzle\Iterator\MapIterator;

    $inner = new ArrayIterator(range(0, 3));

    $mapIterator = new MapIterator($inner, function ($value) {
        return $value * 10;
    });

    foreach ($mapIterator as $value) {
        echo $value . "\n";
    }

    // >>> 0
    // >>> 10
    // >>> 20
    // >>> 30

MethodProxyIterator
-------------------

This decorator is useful when you need to expose a specific method from an inner iterator that might be wrapper
by one or more iterator decorators. This decorator proxies missing method calls to each inner iterator until one
of the inner iterators can fulfill the call.

.. code-block:: php

    use Guzzle\Iterator\MethodProxyIterator;

    $inner = new \ArrayIterator();
    $proxy = new MethodProxyIterator($inner);

    // Proxy method calls to the ArrayIterator
    $proxy->append('a');
    $proxy->append('b');
Guzzle, PHP HTTP client and webservice framework
================================================

# This is an old version of Guzzle

This repository is for Guzzle 3.x. Guzzle 5.x, the new version of Guzzle, has
been released and is available at
[https://github.com/guzzle/guzzle](https://github.com/guzzle/guzzle). The
documentation for Guzzle version 5+ can be found at
[http://guzzlephp.org](http://guzzlephp.org).

Guzzle 3 is only maintained for bug and security fixes. Guzzle 3 will be EOL
at some point in late 2015.

### About Guzzle 3

[![Composer Downloads](https://poser.pugx.org/guzzle/guzzle/d/total.png)](https://packagist.org/packages/guzzle/guzzle)
 [![Build Status](https://secure.travis-ci.org/guzzle/guzzle3.png?branch=master)](http://travis-ci.org/guzzle/guzzle3)

- Extremely powerful API provides all the power of cURL with a simple interface.
- Truly take advantage of HTTP/1.1 with persistent connections, connection pooling, and parallel requests.
- Service description DSL allows you build awesome web service clients faster.
- Symfony2 event-based plugin system allows you to completely modify the behavior of a request.

Get answers with: [Documentation](http://guzzle3.readthedocs.org/en/latest/), [Forums](https://groups.google.com/forum/?hl=en#!forum/guzzle), IRC ([#guzzlephp](irc://irc.freenode.net/#guzzlephp) @ irc.freenode.net)

### Installing via Composer

The recommended way to install Guzzle is through [Composer](http://getcomposer.org).

```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php

# Add Guzzle as a dependency
php composer.phar require guzzle/guzzle:~3.9
```

After installing, you need to require Composer's autoloader:

```php
require 'vendor/autoload.php';
```
## Known Issues

1. Problem following a specific redirect: https://github.com/guzzle/guzzle/issues/385.
   This has been fixed in Guzzle 4/5.
2. Root XML attributes not serialized in a service description: https://github.com/guzzle/guzzle3/issues/5.
   This has been fixed in Guzzle 4/5.
3. Accept-Encoding not preserved when following redirect: https://github.com/guzzle/guzzle3/issues/9
   Fixed in Guzzle 4/5.
4. String "Array" Transmitted w/ PostFiles and Duplicate Aggregator: https://github.com/guzzle/guzzle3/issues/10
   Fixed in Guzzle 4/5.
5. Recursive model references with array items: https://github.com/guzzle/guzzle3/issues/13
   Fixed in Guzzle 4/5
6. String "Array" Transmitted w/ PostFiles and Duplicate Aggregator: https://github.com/guzzle/guzzle3/issues/10
   Fixed in Guzzle 4/5.
# Ingore common cruft
.DS_STORE
coverage
.idea

# Ignore binary files
guzzle.phar
guzzle-min.phar

# Ignore potentially sensitive phpunit file
phpunit.xml

# Ignore composer generated files
composer.phar
composer.lock
composer-test.lock
vendor/

# Ignore build files
build/
phing/build.properties

# Ignore subsplit working directory
.subsplit

docs/_build
docs/*.pyc
<?php
/**
 * Phing wrapper around git subsplit.
 *
 * @see https://github.com/dflydev/git-subsplit
 * @copyright 2012 Clay Loveless <clay@php.net>
 * @license   http://claylo.mit-license.org/2012/ MIT License
 */

require_once 'phing/tasks/ext/git/GitBaseTask.php';

// base - base of tree to split out
// subIndicatorFile - composer.json, package.xml?
class GuzzleSubSplitTask extends GitBaseTask
{
    /**
     * What git repository to pull from and publish to
     */
    protected $remote = null;

    /**
     * Publish for comma-separated heads instead of all heads
     */
    protected $heads = null;

    /**
     * Publish for comma-separated tags instead of all tags
     */
    protected $tags = null;

    /**
     * Base of the tree RELATIVE TO .subsplit working dir
     */
    protected $base = null;

    /**
     * The presence of this file will indicate that the directory it resides
     * in is at the top level of a split.
     */
    protected $subIndicatorFile = 'composer.json';

    /**
     * Do everything except actually send the update.
     */
    protected $dryRun = null;

    /**
     * Do not sync any heads.
     */
    protected $noHeads = false;

    /**
     * Do not sync any tags.
     */
    protected $noTags = false;

    /**
     * The splits we found in the heads
     */
    protected $splits;

    public function setRemote($str)
    {
        $this->remote = $str;
    }

    public function getRemote()
    {
        return $this->remote;
    }

    public function setHeads($str)
    {
        $this->heads = explode(',', $str);
    }

    public function getHeads()
    {
        return $this->heads;
    }

    public function setTags($str)
    {
        $this->tags = explode(',', $str);
    }

    public function getTags()
    {
        return $this->tags;
    }

    public function setBase($str)
    {
        $this->base = $str;
    }

    public function getBase()
    {
        return $this->base;
    }

    public function setSubIndicatorFile($str)
    {
        $this->subIndicatorFile = $str;
    }

    public function getSubIndicatorFile()
    {
        return $this->subIndicatorFile;
    }

    public function setDryRun($bool)
    {
        $this->dryRun = (bool) $bool;
    }

    public function getDryRun()
    {
        return $this->dryRun;
    }

    public function setNoHeads($bool)
    {
        $this->noHeads = (bool) $bool;
    }

    public function getNoHeads()
    {
        return $this->noHeads;
    }

    public function setNoTags($bool)
    {
        $this->noTags = (bool) $bool;
    }

    public function getNoTags()
    {
        return $this->noTags;
    }

    /**
     * GitClient from VersionControl_Git
     */
    protected $client   = null;

    /**
     * The main entry point
     */
    public function main()
    {
        $repo = $this->getRepository();
        if (empty($repo)) {
            throw new BuildException('"repository" is a required parameter');
        }

        $remote = $this->getRemote();
        if (empty($remote)) {
            throw new BuildException('"remote" is a required parameter');
        }

        chdir($repo);
        $this->client = $this->getGitClient(false, $repo);

        // initalized yet?
        if (!is_dir('.subsplit')) {
            $this->subsplitInit();
        } else {
            // update
            $this->subsplitUpdate();
        }

        // find all splits based on heads requested
        $this->findSplits();

        // check that GitHub has the repos
        $this->verifyRepos();

        // execute the subsplits
        $this->publish();
    }

    public function publish()
    {
        $this->log('DRY RUN ONLY FOR NOW');
        $base = $this->getBase();
        $base = rtrim($base, '/') . '/';
        $org = $this->getOwningTarget()->getProject()->getProperty('github.org');

        $splits = array();

        $heads = $this->getHeads();
        foreach ($heads as $head) {
            foreach ($this->splits[$head] as $component => $meta) {
                $splits[] = $base . $component . ':git@github.com:'. $org.'/'.$meta['repo'];
            }

            $cmd = 'git subsplit publish ';
            $cmd .= escapeshellarg(implode(' ', $splits));

            if ($this->getNoHeads()) {
                $cmd .= ' --no-heads';
            } else {
                $cmd .= ' --heads='.$head;
            }

            if ($this->getNoTags()) {
                $cmd .= ' --no-tags';
            } else {
                if ($this->getTags()) {
                    $cmd .= ' --tags=' . escapeshellarg(implode(' ', $this->getTags()));
                }
            }

            passthru($cmd);
        }
    }

    /**
     * Runs `git subsplit update`
     */
    public function subsplitUpdate()
    {
        $repo = $this->getRepository();
        $this->log('git-subsplit update...');
        $cmd = $this->client->getCommand('subsplit');
        $cmd->addArgument('update');
        try {
            $cmd->execute();
        } catch (Exception $e) {
            throw new BuildException('git subsplit update failed'. $e);
        }
        chdir($repo . '/.subsplit');
        passthru('php ../composer.phar update --dev');
        chdir($repo);
    }

    /**
     * Runs `git subsplit init` based on the remote repository.
     */
    public function subsplitInit()
    {
        $remote = $this->getRemote();
        $cmd = $this->client->getCommand('subsplit');
        $this->log('running git-subsplit init ' . $remote);

        $cmd->setArguments(array(
            'init',
            $remote
        ));

        try {
            $output = $cmd->execute();
        } catch (Exception $e) {
            throw new BuildException('git subsplit init failed'. $e);
        }
        $this->log(trim($output), Project::MSG_INFO);
        $repo = $this->getRepository();
        chdir($repo . '/.subsplit');
        passthru('php ../composer.phar install --dev');
        chdir($repo);
    }

    /**
     * Find the composer.json files using Phing's directory scanner
     *
     * @return array
     */
    protected function findSplits()
    {
        $this->log("checking heads for subsplits");
        $repo = $this->getRepository();
        $base = $this->getBase();

        $splits = array();
        $heads = $this->getHeads();

        if (!empty($base)) {
            $base = '/' . ltrim($base, '/');
        } else {
            $base = '/';
        }

        chdir($repo . '/.subsplit');
        foreach ($heads as $head) {
            $splits[$head] = array();

            // check each head requested *BEFORE* the actual subtree split command gets it
            passthru("git checkout '$head'");
            $ds = new DirectoryScanner();
            $ds->setBasedir($repo . '/.subsplit' . $base);
            $ds->setIncludes(array('**/'.$this->subIndicatorFile));
            $ds->scan();
            $files = $ds->getIncludedFiles();

            // Process the files we found
            foreach ($files as $file) {
                $pkg = file_get_contents($repo . '/.subsplit' . $base .'/'. $file);
                $pkg_json = json_decode($pkg, true);
                $name = $pkg_json['name'];
                $component = str_replace('/composer.json', '', $file);
                // keep this for split cmd
                $tmpreponame = explode('/', $name);
                $reponame = $tmpreponame[1];
                $splits[$head][$component]['repo'] = $reponame;
                $nscomponent = str_replace('/', '\\', $component);
                $splits[$head][$component]['desc'] = "[READ ONLY] Subtree split of $nscomponent: " . $pkg_json['description'];
            }
        }

        // go back to how we found it
        passthru("git checkout master");
        chdir($repo);
        $this->splits = $splits;
    }

    /**
     * Based on list of repositories we determined we *should* have, talk
     * to GitHub and make sure they're all there.
     *
     */
    protected function verifyRepos()
    {
        $this->log('verifying GitHub target repos');
        $github_org = $this->getOwningTarget()->getProject()->getProperty('github.org');
        $github_creds = $this->getOwningTarget()->getProject()->getProperty('github.basicauth');

        if ($github_creds == 'username:password') {
            $this->log('Skipping GitHub repo checks. Update github.basicauth in build.properties to verify repos.', 1);
            return;
        }

        $ch = curl_init('https://api.github.com/orgs/'.$github_org.'/repos?type=all');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERPWD, $github_creds);
        // change this when we know we can use our bundled CA bundle!
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $repos = json_decode($result, true);
        $existing_repos = array();

        // parse out the repos we found on GitHub
        foreach ($repos as $repo) {
            $tmpreponame = explode('/', $repo['full_name']);
            $reponame = $tmpreponame[1];
            $existing_repos[$reponame] = $repo['description'];
        }

        $heads = $this->getHeads();
        foreach ($heads as $head) {
            foreach ($this->splits[$head] as $component => $meta) {

                $reponame = $meta['repo'];

                if (!isset($existing_repos[$reponame])) {
                    $this->log("Creating missing repo $reponame");
                    $payload = array(
                        'name' => $reponame,
                        'description' => $meta['desc'],
                        'homepage' => 'http://www.guzzlephp.org/',
                        'private' => true,
                        'has_issues' => false,
                        'has_wiki' => false,
                        'has_downloads' => true,
                        'auto_init' => false
                    );
                    $ch = curl_init('https://api.github.com/orgs/'.$github_org.'/repos');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_USERPWD, $github_creds);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
                    // change this when we know we can use our bundled CA bundle!
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    $result = curl_exec($ch);
                    echo "Response code: ".curl_getinfo($ch, CURLINFO_HTTP_CODE)."\n";
                    curl_close($ch);
                } else {
                    $this->log("Repo $reponame exists", 2);
                }
            }
        }
    }
}
<?php
/**
 * This file is part of Guzzle's build process.
 *
 * @copyright 2012 Clay Loveless <clay@php.net>
 * @license   http://claylo.mit-license.org/2012/ MIT License
 */

require_once 'phing/Task.php';
require_once 'PEAR/PackageFileManager2.php';
require_once 'PEAR/PackageFileManager/File.php';
require_once 'PEAR/Packager.php';

class GuzzlePearPharPackageTask extends Task
{
    private $version;
    private $deploy = true;
    private $makephar = true;

    private $subpackages = array();

    public function setVersion($str)
    {
        $this->version = $str;
    }

    public function getVersion()
    {
        return $this->version;
    }

    public function setDeploy($deploy)
    {
        $this->deploy = (bool) $deploy;
    }

    public function getDeploy()
    {
        return $this->deploy;
    }

    public function setMakephar($makephar)
    {
        $this->makephar = (bool) $makephar;
    }

    public function getMakephar()
    {
        return $this->makephar;
    }

    private $basedir;
    private $guzzleinfo;
    private $changelog_release_date;
    private $changelog_notes = '-';

    public function main()
    {
        $this->basedir = $this->getProject()->getBasedir();

        if (!is_dir((string) $this->basedir.'/.subsplit')) {
            throw new BuildException('PEAR packaging requires .subsplit directory');
        }

        // main composer file
        $composer_file = file_get_contents((string) $this->basedir.'/.subsplit/composer.json');
        $this->guzzleinfo = json_decode($composer_file, true);

        // make sure we have a target
        $pearwork = (string) $this->basedir . '/build/pearwork';
        if (!is_dir($pearwork)) {
            mkdir($pearwork, 0777, true);
        }
        $pearlogs = (string) $this->basedir . '/build/artifacts/logs';
        if (!is_dir($pearlogs)) {
            mkdir($pearlogs, 0777, true);
        }

        $version = $this->getVersion();
        $this->grabChangelog();
        if ($version[0] == '2') {
            $this->log('building single PEAR package');
            $this->buildSinglePackage();
        } else {
            // $this->log("building PEAR subpackages");
            // $this->createSubPackages();
            // $this->log("building PEAR bundle package");
            $this->buildSinglePackage();
        }

        if ($this->getMakephar()) {
            $this->log("building PHAR");
            $this->getProject()->executeTarget('package-phar');
        }

        if ($this->getDeploy()) {
            $this->doDeployment();
        }
    }

    public function doDeployment()
    {
        $basedir = (string) $this->basedir;
        $this->log('beginning PEAR/PHAR deployment');

        chdir($basedir . '/build/pearwork');
        if (!is_dir('./channel')) {
            mkdir('./channel');
        }

        // Pull the PEAR channel down locally
        passthru('aws s3 sync s3://pear.guzzlephp.org ./channel');

        // add PEAR packages
        foreach (scandir('./') as $file) {
            if (substr($file, -4) == '.tgz') {
                passthru('pirum add ./channel ' . $file);
            }
        }

        // if we have a new phar, add it
        if ($this->getMakephar() && file_exists($basedir . '/build/artifacts/guzzle.phar')) {
            rename($basedir . '/build/artifacts/guzzle.phar', './channel/guzzle.phar');
        }

        // Sync up with the S3 bucket
        chdir($basedir . '/build/pearwork/channel');
        passthru('aws s3 sync . s3://pear.guzzlephp.org');
    }

    public function buildSinglePackage()
    {
        $v = $this->getVersion();
        $apiversion = $v[0] . '.0.0';

        $opts = array(
            'packagedirectory' => (string) $this->basedir . '/.subsplit/src/',
            'filelistgenerator' => 'file',
            'ignore' => array('*composer.json'),
            'baseinstalldir' => '/',
            'packagefile' => 'package.xml'
            //'outputdirectory' => (string) $this->basedir . '/build/pearwork/'
        );
        $pfm = new PEAR_PackageFileManager2();
        $pfm->setOptions($opts);
        $pfm->addRole('md', 'doc');
        $pfm->addRole('pem', 'php');
        $pfm->setPackage('Guzzle');
        $pfm->setSummary("Object-oriented PHP HTTP Client for PHP 5.3+");
        $pfm->setDescription($this->guzzleinfo['description']);
        $pfm->setPackageType('php');
        $pfm->setChannel('guzzlephp.org/pear');
        $pfm->setAPIVersion($apiversion);
        $pfm->setReleaseVersion($this->getVersion());
        $pfm->setAPIStability('stable');
        $pfm->setReleaseStability('stable');
        $pfm->setNotes($this->changelog_notes);
        $pfm->setPackageType('php');
        $pfm->setLicense('MIT', 'http://github.com/guzzle/guzzle/blob/master/LICENSE');
        $pfm->addMaintainer('lead', 'mtdowling', 'Michael Dowling', 'mtdowling@gmail.com', 'yes');
        $pfm->setDate($this->changelog_release_date);
        $pfm->generateContents();

        $phpdep = $this->guzzleinfo['require']['php'];
        $phpdep = str_replace('>=', '', $phpdep);
        $pfm->setPhpDep($phpdep);
        $pfm->addExtensionDep('required', 'curl');
        $pfm->setPearinstallerDep('1.4.6');
        $pfm->addPackageDepWithChannel('required', 'EventDispatcher', 'pear.symfony.com', '2.1.0');
        if (!empty($this->subpackages)) {
            foreach ($this->subpackages as $package) {
                $pkg = dirname($package);
                $pkg = str_replace('/', '_', $pkg);
                $pfm->addConflictingPackageDepWithChannel($pkg, 'guzzlephp.org/pear', false, $apiversion);
            }
        }

        ob_start();
        $startdir = getcwd();
        chdir((string) $this->basedir . '/build/pearwork');

        echo "DEBUGGING GENERATED PACKAGE FILE\n";
        $result = $pfm->debugPackageFile();
        if ($result) {
            $out = $pfm->writePackageFile();
            echo "\n\n\nWRITE PACKAGE FILE RESULT:\n";
            var_dump($out);
            // load up package file and build package
            $packager = new PEAR_Packager();
            echo "\n\n\nBUILDING PACKAGE FROM PACKAGE FILE:\n";
            $dest_package = $packager->package($opts['packagedirectory'].'package.xml');
            var_dump($dest_package);
        } else {
            echo "\n\n\nDEBUGGING RESULT:\n";
            var_dump($result);
        }
        echo "removing package.xml";
        unlink($opts['packagedirectory'].'package.xml');
        $log = ob_get_clean();
        file_put_contents((string) $this->basedir . '/build/artifacts/logs/pear_package.log', $log);
        chdir($startdir);
    }

    public function createSubPackages()
    {
        $this->findComponents();

        foreach ($this->subpackages as $package) {
            $baseinstalldir = dirname($package);
            $dir = (string) $this->basedir.'/.subsplit/src/' . $baseinstalldir;
            $composer_file = file_get_contents((string) $this->basedir.'/.subsplit/src/'. $package);
            $package_info = json_decode($composer_file, true);
            $this->log('building ' . $package_info['target-dir'] . ' subpackage');
            $this->buildSubPackage($dir, $baseinstalldir, $package_info);
        }
    }

    public function buildSubPackage($dir, $baseinstalldir, $info)
    {
        $package = str_replace('/', '_', $baseinstalldir);
        $opts = array(
            'packagedirectory' => $dir,
            'filelistgenerator' => 'file',
            'ignore' => array('*composer.json', '*package.xml'),
            'baseinstalldir' => '/' . $info['target-dir'],
            'packagefile' => 'package.xml'
        );
        $pfm = new PEAR_PackageFileManager2();
        $pfm->setOptions($opts);
        $pfm->setPackage($package);
        $pfm->setSummary($info['description']);
        $pfm->setDescription($info['description']);
        $pfm->setPackageType('php');
        $pfm->setChannel('guzzlephp.org/pear');
        $pfm->setAPIVersion('3.0.0');
        $pfm->setReleaseVersion($this->getVersion());
        $pfm->setAPIStability('stable');
        $pfm->setReleaseStability('stable');
        $pfm->setNotes($this->changelog_notes);
        $pfm->setPackageType('php');
        $pfm->setLicense('MIT', 'http://github.com/guzzle/guzzle/blob/master/LICENSE');
        $pfm->addMaintainer('lead', 'mtdowling', 'Michael Dowling', 'mtdowling@gmail.com', 'yes');
        $pfm->setDate($this->changelog_release_date);
        $pfm->generateContents();

        $phpdep = $this->guzzleinfo['require']['php'];
        $phpdep = str_replace('>=', '', $phpdep);
        $pfm->setPhpDep($phpdep);
        $pfm->setPearinstallerDep('1.4.6');

        foreach ($info['require'] as $type => $version) {
            if ($type == 'php') {
                continue;
            }
            if ($type == 'symfony/event-dispatcher') {
                $pfm->addPackageDepWithChannel('required', 'EventDispatcher', 'pear.symfony.com', '2.1.0');
            }
            if ($type == 'ext-curl') {
                $pfm->addExtensionDep('required', 'curl');
            }
            if (substr($type, 0, 6) == 'guzzle') {
                $gdep = str_replace('/', ' ', $type);
                $gdep = ucwords($gdep);
                $gdep = str_replace(' ', '_', $gdep);
                $pfm->addPackageDepWithChannel('required', $gdep, 'guzzlephp.org/pear', $this->getVersion());
            }
        }

        // can't have main Guzzle package AND sub-packages
        $pfm->addConflictingPackageDepWithChannel('Guzzle', 'guzzlephp.org/pear', false, $apiversion);

        ob_start();
        $startdir = getcwd();
        chdir((string) $this->basedir . '/build/pearwork');

        echo "DEBUGGING GENERATED PACKAGE FILE\n";
        $result = $pfm->debugPackageFile();
        if ($result) {
            $out = $pfm->writePackageFile();
            echo "\n\n\nWRITE PACKAGE FILE RESULT:\n";
            var_dump($out);
            // load up package file and build package
            $packager = new PEAR_Packager();
            echo "\n\n\nBUILDING PACKAGE FROM PACKAGE FILE:\n";
            $dest_package = $packager->package($opts['packagedirectory'].'/package.xml');
            var_dump($dest_package);
        } else {
            echo "\n\n\nDEBUGGING RESULT:\n";
            var_dump($result);
        }
        echo "removing package.xml";
        unlink($opts['packagedirectory'].'/package.xml');
        $log = ob_get_clean();
        file_put_contents((string) $this->basedir . '/build/artifacts/logs/pear_package_'.$package.'.log', $log);
        chdir($startdir);
    }

    public function findComponents()
    {
        $ds = new DirectoryScanner();
        $ds->setBasedir((string) $this->basedir.'/.subsplit/src');
        $ds->setIncludes(array('**/composer.json'));
        $ds->scan();
        $files = $ds->getIncludedFiles();
        $this->subpackages = $files;
    }

    public function grabChangelog()
    {
        $cl = file((string) $this->basedir.'/.subsplit/CHANGELOG.md');
        $notes = '';
        $in_version = false;
        $release_date = null;

        foreach ($cl as $line) {
            $line = trim($line);
            if (preg_match('/^\* '.$this->getVersion().' \(([0-9\-]+)\)$/', $line, $matches)) {
                $release_date = $matches[1];
                $in_version = true;
                continue;
            }
            if ($in_version && empty($line) && empty($notes)) {
                continue;
            }
            if ($in_version && ! empty($line)) {
                $notes .= $line."\n";
            }
            if ($in_version && empty($line) && !empty($notes)) {
                $in_version = false;
            }
        }
        $this->changelog_release_date = $release_date;

        if (! empty($notes)) {
            $this->changelog_notes = $notes;
        }
    }
}
<?php
/**
 * Phing task for composer validation.
 *
 * @copyright 2012 Clay Loveless <clay@php.net>
 * @license   http://claylo.mit-license.org/2012/ MIT License
 */

require_once 'phing/Task.php';

class ComposerLintTask extends Task
{
    protected $dir = null;
    protected $file = null;
    protected $passthru = false;
    protected $composer = null;

    /**
     * The setter for the dir
     *
     * @param string $str Directory to crawl recursively for composer files
     */
    public function setDir($str)
    {
        $this->dir = $str;
    }

    /**
     * The setter for the file
     *
     * @param string $str Individual file to validate
     */
    public function setFile($str)
    {
        $this->file = $str;
    }

    /**
     * Whether to use PHP's passthru() function instead of exec()
     *
     * @param boolean $passthru If passthru shall be used
     */
    public function setPassthru($passthru)
    {
        $this->passthru = (bool) $passthru;
    }

    /**
     * Composer to execute. If unset, will attempt composer.phar in project
     * basedir, and if that fails, will attempt global composer
     * installation.
     *
     * @param string $str Individual file to validate
     */
    public function setComposer($str)
    {
        $this->file = $str;
    }

    /**
     * The init method: do init steps
     */
    public function init()
    {
        // nothing needed here
    }

    /**
     * The main entry point
     */
    public function main()
    {
        if ($this->composer === null) {
            $this->findComposer();
        }

        $files = array();
        if (!empty($this->file) && file_exists($this->file)) {
            $files[] = $this->file;
        }

        if (!empty($this->dir)) {
            $found = $this->findFiles();
            foreach ($found as $file) {
                $files[] = $this->dir . DIRECTORY_SEPARATOR . $file;
            }
        }

        foreach ($files as $file) {

            $cmd = $this->composer . ' validate ' . $file;
            $cmd = escapeshellcmd($cmd);

            if ($this->passthru) {
                $retval = null;
                passthru($cmd, $retval);
                if ($retval == 1) {
                    throw new BuildException('invalid composer.json');
                }
            } else {
                $out = array();
                $retval = null;
                exec($cmd, $out, $retval);
                if ($retval == 1) {
                    $err = join("\n", $out);
                    throw new BuildException($err);
                } else {
                    $this->log($out[0]);
                }
            }

        }

    }

    /**
     * Find the composer.json files using Phing's directory scanner
     *
     * @return array
     */
    protected function findFiles()
    {
        $ds = new DirectoryScanner();
        $ds->setBasedir($this->dir);
        $ds->setIncludes(array('**/composer.json'));
        $ds->scan();
        return $ds->getIncludedFiles();
    }

    /**
     * Find composer installation
     *
     */
    protected function findComposer()
    {
        $basedir = $this->project->getBasedir();
        $php = $this->project->getProperty('php.interpreter');

        if (file_exists($basedir . '/composer.phar')) {
            $this->composer = "$php $basedir/composer.phar";
        } else {
            $out = array();
            exec('which composer', $out);
            if (empty($out)) {
                throw new BuildException(
                    'Could not determine composer location.'
                );
            }
            $this->composer = $out[0];
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="../../" default="deploy">

    <property name="git.status" value=""/>
    <property name="git.currentbranch" value=""/>
    <target name="check-git-branch-status">
        <exec command="git status -s -b" outputProperty="git.currentbranch" />
        <echo msg="${git.currentbranch}"/>
        <if>
            <contains string="${git.currentbranch}" substring="${head}"/>
            <then>
                <echo>On branch ${head}</echo>
            </then>
            <else>
                <fail message="-Dhead=${head} arg did not match ${git.currentbranch}"/>
            </else>
        </if>
        <exec command="git status -s" outputProperty="git.status" />
        <if>
            <equals arg1="${git.status}" arg2="" trim="true"/>
            <then>
                <echo>working directory clean</echo>
            </then>
            <else>
                <echo>${git.status}</echo>
                <fail message="Working directory isn't clean." />
            </else>
        </if>
    </target>

    <property name="version.changelog" value=""/>
    <property name="version.version" value=""/>
    <target name="check-changelog-version">
        <exec executable="fgrep" outputProperty="version.changelog">
            <arg value="${new.version} ("/>
            <arg value="${project.basedir}/CHANGELOG.md"/>
        </exec>
        <if>
            <equals arg1="${version.changelog}" arg2="" trim="true"/>
            <then>
                <fail message="${new.version} not mentioned in CHANGELOG"/>
            </then>
        </if>

        <exec executable="fgrep" outputProperty="version.version">
            <arg value="const VERSION = '${new.version}'"/>
            <arg value="${project.basedir}/src/Guzzle/Common/Version.php"/>
        </exec>
        <if>
            <equals arg1="${version.version}" arg2="" trim="true"/>
            <then>
                <fail message="${new.version} not mentioned in Guzzle\Common\Version"/>
            </then>
        </if>

        <echo>ChangeLog Match: ${version.changelog}</echo>
        <echo>Guzzle\Common\Version Match: ${version.version}</echo>
    </target>

    <target name="help" description="HELP AND REMINDERS about what you can do with this project">
        <echo>releasing: phing -Dnew.version=3.0.x -Dhead=master release</echo>
        <echo>--</echo>
        <exec command="phing -l" passthru="true"/>
    </target>

    <target name="release" depends="check-changelog-version,check-git-branch-status"
            description="tag, subtree split, package, deploy: Use: phing -Dnew.version=[TAG] -Dhead=[BRANCH] release">
        <if>
            <isset property="new.version" />
            <then>
                <if>
                    <contains string="${new.version}" substring="v" casesensitive="false" />
                    <then>
                        <fail message="Please specify version as [0-9].[0-9].[0-9]. (I'll add v for you.)"/>
                    </then>
                    <else>

                        <echo>BEGINNING RELEASE FOR ${new.version}</echo>

                        <!-- checkout the specified branch -->
                        <!-- <gitcheckout repository="${repo.dir}" branchname="${head}" gitPath="${cmd.git}" /> -->
                        <!-- Ensure that the tag exists -->
                        <!-- push the tag up so subsplit will get it -->
                        <!--gitpush repository="${repo.dir}" tags="true" gitPath="${cmd.git}" /-->

                        <!-- now do the subsplits -->
                        <guzzlesubsplit
                                repository="${repo.dir}"
                                remote="${guzzle.remote}"
                                heads="${head}"
                                tags="v${new.version}"
                                base="src"
                                subIndicatorFile="composer.json"
                                gitPath="${cmd.git}" />

                        <!-- Copy .md files into the PEAR package -->
                        <copy file="${repo.dir}/LICENSE" tofile=".subsplit/src/Guzzle/LICENSE.md" />
                        <copy file="${repo.dir}/README.md" tofile=".subsplit/src/Guzzle/README.md" />
                        <copy file="${repo.dir}/CHANGELOG.md" tofile=".subsplit/src/Guzzle/CHANGELOG.md" />

                        <!-- and now the pear packages -->
                        <guzzlepear
                                version="${new.version}"
                                makephar="true"
                                />
                    </else>

                </if>
            </then>

            <else>
                <echo>Tip: to create a new release, do: phing -Dnew.version=[TAG] -Dhead=[BRANCH] release</echo>
            </else>

        </if>
    </target>

    <target name="pear-channel">
        <guzzlepear version="${new.version}" deploy="true" makephar="true" />
    </target>

    <target name="package-phar" description="Create a phar with an autoloader">
        <pharpackage
                destfile="${dir.output}/guzzle.phar"
                basedir="${project.basedir}/.subsplit"
                stub="phar-stub.php"
                signature="md5">
            <fileset dir="${project.basedir}/.subsplit">
                <include name="src/**/*.php" />
                <include name="src/**/*.pem" />
                <include name="vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php" />
                <include name="vendor/symfony/event-dispatcher/**/*.php" />
                <include name="vendor/doctrine/common/lib/Doctrine/Common/Cache/*.php" />
                <include name="vendor/monolog/monolog/src/**/*.php" />
            </fileset>
            <metadata>
                <element name="author" value="Michael Dowling" />
            </metadata>
        </pharpackage>
    </target>

</project>
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="../../" default="install-dependencies">

    <property name="cmd.composer" value="" />
    <property name="cmd.git" value="" />
    <property name="cmd.testserver" value="" />

    <!--
    Our custom tasks
    -->
    <taskdef name="composerlint" classname="phing.tasks.ComposerLintTask" />
    <taskdef name="guzzlesubsplit" classname="phing.tasks.GuzzleSubSplitTask" />
    <taskdef name="guzzlepear" classname="phing.tasks.GuzzlePearPharPackageTask" />

    <target name="find-git">
        <if>
            <contains string="${cmd.git}" substring="git" />
            <then>
                <echo>using git at ${cmd.git}</echo>
            </then>
        <else>
            <exec command="which git" outputProperty="cmd.git" />
            <echo>found git at ${cmd.git}</echo>
        </else>
        </if>
    </target>

    <target name="clean-dependencies">
        <delete dir="${project.basedir}/vendor"/>
        <delete file="${project.basedir}/composer.lock" />
    </target>

</project>
# you may need to update this if you're working on a fork.
guzzle.remote=git@github.com:guzzle/guzzle.git

# github credentials -- only used by GitHub API calls to create subtree repos
github.basicauth=username:password
# for the subtree split and testing
github.org=guzzle

# your git path
cmd.git=git

# your composer command
cmd.composer=composer

# test server start
cmd.testserver=node
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./tests/bootstrap.php"
         colors="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader">

    <testsuites>
        <testsuite>
            <directory>./tests/Guzzle/Tests</directory>
        </testsuite>
    </testsuites>

    <logging>
        <log type="junit" target="build/artifacts/logs/junit.xml" logIncompleteSkipped="false" />
    </logging>

    <filter>
        <whitelist>
            <directory suffix=".php">./src/Guzzle</directory>
            <exclude>
                <directory suffix="Interface.php">./src/Guzzle</directory>
                <file>./src/Guzzle/Common/Exception/GuzzleException.php</file>
                <file>./src/Guzzle/Http/Exception/HttpException.php</file>
                <file>./src/Guzzle/Http/Exception/ServerErrorResponseException.php</file>
                <file>./src/Guzzle/Http/Exception/ClientErrorResponseException.php</file>
                <file>./src/Guzzle/Http/Exception/TooManyRedirectsException.php</file>
                <file>./src/Guzzle/Http/Exception/CouldNotRewindStreamException.php</file>
                <file>./src/Guzzle/Common/Exception/BadMethodCallException.php</file>
                <file>./src/Guzzle/Common/Exception/InvalidArgumentException.php</file>
                <file>./src/Guzzle/Common/Exception/RuntimeException.php</file>
                <file>./src/Guzzle/Common/Exception/UnexpectedValueException.php</file>
                <file>./src/Guzzle/Service/Exception/ClientNotFoundException.php</file>
                <file>./src/Guzzle/Service/Exception/CommandException.php</file>
                <file>./src/Guzzle/Service/Exception/DescriptionBuilderException.php</file>
                <file>./src/Guzzle/Service/Exception/ServiceBuilderException.php</file>
                <file>./src/Guzzle/Service/Exception/ServiceNotFoundException.php</file>
                <file>./src/Guzzle/Service/Exception/ValidationException.php</file>
                <file>./src/Guzzle/Service/Exception/JsonException.php</file>
            </exclude>
        </whitelist>
    </filter>

</phpunit>
Guzzle Upgrade Guide
====================

3.6 to 3.7
----------

### Deprecations

- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.:

```php
\Guzzle\Common\Version::$emitWarnings = true;
```

The following APIs and options have been marked as deprecated:

- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead.
- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead.
- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead.
- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated
- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client.
- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8.
- Marked `Guzzle\Common\Collection::inject()` as deprecated.
- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use
  `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or
  `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));`

3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational
request methods. When paired with a client's configuration settings, these options allow you to specify default settings
for various aspects of a request. Because these options make other previous configuration options redundant, several
configuration options and methods of a client and AbstractCommand have been deprecated.

- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`.
- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`.
- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')`
- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0

        $command = $client->getCommand('foo', array(
            'command.headers' => array('Test' => '123'),
            'command.response_body' => '/path/to/file'
        ));

        // Should be changed to:

        $command = $client->getCommand('foo', array(
            'command.request_options' => array(
                'headers' => array('Test' => '123'),
                'save_as' => '/path/to/file'
            )
        ));

### Interface changes

Additions and changes (you will need to update any implementations or subclasses you may have created):

- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`:
  createRequest, head, delete, put, patch, post, options, prepareRequest
- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()`
- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface`
- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to
  `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a
  resource, string, or EntityBody into the $options parameter to specify the download location of the response.
- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a
  default `array()`
- Added `Guzzle\Stream\StreamInterface::isRepeatable`
- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods.

The following methods were removed from interfaces. All of these methods are still available in the concrete classes
that implement them, but you should update your code to use alternative methods:

- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use
  `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or
  `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or
  `$client->setDefaultOption('headers/{header_name}', 'value')`. or
  `$client->setDefaultOption('headers', array('header_name' => 'value'))`.
- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`.
- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail.
- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail.
- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail.
- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin.
- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin.
- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin.

### Cache plugin breaking changes

- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a
  CacheStorageInterface. These two objects and interface will be removed in a future version.
- Always setting X-cache headers on cached responses
- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin
- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface
  $request, Response $response);`
- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);`
- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);`
- Added `CacheStorageInterface::purge($url)`
- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin
  $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache,
  CanCacheStrategyInterface $canCache = null)`
- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)`

3.5 to 3.6
----------

* Mixed casing of headers are now forced to be a single consistent casing across all values for that header.
* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution
* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader().
  For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader().
  Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request.
* Specific header implementations can be created for complex headers. When a message creates a header, it uses a
  HeaderFactory which can map specific headers to specific header classes. There is now a Link header and
  CacheControl header implementation.
* Moved getLinks() from Response to just be used on a Link header object.

If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the
HeaderInterface (e.g. toArray(), getAll(), etc).

### Interface changes

* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate
* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti()
* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in
  Guzzle\Http\Curl\RequestMediator
* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string.
* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface
* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders()

### Removed deprecated functions

* Removed Guzzle\Parser\ParserRegister::get(). Use getParser()
* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser().

### Deprecations

* The ability to case-insensitively search for header values
* Guzzle\Http\Message\Header::hasExactHeader
* Guzzle\Http\Message\Header::raw. Use getAll()
* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object
  instead.

### Other changes

* All response header helper functions return a string rather than mixing Header objects and strings inconsistently
* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc are managed by Guzzle
  directly via interfaces
* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist
  but are a no-op until removed.
* Most classes that used to require a ``Guzzle\Service\Command\CommandInterface` typehint now request a
  `Guzzle\Service\Command\ArrayCommandInterface`.
* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response
  on a request while the request is still being transferred
* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess

3.3 to 3.4
----------

Base URLs of a client now follow the rules of http://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs.

3.2 to 3.3
----------

### Response::getEtag() quote stripping removed

`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header

### Removed `Guzzle\Http\Utils`

The `Guzzle\Http\Utils` class was removed. This class was only used for testing.

### Stream wrapper and type

`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to lowercase.

### curl.emit_io became emit_io

Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the
'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io'

3.1 to 3.2
----------

### CurlMulti is no longer reused globally

Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added
to a single client can pollute requests dispatched from other clients.

If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the
ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is
created.

```php
$multi = new Guzzle\Http\Curl\CurlMulti();
$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json');
$builder->addListener('service_builder.create_client', function ($event) use ($multi) {
    $event['client']->setCurlMulti($multi);
}
});
```

### No default path

URLs no longer have a default path value of '/' if no path was specified.

Before:

```php
$request = $client->get('http://www.foo.com');
echo $request->getUrl();
// >> http://www.foo.com/
```

After:

```php
$request = $client->get('http://www.foo.com');
echo $request->getUrl();
// >> http://www.foo.com
```

### Less verbose BadResponseException

The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and
response information. You can, however, get access to the request and response object by calling `getRequest()` or
`getResponse()` on the exception object.

### Query parameter aggregation

Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a
setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is
responsible for handling the aggregation of multi-valued query string variables into a flattened hash.

2.8 to 3.x
----------

### Guzzle\Service\Inspector

Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig`

**Before**

```php
use Guzzle\Service\Inspector;

class YourClient extends \Guzzle\Service\Client
{
    public static function factory($config = array())
    {
        $default = array();
        $required = array('base_url', 'username', 'api_key');
        $config = Inspector::fromConfig($config, $default, $required);

        $client = new self(
            $config->get('base_url'),
            $config->get('username'),
            $config->get('api_key')
        );
        $client->setConfig($config);

        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }
```

**After**

```php
use Guzzle\Common\Collection;

class YourClient extends \Guzzle\Service\Client
{
    public static function factory($config = array())
    {
        $default = array();
        $required = array('base_url', 'username', 'api_key');
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self(
            $config->get('base_url'),
            $config->get('username'),
            $config->get('api_key')
        );
        $client->setConfig($config);

        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }
```

### Convert XML Service Descriptions to JSON

**Before**

```xml
<?xml version="1.0" encoding="UTF-8"?>
<client>
    <commands>
        <!-- Groups -->
        <command name="list_groups" method="GET" uri="groups.json">
            <doc>Get a list of groups</doc>
        </command>
        <command name="search_groups" method="GET" uri='search.json?query="{{query}} type:group"'>
            <doc>Uses a search query to get a list of groups</doc>
            <param name="query" type="string" required="true" />
        </command>
        <command name="create_group" method="POST" uri="groups.json">
            <doc>Create a group</doc>
            <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
            <param name="Content-Type" location="header" static="application/json"/>
        </command>
        <command name="delete_group" method="DELETE" uri="groups/{{id}}.json">
            <doc>Delete a group by ID</doc>
            <param name="id" type="integer" required="true"/>
        </command>
        <command name="get_group" method="GET" uri="groups/{{id}}.json">
            <param name="id" type="integer" required="true"/>
        </command>
        <command name="update_group" method="PUT" uri="groups/{{id}}.json">
            <doc>Update a group</doc>
            <param name="id" type="integer" required="true"/>
            <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
            <param name="Content-Type" location="header" static="application/json"/>
        </command>
    </commands>
</client>
```

**After**

```json
{
    "name":       "Zendesk REST API v2",
    "apiVersion": "2012-12-31",
    "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users",
    "operations": {
        "list_groups":  {
            "httpMethod":"GET",
            "uri":       "groups.json",
            "summary":   "Get a list of groups"
        },
        "search_groups":{
            "httpMethod":"GET",
            "uri":       "search.json?query=\"{query} type:group\"",
            "summary":   "Uses a search query to get a list of groups",
            "parameters":{
                "query":{
                    "location":   "uri",
                    "description":"Zendesk Search Query",
                    "type":       "string",
                    "required":   true
                }
            }
        },
        "create_group": {
            "httpMethod":"POST",
            "uri":       "groups.json",
            "summary":   "Create a group",
            "parameters":{
                "data":        {
                    "type":       "array",
                    "location":   "body",
                    "description":"Group JSON",
                    "filters":    "json_encode",
                    "required":   true
                },
                "Content-Type":{
                    "type":    "string",
                    "location":"header",
                    "static":  "application/json"
                }
            }
        },
        "delete_group": {
            "httpMethod":"DELETE",
            "uri":       "groups/{id}.json",
            "summary":   "Delete a group",
            "parameters":{
                "id":{
                    "location":   "uri",
                    "description":"Group to delete by ID",
                    "type":       "integer",
                    "required":   true
                }
            }
        },
        "get_group":    {
            "httpMethod":"GET",
            "uri":       "groups/{id}.json",
            "summary":   "Get a ticket",
            "parameters":{
                "id":{
                    "location":   "uri",
                    "description":"Group to get by ID",
                    "type":       "integer",
                    "required":   true
                }
            }
        },
        "update_group": {
            "httpMethod":"PUT",
            "uri":       "groups/{id}.json",
            "summary":   "Update a group",
            "parameters":{
                "id":          {
                    "location":   "uri",
                    "description":"Group to update by ID",
                    "type":       "integer",
                    "required":   true
                },
                "data":        {
                    "type":       "array",
                    "location":   "body",
                    "description":"Group JSON",
                    "filters":    "json_encode",
                    "required":   true
                },
                "Content-Type":{
                    "type":    "string",
                    "location":"header",
                    "static":  "application/json"
                }
            }
        }
}
```

### Guzzle\Service\Description\ServiceDescription

Commands are now called Operations

**Before**

```php
use Guzzle\Service\Description\ServiceDescription;

$sd = new ServiceDescription();
$sd->getCommands();     // @returns ApiCommandInterface[]
$sd->hasCommand($name);
$sd->getCommand($name); // @returns ApiCommandInterface|null
$sd->addCommand($command); // @param ApiCommandInterface $command
```

**After**

```php
use Guzzle\Service\Description\ServiceDescription;

$sd = new ServiceDescription();
$sd->getOperations();           // @returns OperationInterface[]
$sd->hasOperation($name);
$sd->getOperation($name);       // @returns OperationInterface|null
$sd->addOperation($operation);  // @param OperationInterface $operation
```

### Guzzle\Common\Inflection\Inflector

Namespace is now `Guzzle\Inflection\Inflector`

### Guzzle\Http\Plugin

Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below.

### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log

Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively.

**Before**

```php
use Guzzle\Common\Log\ClosureLogAdapter;
use Guzzle\Http\Plugin\LogPlugin;

/** @var \Guzzle\Http\Client */
$client;

// $verbosity is an integer indicating desired message verbosity level
$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE);
```

**After**

```php
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Log\MessageFormatter;
use Guzzle\Plugin\Log\LogPlugin;

/** @var \Guzzle\Http\Client */
$client;

// $format is a string indicating desired message format -- @see MessageFormatter
$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT);
```

### Guzzle\Http\Plugin\CurlAuthPlugin

Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`.

### Guzzle\Http\Plugin\ExponentialBackoffPlugin

Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes.

**Before**

```php
use Guzzle\Http\Plugin\ExponentialBackoffPlugin;

$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge(
        ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429)
    ));

$client->addSubscriber($backoffPlugin);
```

**After**

```php
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;

// Use convenient factory method instead -- see implementation for ideas of what
// you can do with chaining backoff strategies
$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge(
        HttpBackoffStrategy::getDefaultFailureCodes(), array(429)
    ));
$client->addSubscriber($backoffPlugin);
```

### Known Issues

#### [BUG] Accept-Encoding header behavior changed unintentionally.

(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e)

In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to
properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen.
See issue #217 for a workaround, or use a version containing the fix.
language: php

php:
  - 5.3
  - 5.4
  - 5.5
  - 5.6
  - hhvm

before_script:
  - curl --version
  - pecl install uri_template-beta || echo "pecl uri_template not available"
  - composer self-update
  - composer install --no-interaction --prefer-source --dev
  - ~/.nvm/nvm.sh install v0.6.14

script: composer test
{
    "name": "guzzle/guzzle",
    "type": "library",
    "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle",
    "keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
    "homepage": "http://guzzlephp.org/",
    "license": "MIT",

    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        },
        {
            "name": "Guzzle Community",
            "homepage": "https://github.com/guzzle/guzzle/contributors"
        }
    ],

    "replace": {
        "guzzle/batch": "self.version",
        "guzzle/cache": "self.version",
        "guzzle/common": "self.version",
        "guzzle/http": "self.version",
        "guzzle/inflection": "self.version",
        "guzzle/iterator": "self.version",
        "guzzle/log": "self.version",
        "guzzle/parser": "self.version",
        "guzzle/plugin": "self.version",
        "guzzle/plugin-async": "self.version",
        "guzzle/plugin-backoff": "self.version",
        "guzzle/plugin-cache": "self.version",
        "guzzle/plugin-cookie": "self.version",
        "guzzle/plugin-curlauth": "self.version",
        "guzzle/plugin-error-response": "self.version",
        "guzzle/plugin-history": "self.version",
        "guzzle/plugin-log": "self.version",
        "guzzle/plugin-md5": "self.version",
        "guzzle/plugin-mock": "self.version",
        "guzzle/plugin-oauth": "self.version",
        "guzzle/service": "self.version",
        "guzzle/stream": "self.version"
    },

    "require": {
        "php": ">=5.3.3",
        "ext-curl": "*",
        "symfony/event-dispatcher": "~2.1"
    },

    "autoload": {
        "psr-0": {
            "Guzzle": "src/",
            "Guzzle\\Tests": "tests/"
        }
    },

    "suggest": {
        "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated."
    },

    "scripts": {
        "test": "phpunit"
    },

    "require-dev": {
        "doctrine/cache": "~1.3",
        "symfony/class-loader": "~2.1",
        "monolog/monolog": "~1.0",
        "psr/log": "~1.0",
        "zendframework/zend-cache": "2.*,<2.3",
        "zendframework/zend-log": "2.*,<2.3",
        "phpunit/phpunit": "3.7.*"
    },

    "extra": {
        "branch-alias": {
            "dev-master": "3.9-dev"
        }
    }
}
<?php

namespace Guzzle\Cache;

use Guzzle\Common\Version;

/**
 * Zend Framework 1 cache adapter
 *
 * @link http://framework.zend.com/manual/en/zend.cache.html
 * @deprecated
 * @codeCoverageIgnore
 */
class Zf1CacheAdapter extends AbstractCacheAdapter
{
    /**
     * @param \Zend_Cache_Backend $cache Cache object to wrap
     */
    public function __construct(\Zend_Cache_Backend $cache)
    {
        Version::warn(__CLASS__ . ' is deprecated. Upgrade to ZF2 or use PsrCacheAdapter');
        $this->cache = $cache;
    }

    public function contains($id, array $options = null)
    {
        return $this->cache->test($id);
    }

    public function delete($id, array $options = null)
    {
        return $this->cache->remove($id);
    }

    public function fetch($id, array $options = null)
    {
        return $this->cache->load($id);
    }

    public function save($id, $data, $lifeTime = false, array $options = null)
    {
        return $this->cache->save($data, $id, array(), $lifeTime);
    }
}
<?php

namespace Guzzle\Cache;

/**
 * Cache adapter that defers to closures for implementation
 */
class ClosureCacheAdapter implements CacheAdapterInterface
{
    /**
     * @var array Mapping of method names to callables
     */
    protected $callables;

    /**
     * The callables array is an array mapping the actions of the cache adapter to callables.
     * - contains: Callable that accepts an $id and $options argument
     * - delete:   Callable that accepts an $id and $options argument
     * - fetch:    Callable that accepts an $id and $options argument
     * - save:     Callable that accepts an $id, $data, $lifeTime, and $options argument
     *
     * @param array $callables array of action names to callable
     *
     * @throws \InvalidArgumentException if the callable is not callable
     */
    public function __construct(array $callables)
    {
        // Validate each key to ensure it exists and is callable
        foreach (array('contains', 'delete', 'fetch', 'save') as $key) {
            if (!array_key_exists($key, $callables) || !is_callable($callables[$key])) {
                throw new \InvalidArgumentException("callables must contain a callable {$key} key");
            }
        }

        $this->callables = $callables;
    }

    public function contains($id, array $options = null)
    {
        return call_user_func($this->callables['contains'], $id, $options);
    }

    public function delete($id, array $options = null)
    {
        return call_user_func($this->callables['delete'], $id, $options);
    }

    public function fetch($id, array $options = null)
    {
        return call_user_func($this->callables['fetch'], $id, $options);
    }

    public function save($id, $data, $lifeTime = false, array $options = null)
    {
        return call_user_func($this->callables['save'], $id, $data, $lifeTime, $options);
    }
}
<?php

namespace Guzzle\Cache;

/**
 * Interface for cache adapters.
 *
 * Cache adapters allow Guzzle to utilize various frameworks for caching HTTP responses.
 *
 * @link http://www.doctrine-project.org/ Inspired by Doctrine 2
 */
interface CacheAdapterInterface
{
    /**
     * Test if an entry exists in the cache.
     *
     * @param string $id      cache id The cache id of the entry to check for.
     * @param array  $options Array of cache adapter options
     *
     * @return bool Returns TRUE if a cache entry exists for the given cache id, FALSE otherwise.
     */
    public function contains($id, array $options = null);

    /**
     * Deletes a cache entry.
     *
     * @param string $id      cache id
     * @param array  $options Array of cache adapter options
     *
     * @return bool TRUE on success, FALSE on failure
     */
    public function delete($id, array $options = null);

    /**
     * Fetches an entry from the cache.
     *
     * @param string $id      cache id The id of the cache entry to fetch.
     * @param array  $options Array of cache adapter options
     *
     * @return string The cached data or FALSE, if no cache entry exists for the given id.
     */
    public function fetch($id, array $options = null);

    /**
     * Puts data into the cache.
     *
     * @param string   $id       The cache id
     * @param string   $data     The cache entry/data
     * @param int|bool $lifeTime The lifetime. If != false, sets a specific lifetime for this cache entry
     * @param array    $options  Array of cache adapter options
     *
     * @return bool TRUE if the entry was successfully stored in the cache, FALSE otherwise.
     */
    public function save($id, $data, $lifeTime = false, array $options = null);
}
<?php

namespace Guzzle\Cache;

use Doctrine\Common\Cache\Cache;
use Guzzle\Common\Version;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\FromConfigInterface;
use Zend\Cache\Storage\StorageInterface;

/**
 * Generates cache adapters from any number of known cache implementations
 */
class CacheAdapterFactory implements FromConfigInterface
{
    /**
     * Create a Guzzle cache adapter based on an array of options
     *
     * @param mixed $cache Cache value
     *
     * @return CacheAdapterInterface
     * @throws InvalidArgumentException
     */
    public static function fromCache($cache)
    {
        if (!is_object($cache)) {
            throw new InvalidArgumentException('Cache must be one of the known cache objects');
        }

        if ($cache instanceof CacheAdapterInterface) {
            return $cache;
        } elseif ($cache instanceof Cache) {
            return new DoctrineCacheAdapter($cache);
        } elseif ($cache instanceof StorageInterface) {
            return new Zf2CacheAdapter($cache);
        } else {
            throw new InvalidArgumentException('Unknown cache type: ' . get_class($cache));
        }
    }

    /**
     * Create a Guzzle cache adapter based on an array of options
     *
     * @param array $config Array of configuration options
     *
     * @return CacheAdapterInterface
     * @throws InvalidArgumentException
     * @deprecated This will be removed in a future version
     * @codeCoverageIgnore
     */
    public static function factory($config = array())
    {
        Version::warn(__METHOD__ . ' is deprecated');
        if (!is_array($config)) {
            throw new InvalidArgumentException('$config must be an array');
        }

        if (!isset($config['cache.adapter']) && !isset($config['cache.provider'])) {
            $config['cache.adapter'] = 'Guzzle\Cache\NullCacheAdapter';
            $config['cache.provider'] = null;
        } else {
            // Validate that the options are valid
            foreach (array('cache.adapter', 'cache.provider') as $required) {
                if (!isset($config[$required])) {
                    throw new InvalidArgumentException("{$required} is a required CacheAdapterFactory option");
                }
                if (is_string($config[$required])) {
                    // Convert dot notation to namespaces
                    $config[$required] = str_replace('.', '\\', $config[$required]);
                    if (!class_exists($config[$required])) {
                        throw new InvalidArgumentException("{$config[$required]} is not a valid class for {$required}");
                    }
                }
            }
            // Instantiate the cache provider
            if (is_string($config['cache.provider'])) {
                $args = isset($config['cache.provider.args']) ? $config['cache.provider.args'] : null;
                $config['cache.provider'] = self::createObject($config['cache.provider'], $args);
            }
        }

        // Instantiate the cache adapter using the provider and options
        if (is_string($config['cache.adapter'])) {
            $args = isset($config['cache.adapter.args']) ? $config['cache.adapter.args'] : array();
            array_unshift($args, $config['cache.provider']);
            $config['cache.adapter'] = self::createObject($config['cache.adapter'], $args);
        }

        return $config['cache.adapter'];
    }

    /**
     * Create a class using an array of constructor arguments
     *
     * @param string $className Class name
     * @param array  $args      Arguments for the class constructor
     *
     * @return mixed
     * @throws RuntimeException
     * @deprecated
     * @codeCoverageIgnore
     */
    private static function createObject($className, array $args = null)
    {
        try {
            if (!$args) {
                return new $className;
            } else {
                $c = new \ReflectionClass($className);
                return $c->newInstanceArgs($args);
            }
        } catch (\Exception $e) {
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
        }
    }
}
<?php

namespace Guzzle\Cache;

/**
 * Null cache adapter
 */
class NullCacheAdapter extends AbstractCacheAdapter
{
    public function __construct() {}

    public function contains($id, array $options = null)
    {
        return false;
    }

    public function delete($id, array $options = null)
    {
        return true;
    }

    public function fetch($id, array $options = null)
    {
        return false;
    }

    public function save($id, $data, $lifeTime = false, array $options = null)
    {
        return true;
    }
}
<?php

namespace Guzzle\Cache;

use Zend\Cache\Storage\StorageInterface;

/**
 * Zend Framework 2 cache adapter
 *
 * @link http://packages.zendframework.com/docs/latest/manual/en/zend.cache.html
 */
class Zf2CacheAdapter extends AbstractCacheAdapter
{
    /**
     * @param StorageInterface $cache Zend Framework 2 cache adapter
     */
    public function __construct(StorageInterface $cache)
    {
        $this->cache = $cache;
    }

    public function contains($id, array $options = null)
    {
        return $this->cache->hasItem($id);
    }

    public function delete($id, array $options = null)
    {
        return $this->cache->removeItem($id);
    }

    public function fetch($id, array $options = null)
    {
        return $this->cache->getItem($id);
    }

    public function save($id, $data, $lifeTime = false, array $options = null)
    {
        return $this->cache->setItem($id, $data);
    }
}
<?php

namespace Guzzle\Cache;

use Doctrine\Common\Cache\Cache;

/**
 * Doctrine 2 cache adapter
 *
 * @link http://www.doctrine-project.org/
 */
class DoctrineCacheAdapter extends AbstractCacheAdapter
{
    /**
     * @param Cache $cache Doctrine cache object
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    public function contains($id, array $options = null)
    {
        return $this->cache->contains($id);
    }

    public function delete($id, array $options = null)
    {
        return $this->cache->delete($id);
    }

    public function fetch($id, array $options = null)
    {
        return $this->cache->fetch($id);
    }

    public function save($id, $data, $lifeTime = false, array $options = null)
    {
        return $this->cache->save($id, $data, $lifeTime !== false ? $lifeTime : 0);
    }
}
<?php

namespace Guzzle\Cache;

/**
 * Abstract cache adapter
 */
abstract class AbstractCacheAdapter implements CacheAdapterInterface
{
    protected $cache;

    /**
     * Get the object owned by the adapter
     *
     * @return mixed
     */
    public function getCacheObject()
    {
        return $this->cache;
    }
}
{
    "name": "guzzle/cache",
    "description": "Guzzle cache adapter component",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["cache", "adapter", "zf", "doctrine", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/common": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Cache": "" }
    },
    "target-dir": "Guzzle/Cache",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Stream;

/**
 * OO interface to PHP streams
 */
interface StreamInterface
{
    /**
     * Convert the stream to a string if the stream is readable and the stream is seekable.
     *
     * @return string
     */
    public function __toString();

    /**
     * Close the underlying stream
     */
    public function close();

    /**
     * Get stream metadata
     *
     * @param string $key Specific metadata to retrieve
     *
     * @return array|mixed|null
     */
    public function getMetaData($key = null);

    /**
     * Get the stream resource
     *
     * @return resource
     */
    public function getStream();

    /**
     * Set the stream that is wrapped by the object
     *
     * @param resource $stream Stream resource to wrap
     * @param int      $size   Size of the stream in bytes. Only pass if the size cannot be obtained from the stream.
     *
     * @return self
     */
    public function setStream($stream, $size = null);

    /**
     * Detach the current stream resource
     *
     * @return self
     */
    public function detachStream();

    /**
     * Get the stream wrapper type
     *
     * @return string
     */
    public function getWrapper();

    /**
     * Wrapper specific data attached to this stream.
     *
     * @return array
     */
    public function getWrapperData();

    /**
     * Get a label describing the underlying implementation of the stream
     *
     * @return string
     */
    public function getStreamType();

    /**
     * Get the URI/filename associated with this stream
     *
     * @return string
     */
    public function getUri();

    /**
     * Get the size of the stream if able
     *
     * @return int|bool
     */
    public function getSize();

    /**
     * Check if the stream is readable
     *
     * @return bool
     */
    public function isReadable();

    /**
     * Check if the stream is repeatable
     *
     * @return bool
     */
    public function isRepeatable();

    /**
     * Check if the stream is writable
     *
     * @return bool
     */
    public function isWritable();

    /**
     * Check if the stream has been consumed
     *
     * @return bool
     */
    public function isConsumed();

    /**
     * Alias of isConsumed
     *
     * @return bool
     */
    public function feof();

    /**
     * Check if the stream is a local stream vs a remote stream
     *
     * @return bool
     */
    public function isLocal();

    /**
     * Check if the string is repeatable
     *
     * @return bool
     */
    public function isSeekable();

    /**
     * Specify the size of the stream in bytes
     *
     * @param int $size Size of the stream contents in bytes
     *
     * @return self
     */
    public function setSize($size);

    /**
     * Seek to a position in the stream
     *
     * @param int $offset Stream offset
     * @param int $whence Where the offset is applied
     *
     * @return bool Returns TRUE on success or FALSE on failure
     * @link   http://www.php.net/manual/en/function.fseek.php
     */
    public function seek($offset, $whence = SEEK_SET);

    /**
     * Read data from the stream
     *
     * @param int $length Up to length number of bytes read.
     *
     * @return string|bool Returns the data read from the stream or FALSE on failure or EOF
     */
    public function read($length);

    /**
     * Write data to the stream
     *
     * @param string $string The string that is to be written.
     *
     * @return int|bool Returns the number of bytes written to the stream on success or FALSE on failure.
     */
    public function write($string);

    /**
     * Returns the current position of the file read/write pointer
     *
     * @return int|bool Returns the position of the file pointer or false on error
     */
    public function ftell();

    /**
     * Rewind to the beginning of the stream
     *
     * @return bool Returns true on success or false on failure
     */
    public function rewind();

    /**
     * Read a line from the stream up to the maximum allowed buffer length
     *
     * @param int $maxLength Maximum buffer length
     *
     * @return string|bool
     */
    public function readLine($maxLength = null);

    /**
     * Set custom data on the stream
     *
     * @param string $key   Key to set
     * @param mixed  $value Value to set
     *
     * @return self
     */
    public function setCustomData($key, $value);

    /**
     * Get custom data from the stream
     *
     * @param string $key Key to retrieve
     *
     * @return null|mixed
     */
    public function getCustomData($key);
}
<?php

namespace Guzzle\Stream;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * PHP stream implementation
 */
class Stream implements StreamInterface
{
    const STREAM_TYPE = 'stream_type';
    const WRAPPER_TYPE = 'wrapper_type';
    const IS_LOCAL = 'is_local';
    const IS_READABLE = 'is_readable';
    const IS_WRITABLE = 'is_writable';
    const SEEKABLE = 'seekable';

    /** @var resource Stream resource */
    protected $stream;

    /** @var int Size of the stream contents in bytes */
    protected $size;

    /** @var array Stream cached data */
    protected $cache = array();

    /** @var array Custom stream data */
    protected $customData = array();

    /** @var array Hash table of readable and writeable stream types for fast lookups */
    protected static $readWriteHash = array(
        'read' => array(
            'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
            'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true,
            'rt' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a+' => true
        ),
        'write' => array(
            'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, 'c+' => true,
            'wb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true,
            'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true
        )
    );

    /**
     * @param resource $stream Stream resource to wrap
     * @param int      $size   Size of the stream in bytes. Only pass if the size cannot be obtained from the stream.
     *
     * @throws InvalidArgumentException if the stream is not a stream resource
     */
    public function __construct($stream, $size = null)
    {
        $this->setStream($stream, $size);
    }

    /**
     * Closes the stream when the helper is destructed
     */
    public function __destruct()
    {
        $this->close();
    }

    public function __toString()
    {
        if (!$this->isReadable() || (!$this->isSeekable() && $this->isConsumed())) {
            return '';
        }

        $originalPos = $this->ftell();
        $body = stream_get_contents($this->stream, -1, 0);
        $this->seek($originalPos);

        return $body;
    }

    public function close()
    {
        if (is_resource($this->stream)) {
            fclose($this->stream);
        }
        $this->cache[self::IS_READABLE] = false;
        $this->cache[self::IS_WRITABLE] = false;
    }

    /**
     * Calculate a hash of a Stream
     *
     * @param StreamInterface $stream    Stream to calculate the hash for
     * @param string          $algo      Hash algorithm (e.g. md5, crc32, etc)
     * @param bool            $rawOutput Whether or not to use raw output
     *
     * @return bool|string Returns false on failure or a hash string on success
     */
    public static function getHash(StreamInterface $stream, $algo, $rawOutput = false)
    {
        $pos = $stream->ftell();
        if (!$stream->seek(0)) {
            return false;
        }

        $ctx = hash_init($algo);
        while (!$stream->feof()) {
            hash_update($ctx, $stream->read(8192));
        }

        $out = hash_final($ctx, (bool) $rawOutput);
        $stream->seek($pos);

        return $out;
    }

    public function getMetaData($key = null)
    {
        $meta = stream_get_meta_data($this->stream);

        return !$key ? $meta : (array_key_exists($key, $meta) ? $meta[$key] : null);
    }

    public function getStream()
    {
        return $this->stream;
    }

    public function setStream($stream, $size = null)
    {
        if (!is_resource($stream)) {
            throw new InvalidArgumentException('Stream must be a resource');
        }

        $this->size = $size;
        $this->stream = $stream;
        $this->rebuildCache();

        return $this;
    }

    public function detachStream()
    {
        $this->stream = null;

        return $this;
    }

    public function getWrapper()
    {
        return $this->cache[self::WRAPPER_TYPE];
    }

    public function getWrapperData()
    {
        return $this->getMetaData('wrapper_data') ?: array();
    }

    public function getStreamType()
    {
        return $this->cache[self::STREAM_TYPE];
    }

    public function getUri()
    {
        return $this->cache['uri'];
    }

    public function getSize()
    {
        if ($this->size !== null) {
            return $this->size;
        }

        // If the stream is a file based stream and local, then use fstat
        clearstatcache(true, $this->cache['uri']);
        $stats = fstat($this->stream);
        if (isset($stats['size'])) {
            $this->size = $stats['size'];
            return $this->size;
        } elseif ($this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]) {
            // Only get the size based on the content if the the stream is readable and seekable
            $pos = $this->ftell();
            $this->size = strlen((string) $this);
            $this->seek($pos);
            return $this->size;
        }

        return false;
    }

    public function isReadable()
    {
        return $this->cache[self::IS_READABLE];
    }

    public function isRepeatable()
    {
        return $this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE];
    }

    public function isWritable()
    {
        return $this->cache[self::IS_WRITABLE];
    }

    public function isConsumed()
    {
        return feof($this->stream);
    }

    public function feof()
    {
        return $this->isConsumed();
    }

    public function isLocal()
    {
        return $this->cache[self::IS_LOCAL];
    }

    public function isSeekable()
    {
        return $this->cache[self::SEEKABLE];
    }

    public function setSize($size)
    {
        $this->size = $size;

        return $this;
    }

    public function seek($offset, $whence = SEEK_SET)
    {
        return $this->cache[self::SEEKABLE] ? fseek($this->stream, $offset, $whence) === 0 : false;
    }

    public function read($length)
    {
        return fread($this->stream, $length);
    }

    public function write($string)
    {
        // We can't know the size after writing anything
        $this->size = null;

        return fwrite($this->stream, $string);
    }

    public function ftell()
    {
        return ftell($this->stream);
    }

    public function rewind()
    {
        return $this->seek(0);
    }

    public function readLine($maxLength = null)
    {
        if (!$this->cache[self::IS_READABLE]) {
            return false;
        } else {
            return $maxLength ? fgets($this->getStream(), $maxLength) : fgets($this->getStream());
        }
    }

    public function setCustomData($key, $value)
    {
        $this->customData[$key] = $value;

        return $this;
    }

    public function getCustomData($key)
    {
        return isset($this->customData[$key]) ? $this->customData[$key] : null;
    }

    /**
     * Reprocess stream metadata
     */
    protected function rebuildCache()
    {
        $this->cache = stream_get_meta_data($this->stream);
        $this->cache[self::IS_LOCAL] = stream_is_local($this->stream);
        $this->cache[self::IS_READABLE] = isset(self::$readWriteHash['read'][$this->cache['mode']]);
        $this->cache[self::IS_WRITABLE] = isset(self::$readWriteHash['write'][$this->cache['mode']]);
    }
}
<?php

namespace Guzzle\Stream;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Url;

/**
 * Factory used to create fopen streams using PHP's http and https stream wrappers
 *
 * Note: PHP's http stream wrapper only supports streaming downloads. It does not support streaming uploads.
 */
class PhpStreamRequestFactory implements StreamRequestFactoryInterface
{
    /** @var resource Stream context options */
    protected $context;

    /** @var array Stream context */
    protected $contextOptions;

    /** @var Url Stream URL */
    protected $url;

    /** @var array Last response headers received by the HTTP request */
    protected $lastResponseHeaders;

    /**
     * {@inheritdoc}
     *
     * The $params array can contain the following custom keys specific to the PhpStreamRequestFactory:
     * - stream_class: The name of a class to create instead of a Guzzle\Stream\Stream object
     */
    public function fromRequest(RequestInterface $request, $context = array(), array $params = array())
    {
        if (is_resource($context)) {
            $this->contextOptions = stream_context_get_options($context);
            $this->context = $context;
        } elseif (is_array($context) || !$context) {
            $this->contextOptions = $context;
            $this->createContext($params);
        } elseif ($context) {
            throw new InvalidArgumentException('$context must be an array or resource');
        }

        // Dispatch the before send event
        $request->dispatch('request.before_send', array(
            'request'         => $request,
            'context'         => $this->context,
            'context_options' => $this->contextOptions
        ));

        $this->setUrl($request);
        $this->addDefaultContextOptions($request);
        $this->addSslOptions($request);
        $this->addBodyOptions($request);
        $this->addProxyOptions($request);

        // Create the file handle but silence errors
        return $this->createStream($params)
            ->setCustomData('request', $request)
            ->setCustomData('response_headers', $this->getLastResponseHeaders());
    }

    /**
     * Set an option on the context and the internal options array
     *
     * @param string $wrapper   Stream wrapper name of http
     * @param string $name      Context name
     * @param mixed  $value     Context value
     * @param bool   $overwrite Set to true to overwrite an existing value
     */
    protected function setContextValue($wrapper, $name, $value, $overwrite = false)
    {
        if (!isset($this->contextOptions[$wrapper])) {
            $this->contextOptions[$wrapper] = array($name => $value);
        } elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) {
            return;
        }
        $this->contextOptions[$wrapper][$name] = $value;
        stream_context_set_option($this->context, $wrapper, $name, $value);
    }

    /**
     * Create a stream context
     *
     * @param array $params Parameter array
     */
    protected function createContext(array $params)
    {
        $options = $this->contextOptions;
        $this->context = $this->createResource(function () use ($params, $options) {
            return stream_context_create($options, $params);
        });
    }

    /**
     * Get the last response headers received by the HTTP request
     *
     * @return array
     */
    public function getLastResponseHeaders()
    {
        return $this->lastResponseHeaders;
    }

    /**
     * Adds the default context options to the stream context options
     *
     * @param RequestInterface $request Request
     */
    protected function addDefaultContextOptions(RequestInterface $request)
    {
        $this->setContextValue('http', 'method', $request->getMethod());
        $headers = $request->getHeaderLines();

        // "Connection: close" is required to get streams to work in HTTP 1.1
        if (!$request->hasHeader('Connection')) {
            $headers[] = 'Connection: close';
        }

        $this->setContextValue('http', 'header', $headers);
        $this->setContextValue('http', 'protocol_version', $request->getProtocolVersion());
        $this->setContextValue('http', 'ignore_errors', true);
    }

    /**
     * Set the URL to use with the factory
     *
     * @param RequestInterface $request Request that owns the URL
     */
    protected function setUrl(RequestInterface $request)
    {
        $this->url = $request->getUrl(true);

        // Check for basic Auth username
        if ($request->getUsername()) {
            $this->url->setUsername($request->getUsername());
        }

        // Check for basic Auth password
        if ($request->getPassword()) {
            $this->url->setPassword($request->getPassword());
        }
    }

    /**
     * Add SSL options to the stream context
     *
     * @param RequestInterface $request Request
     */
    protected function addSslOptions(RequestInterface $request)
    {
        if ($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) {
            $this->setContextValue('ssl', 'verify_peer', true, true);
            if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) {
                $this->setContextValue('ssl', 'cafile', $cafile, true);
            }
        } else {
            $this->setContextValue('ssl', 'verify_peer', false, true);
        }
    }

    /**
     * Add body (content) specific options to the context options
     *
     * @param RequestInterface $request
     */
    protected function addBodyOptions(RequestInterface $request)
    {
        // Add the content for the request if needed
        if (!($request instanceof EntityEnclosingRequestInterface)) {
            return;
        }

        if (count($request->getPostFields())) {
            $this->setContextValue('http', 'content', (string) $request->getPostFields(), true);
        } elseif ($request->getBody()) {
            $this->setContextValue('http', 'content', (string) $request->getBody(), true);
        }

        // Always ensure a content-length header is sent
        if (isset($this->contextOptions['http']['content'])) {
            $headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array();
            $headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']);
            $this->setContextValue('http', 'header', $headers, true);
        }
    }

    /**
     * Add proxy parameters to the context if needed
     *
     * @param RequestInterface $request Request
     */
    protected function addProxyOptions(RequestInterface $request)
    {
        if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) {
            $this->setContextValue('http', 'proxy', $proxy);
        }
    }

    /**
     * Create the stream for the request with the context options
     *
     * @param array $params Parameters of the stream
     *
     * @return StreamInterface
     */
    protected function createStream(array $params)
    {
        $http_response_header = null;
        $url = $this->url;
        $context = $this->context;
        $fp = $this->createResource(function () use ($context, $url, &$http_response_header) {
            return fopen((string) $url, 'r', false, $context);
        });

        // Determine the class to instantiate
        $className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream';

        /** @var $stream StreamInterface */
        $stream = new $className($fp);

        // Track the response headers of the request
        if (isset($http_response_header)) {
            $this->lastResponseHeaders = $http_response_header;
            $this->processResponseHeaders($stream);
        }

        return $stream;
    }

    /**
     * Process response headers
     *
     * @param StreamInterface $stream
     */
    protected function processResponseHeaders(StreamInterface $stream)
    {
        // Set the size on the stream if it was returned in the response
        foreach ($this->lastResponseHeaders as $header) {
            if ((stripos($header, 'Content-Length:')) === 0) {
                $stream->setSize(trim(substr($header, 15)));
            }
        }
    }

    /**
     * Create a resource and check to ensure it was created successfully
     *
     * @param callable $callback Closure to invoke that must return a valid resource
     *
     * @return resource
     * @throws RuntimeException on error
     */
    protected function createResource($callback)
    {
        $errors = null;
        set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
            $errors[] = array(
                'message' => $msg,
                'file'    => $file,
                'line'    => $line
            );
            return true;
        });
        $resource = call_user_func($callback);
        restore_error_handler();

        if (!$resource) {
            $message = 'Error creating resource. ';
            foreach ($errors as $err) {
                foreach ($err as $key => $value) {
                    $message .= "[$key] $value" . PHP_EOL;
                }
            }
            throw new RuntimeException(trim($message));
        }

        return $resource;
    }
}
<?php

namespace Guzzle\Stream;

use Guzzle\Http\Message\RequestInterface;

/**
 * Interface used for creating streams from requests
 */
interface StreamRequestFactoryInterface
{
    /**
     * Create a stream based on a request object
     *
     * @param RequestInterface $request Base the stream on a request
     * @param array|resource   $context A stream_context_options resource or array of parameters used to create a
     *                                  stream context.
     * @param array            $params  Optional array of parameters specific to the factory
     *
     * @return StreamInterface Returns a stream object
     * @throws \Guzzle\Common\Exception\RuntimeException if the stream cannot be opened or an error occurs
     */
    public function fromRequest(RequestInterface $request, $context = array(), array $params = array());
}
{
    "name": "guzzle/stream",
    "description": "Guzzle stream wrapper component",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["stream", "component", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/common": "self.version"
    },
    "suggest": {
        "guzzle/http": "To convert Guzzle request objects to PHP streams"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Stream": "" }
    },
    "target-dir": "Guzzle/Stream",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Strategy that will invoke a closure to determine whether or not to retry with a delay
 */
class CallbackBackoffStrategy extends AbstractBackoffStrategy
{
    /** @var \Closure|array|mixed Callable method to invoke */
    protected $callback;

    /** @var bool Whether or not this strategy makes a retry decision */
    protected $decision;

    /**
     * @param \Closure|array|mixed     $callback Callable method to invoke
     * @param bool                     $decision Set to true if this strategy makes a backoff decision
     * @param BackoffStrategyInterface $next     The optional next strategy
     *
     * @throws InvalidArgumentException
     */
    public function __construct($callback, $decision, BackoffStrategyInterface $next = null)
    {
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('The callback must be callable');
        }
        $this->callback = $callback;
        $this->decision = (bool) $decision;
        $this->next = $next;
    }

    public function makesDecision()
    {
        return $this->decision;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        return call_user_func($this->callback, $retries, $request, $response, $e);
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

/**
 * Strategy used to retry when certain error codes are encountered
 */
abstract class AbstractErrorCodeBackoffStrategy extends AbstractBackoffStrategy
{
    /** @var array Default cURL errors to retry */
    protected static $defaultErrorCodes = array();

    /** @var array Error codes that can be retried */
    protected $errorCodes;

    /**
     * @param array                    $codes Array of codes that should be retried
     * @param BackoffStrategyInterface $next  The optional next strategy
     */
    public function __construct(array $codes = null, BackoffStrategyInterface $next = null)
    {
        $this->errorCodes = array_fill_keys($codes ?: static::$defaultErrorCodes, 1);
        $this->next = $next;
    }

    /**
     * Get the default failure codes to retry
     *
     * @return array
     */
    public static function getDefaultFailureCodes()
    {
        return static::$defaultErrorCodes;
    }

    public function makesDecision()
    {
        return true;
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Will retry the request using the same amount of delay for each retry.
 *
 * Warning: If no decision making strategies precede this strategy in the the chain, then all requests will be retried
 */
class ConstantBackoffStrategy extends AbstractBackoffStrategy
{
    /** @var int Amount of time for each delay */
    protected $delay;

    /** @param int $delay Amount of time to delay between each additional backoff */
    public function __construct($delay)
    {
        $this->delay = $delay;
    }

    public function makesDecision()
    {
        return false;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        return $this->delay;
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Strategy to determine if a request should be retried and how long to delay between retries
 */
interface BackoffStrategyInterface
{
    /**
     * Get the amount of time to delay in seconds before retrying a request
     *
     * @param int              $retries  Number of retries of the request
     * @param RequestInterface $request  Request that was sent
     * @param Response         $response Response that was received. Note that there may not be a response
     * @param HttpException    $e        Exception that was encountered if any
     *
     * @return bool|int Returns false to not retry or the number of seconds to delay between retries
     */
    public function getBackoffPeriod(
        $retries,
        RequestInterface $request,
        Response $response = null,
        HttpException $e = null
    );
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Strategy used to retry HTTP requests based on the response code.
 *
 * Retries 500 and 503 error by default.
 */
class HttpBackoffStrategy extends AbstractErrorCodeBackoffStrategy
{
    /** @var array Default cURL errors to retry */
    protected static $defaultErrorCodes = array(500, 503);

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        if ($response) {
            //Short circuit the rest of the checks if it was successful
            if ($response->isSuccessful()) {
                return false;
            } else {
                return isset($this->errorCodes[$response->getStatusCode()]) ? true : null;
            }
        }
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Strategy used to retry HTTP requests when the response's reason phrase matches one of the registered phrases.
 */
class ReasonPhraseBackoffStrategy extends AbstractErrorCodeBackoffStrategy
{
    public function makesDecision()
    {
        return true;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        if ($response) {
            return isset($this->errorCodes[$response->getReasonPhrase()]) ? true : null;
        }
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Abstract backoff strategy that allows for a chain of responsibility
 */
abstract class AbstractBackoffStrategy implements BackoffStrategyInterface
{
    /** @var AbstractBackoffStrategy Next strategy in the chain */
    protected $next;

    /** @param AbstractBackoffStrategy $next Next strategy in the chain */
    public function setNext(AbstractBackoffStrategy $next)
    {
        $this->next = $next;
    }

    /**
     * Get the next backoff strategy in the chain
     *
     * @return AbstractBackoffStrategy|null
     */
    public function getNext()
    {
        return $this->next;
    }

    public function getBackoffPeriod(
        $retries,
        RequestInterface $request,
        Response $response = null,
        HttpException $e = null
    ) {
        $delay = $this->getDelay($retries, $request, $response, $e);
        if ($delay === false) {
            // The strategy knows that this must not be retried
            return false;
        } elseif ($delay === null) {
            // If the strategy is deferring a decision and the next strategy will not make a decision then return false
            return !$this->next || !$this->next->makesDecision()
                ? false
                : $this->next->getBackoffPeriod($retries, $request, $response, $e);
        } elseif ($delay === true) {
            // if the strategy knows that it must retry but is deferring to the next to determine the delay
            if (!$this->next) {
                return 0;
            } else {
                $next = $this->next;
                while ($next->makesDecision() && $next->getNext()) {
                    $next = $next->getNext();
                }
                return !$next->makesDecision() ? $next->getBackoffPeriod($retries, $request, $response, $e) : 0;
            }
        } else {
            return $delay;
        }
    }

    /**
     * Check if the strategy does filtering and makes decisions on whether or not to retry.
     *
     * Strategies that return false will never retry if all of the previous strategies in a chain defer on a backoff
     * decision.
     *
     * @return bool
     */
    abstract public function makesDecision();

    /**
     * Implement the concrete strategy
     *
     * @param int              $retries  Number of retries of the request
     * @param RequestInterface $request  Request that was sent
     * @param Response         $response Response that was received. Note that there may not be a response
     * @param HttpException    $e        Exception that was encountered if any
     *
     * @return bool|int|null Returns false to not retry or the number of seconds to delay between retries. Return true
     *                       or null to defer to the next strategy if available, and if not, return 0.
     */
    abstract protected function getDelay(
        $retries,
        RequestInterface $request,
        Response $response = null,
        HttpException $e = null
    );
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Common\Event;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Curl\CurlMultiInterface;
use Guzzle\Http\Exception\CurlException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Plugin to automatically retry failed HTTP requests using a backoff strategy
 */
class BackoffPlugin extends AbstractHasDispatcher implements EventSubscriberInterface
{
    const DELAY_PARAM = CurlMultiInterface::BLOCKING;
    const RETRY_PARAM = 'plugins.backoff.retry_count';
    const RETRY_EVENT = 'plugins.backoff.retry';

    /** @var BackoffStrategyInterface Backoff strategy */
    protected $strategy;

    /**
     * @param BackoffStrategyInterface $strategy The backoff strategy used to determine whether or not to retry and
     *                                           the amount of delay between retries.
     */
    public function __construct(BackoffStrategyInterface $strategy = null)
    {
        $this->strategy = $strategy;
    }

    /**
     * Retrieve a basic truncated exponential backoff plugin that will retry HTTP errors and cURL errors
     *
     * @param int   $maxRetries Maximum number of retries
     * @param array $httpCodes  HTTP response codes to retry
     * @param array $curlCodes  cURL error codes to retry
     *
     * @return self
     */
    public static function getExponentialBackoff(
        $maxRetries = 3,
        array $httpCodes = null,
        array $curlCodes = null
    ) {
        return new self(new TruncatedBackoffStrategy($maxRetries,
            new HttpBackoffStrategy($httpCodes,
                new CurlBackoffStrategy($curlCodes,
                    new ExponentialBackoffStrategy()
                )
            )
        ));
    }

    public static function getAllEvents()
    {
        return array(self::RETRY_EVENT);
    }

    public static function getSubscribedEvents()
    {
        return array(
            'request.sent'      => 'onRequestSent',
            'request.exception' => 'onRequestSent',
            CurlMultiInterface::POLLING_REQUEST => 'onRequestPoll'
        );
    }

    /**
     * Called when a request has been sent  and isn't finished processing
     *
     * @param Event $event
     */
    public function onRequestSent(Event $event)
    {
        $request = $event['request'];
        $response = $event['response'];
        $exception = $event['exception'];

        $params = $request->getParams();
        $retries = (int) $params->get(self::RETRY_PARAM);
        $delay = $this->strategy->getBackoffPeriod($retries, $request, $response, $exception);

        if ($delay !== false) {
            // Calculate how long to wait until the request should be retried
            $params->set(self::RETRY_PARAM, ++$retries)
                ->set(self::DELAY_PARAM, microtime(true) + $delay);
            // Send the request again
            $request->setState(RequestInterface::STATE_TRANSFER);
            $this->dispatch(self::RETRY_EVENT, array(
                'request'  => $request,
                'response' => $response,
                'handle'   => ($exception && $exception instanceof CurlException) ? $exception->getCurlHandle() : null,
                'retries'  => $retries,
                'delay'    => $delay
            ));
        }
    }

    /**
     * Called when a request is polling in the curl multi object
     *
     * @param Event $event
     */
    public function onRequestPoll(Event $event)
    {
        $request = $event['request'];
        $delay = $request->getParams()->get(self::DELAY_PARAM);

        // If the duration of the delay has passed, retry the request using the pool
        if (null !== $delay && microtime(true) >= $delay) {
            // Remove the request from the pool and then add it back again. This is required for cURL to know that we
            // want to retry sending the easy handle.
            $request->getParams()->remove(self::DELAY_PARAM);
            // Rewind the request body if possible
            if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()) {
                $request->getBody()->seek(0);
            }
            $multi = $event['curl_multi'];
            $multi->remove($request);
            $multi->add($request);
        }
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Strategy that will not retry more than a certain number of times.
 */
class TruncatedBackoffStrategy extends AbstractBackoffStrategy
{
    /** @var int Maximum number of retries per request */
    protected $max;

    /**
     * @param int                      $maxRetries Maximum number of retries per request
     * @param BackoffStrategyInterface $next The optional next strategy
     */
    public function __construct($maxRetries, BackoffStrategyInterface $next = null)
    {
        $this->max = $maxRetries;
        $this->next = $next;
    }

    public function makesDecision()
    {
        return true;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        return $retries < $this->max ? null : false;
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Implements a linear backoff retry strategy.
 *
 * Warning: If no decision making strategies precede this strategy in the the chain, then all requests will be retried
 */
class LinearBackoffStrategy extends AbstractBackoffStrategy
{
    /** @var int Amount of time to progress each delay */
    protected $step;

    /**
     * @param int $step Amount of time to increase the delay each additional backoff
     */
    public function __construct($step = 1)
    {
        $this->step = $step;
    }

    public function makesDecision()
    {
        return false;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        return $retries * $this->step;
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

/**
 * Implements an exponential backoff retry strategy.
 *
 * Warning: If no decision making strategies precede this strategy in the the chain, then all requests will be retried
 */
class ExponentialBackoffStrategy extends AbstractBackoffStrategy
{
    public function makesDecision()
    {
        return false;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        return (int) pow(2, $retries);
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Exception\CurlException;

/**
 * Strategy used to retry when certain cURL error codes are encountered.
 */
class CurlBackoffStrategy extends AbstractErrorCodeBackoffStrategy
{
    /** @var array Default cURL errors to retry */
    protected static $defaultErrorCodes = array(
        CURLE_COULDNT_RESOLVE_HOST, CURLE_COULDNT_CONNECT, CURLE_PARTIAL_FILE, CURLE_WRITE_ERROR, CURLE_READ_ERROR,
        CURLE_OPERATION_TIMEOUTED, CURLE_SSL_CONNECT_ERROR, CURLE_HTTP_PORT_FAILED, CURLE_GOT_NOTHING,
        CURLE_SEND_ERROR, CURLE_RECV_ERROR
    );

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        if ($e && $e instanceof CurlException) {
            return isset($this->errorCodes[$e->getErrorNo()]) ? true : null;
        }
    }
}
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Common\Event;
use Guzzle\Log\LogAdapterInterface;
use Guzzle\Log\MessageFormatter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Logs backoff retries triggered from the BackoffPlugin
 *
 * Format your log messages using a template that can contain template substitutions found in {@see MessageFormatter}.
 * In addition to the default template substitutions, there is also:
 *
 * - retries: The number of times the request has been retried
 * - delay:   The amount of time the request is being delayed
 */
class BackoffLogger implements EventSubscriberInterface
{
    /** @var string Default log message template */
    const DEFAULT_FORMAT = '[{ts}] {method} {url} - {code} {phrase} - Retries: {retries}, Delay: {delay}, Time: {connect_time}, {total_time}, cURL: {curl_code} {curl_error}';

    /** @var LogAdapterInterface Logger used to log retries */
    protected $logger;

    /** @var MessageFormatter Formatter used to format log messages */
    protected $formatter;

    /**
     * @param LogAdapterInterface $logger    Logger used to log the retries
     * @param MessageFormatter    $formatter Formatter used to format log messages
     */
    public function __construct(LogAdapterInterface $logger, MessageFormatter $formatter = null)
    {
        $this->logger = $logger;
        $this->formatter = $formatter ?: new MessageFormatter(self::DEFAULT_FORMAT);
    }

    public static function getSubscribedEvents()
    {
        return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry');
    }

    /**
     * Set the template to use for logging
     *
     * @param string $template Log message template
     *
     * @return self
     */
    public function setTemplate($template)
    {
        $this->formatter->setTemplate($template);

        return $this;
    }

    /**
     * Called when a request is being retried
     *
     * @param Event $event Event emitted
     */
    public function onRequestRetry(Event $event)
    {
        $this->logger->log($this->formatter->format(
            $event['request'],
            $event['response'],
            $event['handle'],
            array(
                'retries' => $event['retries'],
                'delay'   => $event['delay']
            )
        ));
    }
}
{
    "name": "guzzle/plugin-backoff",
    "description": "Guzzle backoff retry plugins",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version",
        "guzzle/log": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Backoff": "" }
    },
    "target-dir": "Guzzle/Plugin/Backoff",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Md5;

use Guzzle\Common\Event;
use Guzzle\Common\Exception\UnexpectedValueException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Ensures that an the MD5 hash of an entity body matches the Content-MD5
 * header (if set) of an HTTP response.  An exception is thrown if the
 * calculated MD5 does not match the expected MD5.
 */
class Md5ValidatorPlugin implements EventSubscriberInterface
{
    /** @var int Maximum Content-Length in bytes to validate */
    protected $contentLengthCutoff;

    /** @var bool Whether or not to compare when a Content-Encoding is present */
    protected $contentEncoded;

    /**
     * @param bool     $contentEncoded      Calculating the MD5 hash of an entity body where a Content-Encoding was
     *                                      applied is a more expensive comparison because the entity body will need to
     *                                      be compressed in order to get the correct hash.  Set to FALSE to not
     *                                      validate the MD5 hash of an entity body with an applied Content-Encoding.
     * @param bool|int $contentLengthCutoff Maximum Content-Length (bytes) in which a MD5 hash will be validated. Any
     *                                      response with a Content-Length greater than this value will not be validated
     *                                      because it will be deemed too memory intensive.
     */
    public function __construct($contentEncoded = true, $contentLengthCutoff = false)
    {
        $this->contentLengthCutoff = $contentLengthCutoff;
        $this->contentEncoded = $contentEncoded;
    }

    public static function getSubscribedEvents()
    {
        return array('request.complete' => array('onRequestComplete', 255));
    }

    /**
     * {@inheritdoc}
     * @throws UnexpectedValueException
     */
    public function onRequestComplete(Event $event)
    {
        $response = $event['response'];

        if (!$contentMd5 = $response->getContentMd5()) {
            return;
        }

        $contentEncoding = $response->getContentEncoding();
        if ($contentEncoding && !$this->contentEncoded) {
            return false;
        }

        // Make sure that the size of the request is under the cutoff size
        if ($this->contentLengthCutoff) {
            $size = $response->getContentLength() ?: $response->getBody()->getSize();
            if (!$size || $size > $this->contentLengthCutoff) {
                return;
            }
        }

        if (!$contentEncoding) {
            $hash = $response->getBody()->getContentMd5();
        } elseif ($contentEncoding == 'gzip') {
            $response->getBody()->compress('zlib.deflate');
            $hash = $response->getBody()->getContentMd5();
            $response->getBody()->uncompress();
        } elseif ($contentEncoding == 'compress') {
            $response->getBody()->compress('bzip2.compress');
            $hash = $response->getBody()->getContentMd5();
            $response->getBody()->uncompress();
        } else {
            return;
        }

        if ($contentMd5 !== $hash) {
            throw new UnexpectedValueException(
                "The response entity body may have been modified over the wire.  The Content-MD5 "
                . "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})."
            );
        }
    }
}
<?php

namespace Guzzle\Plugin\Md5;

use Guzzle\Common\Event;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener used to add a ContentMD5 header to the body of a command and adds ContentMD5 validation if the
 * ValidateMD5 option is not set to false on a command
 */
class CommandContentMd5Plugin  implements EventSubscriberInterface
{
    /** @var string Parameter used to check if the ContentMD5 value is being added */
    protected $contentMd5Param;

    /** @var string Parameter used to check if validation should occur on the response */
    protected $validateMd5Param;

    /**
     * @param string $contentMd5Param  Parameter used to check if the ContentMD5 value is being added
     * @param string $validateMd5Param Parameter used to check if validation should occur on the response
     */
    public function __construct($contentMd5Param = 'ContentMD5', $validateMd5Param = 'ValidateMD5')
    {
        $this->contentMd5Param = $contentMd5Param;
        $this->validateMd5Param = $validateMd5Param;
    }

    public static function getSubscribedEvents()
    {
        return array('command.before_send' => array('onCommandBeforeSend', -255));
    }

    public function onCommandBeforeSend(Event $event)
    {
        $command = $event['command'];
        $request = $command->getRequest();

        // Only add an MD5 is there is a MD5 option on the operation and it has a payload
        if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
            && $command->getOperation()->hasParam($this->contentMd5Param)) {
            // Check if an MD5 checksum value should be passed along to the request
            if ($command[$this->contentMd5Param] === true) {
                if (false !== ($md5 = $request->getBody()->getContentMd5(true, true))) {
                    $request->setHeader('Content-MD5', $md5);
                }
            }
        }

        // Check if MD5 validation should be used with the response
        if ($command[$this->validateMd5Param] === true) {
            $request->addSubscriber(new Md5ValidatorPlugin(true, false));
        }
    }
}
{
    "name": "guzzle/plugin-md5",
    "description": "Guzzle MD5 plugins",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Md5": "" }
    },
    "target-dir": "Guzzle/Plugin/Md5",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Oauth;

use Guzzle\Common\Event;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * OAuth signing plugin
 * @link http://oauth.net/core/1.0/#rfc.section.9.1.1
 */
class OauthPlugin implements EventSubscriberInterface
{
    /**
     * Consumer request method constants. See http://oauth.net/core/1.0/#consumer_req_param
     */
    const REQUEST_METHOD_HEADER = 'header';
    const REQUEST_METHOD_QUERY  = 'query';

    /** @var Collection Configuration settings */
    protected $config;

    /**
     * Create a new OAuth 1.0 plugin
     *
     * @param array $config Configuration array containing these parameters:
     *     - string 'request_method'       Consumer request method. Use the class constants.
     *     - string 'callback'             OAuth callback
     *     - string 'consumer_key'         Consumer key
     *     - string 'consumer_secret'      Consumer secret
     *     - string 'token'                Token
     *     - string 'token_secret'         Token secret
     *     - string 'verifier'             OAuth verifier.
     *     - string 'version'              OAuth version.  Defaults to 1.0
     *     - string 'signature_method'     Custom signature method
     *     - bool   'disable_post_params'  Set to true to prevent POST parameters from being signed
     *     - array|Closure 'signature_callback' Custom signature callback that accepts a string to sign and a signing key
     */
    public function __construct($config)
    {
        $this->config = Collection::fromConfig($config, array(
            'version' => '1.0',
            'request_method' => self::REQUEST_METHOD_HEADER,
            'consumer_key' => 'anonymous',
            'consumer_secret' => 'anonymous',
            'signature_method' => 'HMAC-SHA1',
            'signature_callback' => function($stringToSign, $key) {
                return hash_hmac('sha1', $stringToSign, $key, true);
            }
        ), array(
            'signature_method', 'signature_callback', 'version',
            'consumer_key', 'consumer_secret'
        ));
    }

    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send' => array('onRequestBeforeSend', -1000)
        );
    }

    /**
     * Request before-send event handler
     *
     * @param Event $event Event received
     * @return array
     * @throws \InvalidArgumentException
     */
    public function onRequestBeforeSend(Event $event)
    {
        $timestamp = $this->getTimestamp($event);
        $request = $event['request'];
        $nonce = $this->generateNonce($request);
        $authorizationParams = $this->getOauthParams($timestamp, $nonce);
        $authorizationParams['oauth_signature']  = $this->getSignature($request, $timestamp, $nonce);

        switch ($this->config['request_method']) {
            case self::REQUEST_METHOD_HEADER:
                $request->setHeader(
                    'Authorization',
                    $this->buildAuthorizationHeader($authorizationParams)
                );
                break;
            case self::REQUEST_METHOD_QUERY:
                foreach ($authorizationParams as $key => $value) {
                    $request->getQuery()->set($key, $value);
                }
                break;
            default:
                throw new \InvalidArgumentException(sprintf(
                    'Invalid consumer method "%s"',
                    $this->config['request_method']
                ));
        }

        return $authorizationParams;
    }

    /**
     * Builds the Authorization header for a request
     *
     * @param array $authorizationParams Associative array of authorization parameters
     *
     * @return string
     */
    private function buildAuthorizationHeader($authorizationParams)
    {
        $authorizationString = 'OAuth ';
        foreach ($authorizationParams as $key => $val) {
            if ($val) {
                $authorizationString .= $key . '="' . urlencode($val) . '", ';
            }
        }

        return substr($authorizationString, 0, -2);
    }

    /**
     * Calculate signature for request
     *
     * @param RequestInterface $request   Request to generate a signature for
     * @param integer          $timestamp Timestamp to use for nonce
     * @param string           $nonce
     *
     * @return string
     */
    public function getSignature(RequestInterface $request, $timestamp, $nonce)
    {
        $string = $this->getStringToSign($request, $timestamp, $nonce);
        $key = urlencode($this->config['consumer_secret']) . '&' . urlencode($this->config['token_secret']);

        return base64_encode(call_user_func($this->config['signature_callback'], $string, $key));
    }

    /**
     * Calculate string to sign
     *
     * @param RequestInterface $request   Request to generate a signature for
     * @param int              $timestamp Timestamp to use for nonce
     * @param string           $nonce
     *
     * @return string
     */
    public function getStringToSign(RequestInterface $request, $timestamp, $nonce)
    {
        $params = $this->getParamsToSign($request, $timestamp, $nonce);

        // Convert booleans to strings.
        $params = $this->prepareParameters($params);

        // Build signing string from combined params
        $parameterString = clone $request->getQuery();
        $parameterString->replace($params);

        $url = Url::factory($request->getUrl())->setQuery('')->setFragment(null);

        return strtoupper($request->getMethod()) . '&'
             . rawurlencode($url) . '&'
             . rawurlencode((string) $parameterString);
    }

    /**
     * Get the oauth parameters as named by the oauth spec
     *
     * @param $timestamp
     * @param $nonce
     * @return Collection
     */
    protected function getOauthParams($timestamp, $nonce)
    {
        $params = new Collection(array(
            'oauth_consumer_key'     => $this->config['consumer_key'],
            'oauth_nonce'            => $nonce,
            'oauth_signature_method' => $this->config['signature_method'],
            'oauth_timestamp'        => $timestamp,
        ));

        // Optional parameters should not be set if they have not been set in the config as
        // the parameter may be considered invalid by the Oauth service.
        $optionalParams = array(
            'callback'  => 'oauth_callback',
            'token'     => 'oauth_token',
            'verifier'  => 'oauth_verifier',
            'version'   => 'oauth_version'
        );

        foreach ($optionalParams as $optionName => $oauthName) {
            if (isset($this->config[$optionName]) == true) {
                $params[$oauthName] = $this->config[$optionName];
            }
        }

        return $params;
    }

    /**
     * Get all of the parameters required to sign a request including:
     * * The oauth params
     * * The request GET params
     * * The params passed in the POST body (with a content-type of application/x-www-form-urlencoded)
     *
     * @param RequestInterface $request   Request to generate a signature for
     * @param integer          $timestamp Timestamp to use for nonce
     * @param string           $nonce
     *
     * @return array
     */
    public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
    {
        $params = $this->getOauthParams($timestamp, $nonce);

        // Add query string parameters
        $params->merge($request->getQuery());

        // Add POST fields to signing string if required
        if ($this->shouldPostFieldsBeSigned($request))
        {
            $params->merge($request->getPostFields());
        }

        // Sort params
        $params = $params->toArray();
        uksort($params, 'strcmp');

        return $params;
    }

    /**
     * Decide whether the post fields should be added to the base string that Oauth signs.
     * This implementation is correct. Non-conformant APIs may require that this method be
     * overwritten e.g. the Flickr API incorrectly adds the post fields when the Content-Type
     * is 'application/x-www-form-urlencoded'
     *
     * @param $request
     * @return bool Whether the post fields should be signed or not
     */
    public function shouldPostFieldsBeSigned($request)
    {
        if (!$this->config->get('disable_post_params') &&
            $request instanceof EntityEnclosingRequestInterface &&
            false !== strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded'))
        {
            return true;
        }

        return false;
    }

    /**
     * Returns a Nonce Based on the unique id and URL. This will allow for multiple requests in parallel with the same
     * exact timestamp to use separate nonce's.
     *
     * @param RequestInterface $request Request to generate a nonce for
     *
     * @return string
     */
    public function generateNonce(RequestInterface $request)
    {
        return sha1(uniqid('', true) . $request->getUrl());
    }

    /**
     * Gets timestamp from event or create new timestamp
     *
     * @param Event $event Event containing contextual information
     *
     * @return int
     */
    public function getTimestamp(Event $event)
    {
       return $event['timestamp'] ?: time();
    }

    /**
     * Convert booleans to strings, removed unset parameters, and sorts the array
     *
     * @param array $data Data array
     *
     * @return array
     */
    protected function prepareParameters($data)
    {
        ksort($data);
        foreach ($data as $key => &$value) {
            switch (gettype($value)) {
                case 'NULL':
                    unset($data[$key]);
                    break;
                case 'array':
                    $data[$key] = self::prepareParameters($value);
                    break;
                case 'boolean':
                    $data[$key] = $value ? 'true' : 'false';
                    break;
            }
        }

        return $data;
    }
}
{
    "name": "guzzle/plugin-oauth",
    "description": "Guzzle OAuth plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["oauth", "plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Oauth": "" }
    },
    "target-dir": "Guzzle/Plugin/Oauth",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;

\Guzzle\Common\Version::warn('Guzzle\Plugin\Cache\DefaultCacheKeyProvider is no longer used');

/**
 * @deprecated This class is no longer used
 * @codeCoverageIgnore
 */
class DefaultCacheKeyProvider implements CacheKeyProviderInterface
{
    public function getCacheKey(RequestInterface $request)
    {
        // See if the key has already been calculated
        $key = $request->getParams()->get(self::CACHE_KEY);

        if (!$key) {

            $cloned = clone $request;
            $cloned->removeHeader('Cache-Control');

            // Check to see how and if the key should be filtered
            foreach (explode(';', $request->getParams()->get(self::CACHE_KEY_FILTER)) as $part) {
                $pieces = array_map('trim', explode('=', $part));
                if (isset($pieces[1])) {
                    foreach (array_map('trim', explode(',', $pieces[1])) as $remove) {
                        if ($pieces[0] == 'header') {
                            $cloned->removeHeader($remove);
                        } elseif ($pieces[0] == 'query') {
                            $cloned->getQuery()->remove($remove);
                        }
                    }
                }
            }

            $raw = (string) $cloned;
            $key = 'GZ' . md5($raw);
            $request->getParams()->set(self::CACHE_KEY, $key)->set(self::CACHE_KEY_RAW, $raw);
        }

        return $key;
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Determines if a request can be cached using a callback
 */
class CallbackCanCacheStrategy extends DefaultCanCacheStrategy
{
    /** @var callable Callback for request */
    protected $requestCallback;

    /** @var callable Callback for response */
    protected $responseCallback;

    /**
     * @param \Closure|array|mixed $requestCallback  Callable method to invoke for requests
     * @param \Closure|array|mixed $responseCallback Callable method to invoke for responses
     *
     * @throws InvalidArgumentException
     */
    public function __construct($requestCallback = null, $responseCallback = null)
    {
        if ($requestCallback && !is_callable($requestCallback)) {
            throw new InvalidArgumentException('Method must be callable');
        }

        if ($responseCallback && !is_callable($responseCallback)) {
            throw new InvalidArgumentException('Method must be callable');
        }

        $this->requestCallback = $requestCallback;
        $this->responseCallback = $responseCallback;
    }

    public function canCacheRequest(RequestInterface $request)
    {
        return $this->requestCallback
            ? call_user_func($this->requestCallback, $request)
            : parent::canCacheRequest($request);
    }

    public function canCacheResponse(Response $response)
    {
        return $this->responseCallback
            ? call_user_func($this->responseCallback, $response)
            : parent::canCacheResponse($response);
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Cache\CacheAdapterFactory;
use Guzzle\Cache\CacheAdapterInterface;
use Guzzle\Common\Event;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Version;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Http\Exception\CurlException;
use Doctrine\Common\Cache\ArrayCache;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Plugin to enable the caching of GET and HEAD requests.  Caching can be done on all requests passing through this
 * plugin or only after retrieving resources with cacheable response headers.
 *
 * This is a simple implementation of RFC 2616 and should be considered a private transparent proxy cache, meaning
 * authorization and private data can be cached.
 *
 * It also implements RFC 5861's `stale-if-error` Cache-Control extension, allowing stale cache responses to be used
 * when an error is encountered (such as a `500 Internal Server Error` or DNS failure).
 */
class CachePlugin implements EventSubscriberInterface
{
    /** @var RevalidationInterface Cache revalidation strategy */
    protected $revalidation;

    /** @var CanCacheStrategyInterface Object used to determine if a request can be cached */
    protected $canCache;

    /** @var CacheStorageInterface $cache Object used to cache responses */
    protected $storage;

    /** @var bool */
    protected $autoPurge;

    /**
     * @param array|CacheAdapterInterface|CacheStorageInterface $options Array of options for the cache plugin,
     *     cache adapter, or cache storage object.
     *     - CacheStorageInterface storage:      Adapter used to cache responses
     *     - RevalidationInterface revalidation: Cache revalidation strategy
     *     - CanCacheInterface     can_cache:    Object used to determine if a request can be cached
     *     - bool                  auto_purge    Set to true to automatically PURGE resources when non-idempotent
     *                                           requests are sent to a resource. Defaults to false.
     * @throws InvalidArgumentException if no cache is provided and Doctrine cache is not installed
     */
    public function __construct($options = null)
    {
        if (!is_array($options)) {
            if ($options instanceof CacheAdapterInterface) {
                $options = array('storage' => new DefaultCacheStorage($options));
            } elseif ($options instanceof CacheStorageInterface) {
                $options = array('storage' => $options);
            } elseif ($options) {
                $options = array('storage' => new DefaultCacheStorage(CacheAdapterFactory::fromCache($options)));
            } elseif (!class_exists('Doctrine\Common\Cache\ArrayCache')) {
                // @codeCoverageIgnoreStart
                throw new InvalidArgumentException('No cache was provided and Doctrine is not installed');
                // @codeCoverageIgnoreEnd
            }
        }

        $this->autoPurge = isset($options['auto_purge']) ? $options['auto_purge'] : false;

        // Add a cache storage if a cache adapter was provided
        $this->storage = isset($options['storage'])
            ? $options['storage']
            : new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache()));

        if (!isset($options['can_cache'])) {
            $this->canCache = new DefaultCanCacheStrategy();
        } else {
            $this->canCache = is_callable($options['can_cache'])
                ? new CallbackCanCacheStrategy($options['can_cache'])
                : $options['can_cache'];
        }

        // Use the provided revalidation strategy or the default
        $this->revalidation = isset($options['revalidation'])
            ? $options['revalidation']
            : new DefaultRevalidation($this->storage, $this->canCache);
    }

    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send' => array('onRequestBeforeSend', -255),
            'request.sent'        => array('onRequestSent', 255),
            'request.error'       => array('onRequestError', 0),
            'request.exception'   => array('onRequestException', 0),
        );
    }

    /**
     * Check if a response in cache will satisfy the request before sending
     *
     * @param Event $event
     */
    public function onRequestBeforeSend(Event $event)
    {
        $request = $event['request'];
        $request->addHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION));

        if (!$this->canCache->canCacheRequest($request)) {
            switch ($request->getMethod()) {
                case 'PURGE':
                    $this->purge($request);
                    $request->setResponse(new Response(200, array(), 'purged'));
                    break;
                case 'PUT':
                case 'POST':
                case 'DELETE':
                case 'PATCH':
                    if ($this->autoPurge) {
                        $this->purge($request);
                    }
            }
            return;
        }

        if ($response = $this->storage->fetch($request)) {
            $params = $request->getParams();
            $params['cache.lookup'] = true;
            $response->setHeader(
                'Age',
                time() - strtotime($response->getDate() ? : $response->getLastModified() ?: 'now')
            );
            // Validate that the response satisfies the request
            if ($this->canResponseSatisfyRequest($request, $response)) {
                if (!isset($params['cache.hit'])) {
                    $params['cache.hit'] = true;
                }
                $request->setResponse($response);
            }
        }
    }

    /**
     * If possible, store a response in cache after sending
     *
     * @param Event $event
     */
    public function onRequestSent(Event $event)
    {
        $request = $event['request'];
        $response = $event['response'];

        if ($request->getParams()->get('cache.hit') === null &&
            $this->canCache->canCacheRequest($request) &&
            $this->canCache->canCacheResponse($response)
        ) {
            $this->storage->cache($request, $response);
        }

        $this->addResponseHeaders($request, $response);
    }

    /**
     * If possible, return a cache response on an error
     *
     * @param Event $event
     */
    public function onRequestError(Event $event)
    {
        $request = $event['request'];

        if (!$this->canCache->canCacheRequest($request)) {
            return;
        }

        if ($response = $this->storage->fetch($request)) {
            $response->setHeader(
                'Age',
                time() - strtotime($response->getLastModified() ? : $response->getDate() ?: 'now')
            );

            if ($this->canResponseSatisfyFailedRequest($request, $response)) {
                $request->getParams()->set('cache.hit', 'error');
                $this->addResponseHeaders($request, $response);
                $event['response'] = $response;
                $event->stopPropagation();
            }
        }
    }

    /**
     * If possible, set a cache response on a cURL exception
     *
     * @param Event $event
     *
     * @return null
     */
    public function onRequestException(Event $event)
    {
        if (!$event['exception'] instanceof CurlException) {
            return;
        }

        $request = $event['request'];
        if (!$this->canCache->canCacheRequest($request)) {
            return;
        }

        if ($response = $this->storage->fetch($request)) {
            $response->setHeader('Age', time() - strtotime($response->getDate() ? : 'now'));
            if (!$this->canResponseSatisfyFailedRequest($request, $response)) {
                return;
            }
            $request->getParams()->set('cache.hit', 'error');
            $request->setResponse($response);
            $this->addResponseHeaders($request, $response);
            $event->stopPropagation();
        }
    }

    /**
     * Check if a cache response satisfies a request's caching constraints
     *
     * @param RequestInterface $request  Request to validate
     * @param Response         $response Response to validate
     *
     * @return bool
     */
    public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
    {
        $responseAge = $response->calculateAge();
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');

        // Check the request's max-age header against the age of the response
        if ($reqc && $reqc->hasDirective('max-age') &&
            $responseAge > $reqc->getDirective('max-age')) {
            return false;
        }

        // Check the response's max-age header
        if ($response->isFresh() === false) {
            $maxStale = $reqc ? $reqc->getDirective('max-stale') : null;
            if (null !== $maxStale) {
                if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) {
                    return false;
                }
            } elseif ($resc && $resc->hasDirective('max-age')
                && $responseAge > $resc->getDirective('max-age')
            ) {
                return false;
            }
        }

        if ($this->revalidation->shouldRevalidate($request, $response)) {
            try {
                return $this->revalidation->revalidate($request, $response);
            } catch (CurlException $e) {
                $request->getParams()->set('cache.hit', 'error');
                return $this->canResponseSatisfyFailedRequest($request, $response);
            }
        }

        return true;
    }

    /**
     * Check if a cache response satisfies a failed request's caching constraints
     *
     * @param RequestInterface $request  Request to validate
     * @param Response         $response Response to validate
     *
     * @return bool
     */
    public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response)
    {
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');
        $requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null;
        $responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null;

        if (!$requestStaleIfError && !$responseStaleIfError) {
            return false;
        }

        if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) {
            return false;
        }

        if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) {
            return false;
        }

        return true;
    }

    /**
     * Purge all cache entries for a given URL
     *
     * @param string $url URL to purge
     */
    public function purge($url)
    {
        // BC compatibility with previous version that accepted a Request object
        $url = $url instanceof RequestInterface ? $url->getUrl() : $url;
        $this->storage->purge($url);
    }

    /**
     * Add the plugin's headers to a response
     *
     * @param RequestInterface $request  Request
     * @param Response         $response Response to add headers to
     */
    protected function addResponseHeaders(RequestInterface $request, Response $response)
    {
        $params = $request->getParams();
        $response->setHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION));

        $lookup = ($params['cache.lookup'] === true ? 'HIT' : 'MISS') . ' from GuzzleCache';
        if ($header = $response->getHeader('X-Cache-Lookup')) {
            // Don't add duplicates
            $values = $header->toArray();
            $values[] = $lookup;
            $response->setHeader('X-Cache-Lookup', array_unique($values));
        } else {
            $response->setHeader('X-Cache-Lookup', $lookup);
        }

        if ($params['cache.hit'] === true) {
            $xcache = 'HIT from GuzzleCache';
        } elseif ($params['cache.hit'] == 'error') {
            $xcache = 'HIT_ERROR from GuzzleCache';
        } else {
            $xcache = 'MISS from GuzzleCache';
        }

        if ($header = $response->getHeader('X-Cache')) {
            // Don't add duplicates
            $values = $header->toArray();
            $values[] = $xcache;
            $response->setHeader('X-Cache', array_unique($values));
        } else {
            $response->setHeader('X-Cache', $xcache);
        }

        if ($response->isFresh() === false) {
            $response->addHeader('Warning', sprintf('110 GuzzleCache/%s "Response is stale"', Version::VERSION));
            if ($params['cache.hit'] === 'error') {
                $response->addHeader('Warning', sprintf('111 GuzzleCache/%s "Revalidation failed"', Version::VERSION));
            }
        }
    }
}
<?php

namespace Guzzle\Plugin\Cache;

\Guzzle\Common\Version::warn('Guzzle\Plugin\Cache\CacheKeyProviderInterface is no longer used');

/**
 * @deprecated This is no longer used
 * @codeCoverageIgnore
 */
interface CacheKeyProviderInterface {}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Cache revalidation interface
 */
interface RevalidationInterface
{
    /**
     * Performs a cache revalidation
     *
     * @param RequestInterface $request    Request to revalidate
     * @param Response         $response   Response that was received
     *
     * @return bool Returns true if the request can be cached
     */
    public function revalidate(RequestInterface $request, Response $response);

    /**
     * Returns true if the response should be revalidated
     *
     * @param RequestInterface $request  Request to check
     * @param Response         $response Response to check
     *
     * @return bool
     */
    public function shouldRevalidate(RequestInterface $request, Response $response);
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Default strategy used to determine of an HTTP request can be cached
 */
class DefaultCanCacheStrategy implements CanCacheStrategyInterface
{
    public function canCacheRequest(RequestInterface $request)
    {
        // Only GET and HEAD requests can be cached
        if ($request->getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) {
            return false;
        }

        // Never cache requests when using no-store
        if ($request->hasHeader('Cache-Control') && $request->getHeader('Cache-Control')->hasDirective('no-store')) {
            return false;
        }

        return true;
    }

    public function canCacheResponse(Response $response)
    {
        return $response->isSuccessful() && $response->canCache();
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Strategy used to determine if a request can be cached
 */
interface CanCacheStrategyInterface
{
    /**
     * Determine if a request can be cached
     *
     * @param RequestInterface $request Request to determine
     *
     * @return bool
     */
    public function canCacheRequest(RequestInterface $request);

    /**
     * Determine if a response can be cached
     *
     * @param Response $response Response to determine
     *
     * @return bool
     */
    public function canCacheResponse(Response $response);
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Never performs cache revalidation and just assumes the request is still ok
 */
class SkipRevalidation extends DefaultRevalidation
{
    public function __construct() {}

    public function revalidate(RequestInterface $request, Response $response)
    {
        return true;
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\BadResponseException;

/**
 * Default revalidation strategy
 */
class DefaultRevalidation implements RevalidationInterface
{
    /** @var CacheStorageInterface Cache object storing cache data */
    protected $storage;

    /** @var CanCacheStrategyInterface */
    protected $canCache;

    /**
     * @param CacheStorageInterface     $cache    Cache storage
     * @param CanCacheStrategyInterface $canCache Determines if a message can be cached
     */
    public function __construct(CacheStorageInterface $cache, CanCacheStrategyInterface $canCache = null)
    {
        $this->storage = $cache;
        $this->canCache = $canCache ?: new DefaultCanCacheStrategy();
    }

    public function revalidate(RequestInterface $request, Response $response)
    {
        try {
            $revalidate = $this->createRevalidationRequest($request, $response);
            $validateResponse = $revalidate->send();
            if ($validateResponse->getStatusCode() == 200) {
                return $this->handle200Response($request, $validateResponse);
            } elseif ($validateResponse->getStatusCode() == 304) {
                return $this->handle304Response($request, $validateResponse, $response);
            }
        } catch (BadResponseException $e) {
            $this->handleBadResponse($e);
        }

        // Other exceptions encountered in the revalidation request are ignored
        // in hopes that sending a request to the origin server will fix it
        return false;
    }

    public function shouldRevalidate(RequestInterface $request, Response $response)
    {
        if ($request->getMethod() != RequestInterface::GET) {
            return false;
        }

        $reqCache = $request->getHeader('Cache-Control');
        $resCache = $response->getHeader('Cache-Control');

        $revalidate = $request->getHeader('Pragma') == 'no-cache' ||
            ($reqCache && ($reqCache->hasDirective('no-cache') || $reqCache->hasDirective('must-revalidate'))) ||
            ($resCache && ($resCache->hasDirective('no-cache') || $resCache->hasDirective('must-revalidate')));

        // Use the strong ETag validator if available and the response contains no Cache-Control directive
        if (!$revalidate && !$resCache && $response->hasHeader('ETag')) {
            $revalidate = true;
        }

        return $revalidate;
    }

    /**
     * Handles a bad response when attempting to revalidate
     *
     * @param BadResponseException $e Exception encountered
     *
     * @throws BadResponseException
     */
    protected function handleBadResponse(BadResponseException $e)
    {
        // 404 errors mean the resource no longer exists, so remove from
        // cache, and prevent an additional request by throwing the exception
        if ($e->getResponse()->getStatusCode() == 404) {
            $this->storage->delete($e->getRequest());
            throw $e;
        }
    }

    /**
     * Creates a request to use for revalidation
     *
     * @param RequestInterface $request  Request
     * @param Response         $response Response to revalidate
     *
     * @return RequestInterface returns a revalidation request
     */
    protected function createRevalidationRequest(RequestInterface $request, Response $response)
    {
        $revalidate = clone $request;
        $revalidate->removeHeader('Pragma')->removeHeader('Cache-Control');

        if ($response->getLastModified()) {
            $revalidate->setHeader('If-Modified-Since', $response->getLastModified());
        }

        if ($response->getEtag()) {
            $revalidate->setHeader('If-None-Match', $response->getEtag());
        }

        // Remove any cache plugins that might be on the request to prevent infinite recursive revalidations
        $dispatcher = $revalidate->getEventDispatcher();
        foreach ($dispatcher->getListeners() as $eventName => $listeners) {
            foreach ($listeners as $listener) {
                if (is_array($listener) && $listener[0] instanceof CachePlugin) {
                    $dispatcher->removeListener($eventName, $listener);
                }
            }
        }

        return $revalidate;
    }

    /**
     * Handles a 200 response response from revalidating. The server does not support validation, so use this response.
     *
     * @param RequestInterface $request          Request that was sent
     * @param Response         $validateResponse Response received
     *
     * @return bool Returns true if valid, false if invalid
     */
    protected function handle200Response(RequestInterface $request, Response $validateResponse)
    {
        $request->setResponse($validateResponse);
        if ($this->canCache->canCacheResponse($validateResponse)) {
            $this->storage->cache($request, $validateResponse);
        }

        return false;
    }

    /**
     * Handle a 304 response and ensure that it is still valid
     *
     * @param RequestInterface $request          Request that was sent
     * @param Response         $validateResponse Response received
     * @param Response         $response         Original cached response
     *
     * @return bool Returns true if valid, false if invalid
     */
    protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response)
    {
        static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified');

        // Make sure that this response has the same ETag
        if ($validateResponse->getEtag() != $response->getEtag()) {
            return false;
        }

        // Replace cached headers with any of these headers from the
        // origin server that might be more up to date
        $modified = false;
        foreach ($replaceHeaders as $name) {
            if ($validateResponse->hasHeader($name)) {
                $modified = true;
                $response->setHeader($name, $validateResponse->getHeader($name));
            }
        }

        // Store the updated response in cache
        if ($modified && $this->canCache->canCacheResponse($response)) {
            $this->storage->cache($request, $response);
        }

        return true;
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Never performs cache revalidation and just assumes the request is invalid
 */
class DenyRevalidation extends DefaultRevalidation
{
    public function __construct() {}

    public function revalidate(RequestInterface $request, Response $response)
    {
        return false;
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Cache\CacheAdapterFactory;
use Guzzle\Cache\CacheAdapterInterface;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\Message\MessageInterface;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Default cache storage implementation
 */
class DefaultCacheStorage implements CacheStorageInterface
{
    /** @var string */
    protected $keyPrefix;

    /** @var CacheAdapterInterface Cache used to store cache data */
    protected $cache;

    /** @var int Default cache TTL */
    protected $defaultTtl;

    /**
     * @param mixed  $cache      Cache used to store cache data
     * @param string $keyPrefix  Provide an optional key prefix to prefix on all cache keys
     * @param int    $defaultTtl Default cache TTL
     */
    public function __construct($cache, $keyPrefix = '', $defaultTtl = 3600)
    {
        $this->cache = CacheAdapterFactory::fromCache($cache);
        $this->defaultTtl = $defaultTtl;
        $this->keyPrefix = $keyPrefix;
    }

    public function cache(RequestInterface $request, Response $response)
    {
        $currentTime = time();

        $overrideTtl = $request->getParams()->get('cache.override_ttl');
        if ($overrideTtl) {
            $ttl = $overrideTtl;
        } else {
            $maxAge = $response->getMaxAge();
            if ($maxAge !== null) {
                $ttl = $maxAge;
            } else {
                $ttl = $this->defaultTtl;
            }
        }

        if ($cacheControl = $response->getHeader('Cache-Control')) {
            $stale = $cacheControl->getDirective('stale-if-error');
            if ($stale === true) {
                $ttl += $ttl;
            } else if (is_numeric($stale)) {
                $ttl += $stale;
            }
        }

        // Determine which manifest key should be used
        $key = $this->getCacheKey($request);
        $persistedRequest = $this->persistHeaders($request);
        $entries = array();

        if ($manifest = $this->cache->fetch($key)) {
            // Determine which cache entries should still be in the cache
            $vary = $response->getVary();
            foreach (unserialize($manifest) as $entry) {
                // Check if the entry is expired
                if ($entry[4] < $currentTime) {
                    continue;
                }
                $entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : '';
                if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) {
                    $entries[] = $entry;
                }
            }
        }

        // Persist the response body if needed
        $bodyDigest = null;
        if ($response->getBody() && $response->getBody()->getContentLength() > 0) {
            $bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody());
            $this->cache->save($bodyDigest, (string) $response->getBody(), $ttl);
        }

        array_unshift($entries, array(
            $persistedRequest,
            $this->persistHeaders($response),
            $response->getStatusCode(),
            $bodyDigest,
            $currentTime + $ttl
        ));

        $this->cache->save($key, serialize($entries));
    }

    public function delete(RequestInterface $request)
    {
        $key = $this->getCacheKey($request);
        if ($entries = $this->cache->fetch($key)) {
            // Delete each cached body
            foreach (unserialize($entries) as $entry) {
                if ($entry[3]) {
                    $this->cache->delete($entry[3]);
                }
            }
            $this->cache->delete($key);
        }
    }

    public function purge($url)
    {
        foreach (array('GET', 'HEAD', 'POST', 'PUT', 'DELETE') as $method) {
            $this->delete(new Request($method, $url));
        }
    }

    public function fetch(RequestInterface $request)
    {
        $key = $this->getCacheKey($request);
        if (!($entries = $this->cache->fetch($key))) {
            return null;
        }

        $match = null;
        $headers = $this->persistHeaders($request);
        $entries = unserialize($entries);
        foreach ($entries as $index => $entry) {
            if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'] : '', $headers, $entry[0])) {
                $match = $entry;
                break;
            }
        }

        if (!$match) {
            return null;
        }

        // Ensure that the response is not expired
        $response = null;
        if ($match[4] < time()) {
            $response = -1;
        } else {
            $response = new Response($match[2], $match[1]);
            if ($match[3]) {
                if ($body = $this->cache->fetch($match[3])) {
                    $response->setBody($body);
                } else {
                    // The response is not valid because the body was somehow deleted
                    $response = -1;
                }
            }
        }

        if ($response === -1) {
            // Remove the entry from the metadata and update the cache
            unset($entries[$index]);
            if ($entries) {
                $this->cache->save($key, serialize($entries));
            } else {
                $this->cache->delete($key);
            }
            return null;
        }

        return $response;
    }

    /**
     * Hash a request URL into a string that returns cache metadata
     *
     * @param RequestInterface $request
     *
     * @return string
     */
    protected function getCacheKey(RequestInterface $request)
    {
        // Allow cache.key_filter to trim down the URL cache key by removing generate query string values (e.g. auth)
        if ($filter = $request->getParams()->get('cache.key_filter')) {
            $url = $request->getUrl(true);
            foreach (explode(',', $filter) as $remove) {
                $url->getQuery()->remove(trim($remove));
            }
        } else {
            $url = $request->getUrl();
        }

        return $this->keyPrefix . md5($request->getMethod() . ' ' . $url);
    }

    /**
     * Create a cache key for a response's body
     *
     * @param string              $url  URL of the entry
     * @param EntityBodyInterface $body Response body
     *
     * @return string
     */
    protected function getBodyKey($url, EntityBodyInterface $body)
    {
        return $this->keyPrefix . md5($url) . $body->getContentMd5();
    }

    /**
     * Determines whether two Request HTTP header sets are non-varying
     *
     * @param string $vary Response vary header
     * @param array  $r1   HTTP header array
     * @param array  $r2   HTTP header array
     *
     * @return bool
     */
    private function requestsMatch($vary, $r1, $r2)
    {
        if ($vary) {
            foreach (explode(',', $vary) as $header) {
                $key = trim(strtolower($header));
                $v1 = isset($r1[$key]) ? $r1[$key] : null;
                $v2 = isset($r2[$key]) ? $r2[$key] : null;
                if ($v1 !== $v2) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Creates an array of cacheable and normalized message headers
     *
     * @param MessageInterface $message
     *
     * @return array
     */
    private function persistHeaders(MessageInterface $message)
    {
        // Headers are excluded from the caching (see RFC 2616:13.5.1)
        static $noCache = array(
            'age' => true,
            'connection' => true,
            'keep-alive' => true,
            'proxy-authenticate' => true,
            'proxy-authorization' => true,
            'te' => true,
            'trailers' => true,
            'transfer-encoding' => true,
            'upgrade' => true,
            'set-cookie' => true,
            'set-cookie2' => true
        );

        // Clone the response to not destroy any necessary headers when caching
        $headers = $message->getHeaders()->getAll();
        $headers = array_diff_key($headers, $noCache);
        // Cast the headers to a string
        $headers = array_map(function ($h) { return (string) $h; }, $headers);

        return $headers;
    }
}
{
    "name": "guzzle/plugin-cache",
    "description": "Guzzle HTTP cache plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version",
        "guzzle/cache": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Cache": "" }
    },
    "target-dir": "Guzzle/Plugin/Cache",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Interface used to cache HTTP requests
 */
interface CacheStorageInterface
{
    /**
     * Get a Response from the cache for a request
     *
     * @param RequestInterface $request
     *
     * @return null|Response
     */
    public function fetch(RequestInterface $request);

    /**
     * Cache an HTTP request
     *
     * @param RequestInterface $request  Request being cached
     * @param Response         $response Response to cache
     */
    public function cache(RequestInterface $request, Response $response);

    /**
     * Deletes cache entries that match a request
     *
     * @param RequestInterface $request Request to delete from cache
     */
    public function delete(RequestInterface $request);

    /**
     * Purge all cache entries for a given URL
     *
     * @param string $url
     */
    public function purge($url);
}
<?php

namespace Guzzle\Plugin\ErrorResponse;

use Guzzle\Common\Event;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Operation;
use Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Converts generic Guzzle response exceptions into errorResponse exceptions
 */
class ErrorResponsePlugin implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('command.before_send' => array('onCommandBeforeSend', -1));
    }

    /**
     * Adds a listener to requests before they sent from a command
     *
     * @param Event $event Event emitted
     */
    public function onCommandBeforeSend(Event $event)
    {
        $command = $event['command'];
        if ($operation = $command->getOperation()) {
            if ($operation->getErrorResponses()) {
                $request = $command->getRequest();
                $request->getEventDispatcher()
                    ->addListener('request.complete', $this->getErrorClosure($request, $command, $operation));
            }
        }
    }

    /**
     * @param RequestInterface $request   Request that received an error
     * @param CommandInterface $command   Command that created the request
     * @param Operation        $operation Operation that defines the request and errors
     *
     * @return \Closure Returns a closure
     * @throws ErrorResponseException
     */
    protected function getErrorClosure(RequestInterface $request, CommandInterface $command, Operation $operation)
    {
        return function (Event $event) use ($request, $command, $operation) {
            $response = $event['response'];
            foreach ($operation->getErrorResponses() as $error) {
                if (!isset($error['class'])) {
                    continue;
                }
                if (isset($error['code']) && $response->getStatusCode() != $error['code']) {
                    continue;
                }
                if (isset($error['reason']) && $response->getReasonPhrase() != $error['reason']) {
                    continue;
                }
                $className = $error['class'];
                $errorClassInterface = __NAMESPACE__ . '\\ErrorResponseExceptionInterface';
                if (!class_exists($className)) {
                    throw new ErrorResponseException("{$className} does not exist");
                } elseif (!(in_array($errorClassInterface, class_implements($className)))) {
                    throw new ErrorResponseException("{$className} must implement {$errorClassInterface}");
                }
                throw $className::fromCommand($command, $response);
            }
        };
    }
}
<?php

namespace Guzzle\Plugin\ErrorResponse;

use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;

/**
 * Interface used to create an exception from an error response
 */
interface ErrorResponseExceptionInterface
{
    /**
     * Create an exception for a command based on a command and an error response definition
     *
     * @param CommandInterface $command  Command that was sent
     * @param Response         $response The error response
     *
     * @return self
     */
    public static function fromCommand(CommandInterface $command, Response $response);
}
<?php

namespace Guzzle\Plugin\ErrorResponse\Exception;

use Guzzle\Common\Exception\RuntimeException;

class ErrorResponseException extends RuntimeException {}
{
    "name": "guzzle/plugin-error-response",
    "description": "Guzzle errorResponse plugin for creating error exceptions based on a service description",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/service": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\ErrorResponse": "" }
    },
    "target-dir": "Guzzle/Plugin/ErrorResponse",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
{
    "name": "guzzle/plugin-mock",
    "description": "Guzzle Mock plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["mock", "plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Mock": "" }
    },
    "target-dir": "Guzzle/Plugin/Mock",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Mock;

use Guzzle\Common\Event;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Queues mock responses or exceptions and delivers mock responses or exceptions in a fifo order.
 */
class MockPlugin extends AbstractHasDispatcher implements EventSubscriberInterface, \Countable
{
    /** @var array Array of mock responses / exceptions */
    protected $queue = array();

    /** @var bool Whether or not to remove the plugin when the queue is empty */
    protected $temporary = false;

    /** @var array Array of requests that were mocked */
    protected $received = array();

    /** @var bool Whether or not to consume an entity body when a mock response is served */
    protected $readBodies;

    /**
     * @param array $items      Array of responses or exceptions to queue
     * @param bool  $temporary  Set to TRUE to remove the plugin when the queue is empty
     * @param bool  $readBodies Set to TRUE to consume the entity body when a mock is served
     */
    public function __construct(array $items = null, $temporary = false, $readBodies = false)
    {
        $this->readBodies = $readBodies;
        $this->temporary = $temporary;
        if ($items) {
            foreach ($items as $item) {
                if ($item instanceof \Exception) {
                    $this->addException($item);
                } else {
                    $this->addResponse($item);
                }
            }
        }
    }

    public static function getSubscribedEvents()
    {
        // Use a number lower than the CachePlugin
        return array('request.before_send' => array('onRequestBeforeSend', -999));
    }

    public static function getAllEvents()
    {
        return array('mock.request');
    }

    /**
     * Get a mock response from a file
     *
     * @param string $path File to retrieve a mock response from
     *
     * @return Response
     * @throws InvalidArgumentException if the file is not found
     */
    public static function getMockFile($path)
    {
        if (!file_exists($path)) {
            throw new InvalidArgumentException('Unable to open mock file: ' . $path);
        }

        return Response::fromMessage(file_get_contents($path));
    }

    /**
     * Set whether or not to consume the entity body of a request when a mock
     * response is used
     *
     * @param bool $readBodies Set to true to read and consume entity bodies
     *
     * @return self
     */
    public function readBodies($readBodies)
    {
        $this->readBodies = $readBodies;

        return $this;
    }

    /**
     * Returns the number of remaining mock responses
     *
     * @return int
     */
    public function count()
    {
        return count($this->queue);
    }

    /**
     * Add a response to the end of the queue
     *
     * @param string|Response $response Response object or path to response file
     *
     * @return MockPlugin
     * @throws InvalidArgumentException if a string or Response is not passed
     */
    public function addResponse($response)
    {
        if (!($response instanceof Response)) {
            if (!is_string($response)) {
                throw new InvalidArgumentException('Invalid response');
            }
            $response = self::getMockFile($response);
        }

        $this->queue[] = $response;

        return $this;
    }

    /**
     * Add an exception to the end of the queue
     *
     * @param CurlException $e Exception to throw when the request is executed
     *
     * @return MockPlugin
     */
    public function addException(CurlException $e)
    {
        $this->queue[] = $e;

        return $this;
    }

    /**
     * Clear the queue
     *
     * @return MockPlugin
     */
    public function clearQueue()
    {
        $this->queue = array();

        return $this;
    }

    /**
     * Returns an array of mock responses remaining in the queue
     *
     * @return array
     */
    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * Check if this is a temporary plugin
     *
     * @return bool
     */
    public function isTemporary()
    {
        return $this->temporary;
    }

    /**
     * Get a response from the front of the list and add it to a request
     *
     * @param RequestInterface $request Request to mock
     *
     * @return self
     * @throws CurlException When request.send is called and an exception is queued
     */
    public function dequeue(RequestInterface $request)
    {
        $this->dispatch('mock.request', array('plugin' => $this, 'request' => $request));

        $item = array_shift($this->queue);
        if ($item instanceof Response) {
            if ($this->readBodies && $request instanceof EntityEnclosingRequestInterface) {
                $request->getEventDispatcher()->addListener('request.sent', $f = function (Event $event) use (&$f) {
                    while ($data = $event['request']->getBody()->read(8096));
                    // Remove the listener after one-time use
                    $event['request']->getEventDispatcher()->removeListener('request.sent', $f);
                });
            }
            $request->setResponse($item);
        } elseif ($item instanceof CurlException) {
            // Emulates exceptions encountered while transferring requests
            $item->setRequest($request);
            $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $item));
            // Only throw if the exception wasn't handled
            if ($state == RequestInterface::STATE_ERROR) {
                throw $item;
            }
        }

        return $this;
    }

    /**
     * Clear the array of received requests
     */
    public function flush()
    {
        $this->received = array();
    }

    /**
     * Get an array of requests that were mocked by this plugin
     *
     * @return array
     */
    public function getReceivedRequests()
    {
        return $this->received;
    }

    /**
     * Called when a request is about to be sent
     *
     * @param Event $event
     * @throws \OutOfBoundsException When queue is empty
     */
    public function onRequestBeforeSend(Event $event)
    {
        if (!$this->queue) {
            throw new \OutOfBoundsException('Mock queue is empty');
        }

        $request = $event['request'];
        $this->received[] = $request;
        // Detach the filter from the client so it's a one-time use
        if ($this->temporary && count($this->queue) == 1 && $request->getClient()) {
            $request->getClient()->getEventDispatcher()->removeSubscriber($this);
        }
        $this->dequeue($request);
    }
}
<?php

namespace Guzzle\Plugin\Async;

use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\CurlException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sends requests but does not wait for the response
 */
class AsyncPlugin implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send'    => 'onBeforeSend',
            'request.exception'      => 'onRequestTimeout',
            'request.sent'           => 'onRequestSent',
            'curl.callback.progress' => 'onCurlProgress'
        );
    }

    /**
     * Event used to ensure that progress callback are emitted from the curl handle's request mediator.
     *
     * @param Event $event
     */
    public function onBeforeSend(Event $event)
    {
        // Ensure that progress callbacks are dispatched
        $event['request']->getCurlOptions()->set('progress', true);
    }

    /**
     * Event emitted when a curl progress function is called. When the amount of data uploaded == the amount of data to
     * upload OR any bytes have been downloaded, then time the request out after 1ms because we're done with
     * transmitting the request, and tell curl not download a body.
     *
     * @param Event $event
     */
    public function onCurlProgress(Event $event)
    {
        if ($event['handle'] &&
            ($event['downloaded'] || (isset($event['uploaded']) && $event['upload_size'] === $event['uploaded']))
        ) {
            // Timeout after 1ms
            curl_setopt($event['handle'], CURLOPT_TIMEOUT_MS, 1);
            // Even if the response is quick, tell curl not to download the body.
            // - Note that we can only perform this shortcut if the request transmitted a body so as to ensure that the
            //   request method is not converted to a HEAD request before the request was sent via curl.
            if ($event['uploaded']) {
                curl_setopt($event['handle'], CURLOPT_NOBODY, true);
            }
        }
    }

    /**
     * Event emitted when a curl exception occurs. Ignore the exception and set a mock response.
     *
     * @param Event $event
     */
    public function onRequestTimeout(Event $event)
    {
        if ($event['exception'] instanceof CurlException) {
            $event['request']->setResponse(new Response(200, array(
                'X-Guzzle-Async' => 'Did not wait for the response'
            )));
        }
    }

    /**
     * Event emitted when a request completes because it took less than 1ms. Add an X-Guzzle-Async header to notify the
     * caller that there is no body in the message.
     *
     * @param Event $event
     */
    public function onRequestSent(Event $event)
    {
        // Let the caller know this was meant to be async
        $event['request']->getResponse()->setHeader('X-Guzzle-Async', 'Did not wait for the response');
    }
}
{
    "name": "guzzle/plugin-async",
    "description": "Guzzle async request plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Async": "" }
    },
    "target-dir": "Guzzle/Plugin/Async",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\CurlAuth;

use Guzzle\Common\Event;
use Guzzle\Common\Version;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Adds specified curl auth to all requests sent from a client. Defaults to CURLAUTH_BASIC if none supplied.
 * @deprecated Use $client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');
 */
class CurlAuthPlugin implements EventSubscriberInterface
{
    private $username;
    private $password;
    private $scheme;

    /**
     * @param string $username HTTP basic auth username
     * @param string $password Password
     * @param int    $scheme   Curl auth scheme
     */
    public function __construct($username, $password, $scheme=CURLAUTH_BASIC)
    {
        Version::warn(__CLASS__ . " is deprecated. Use \$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');");
        $this->username = $username;
        $this->password = $password;
        $this->scheme = $scheme;
    }

    public static function getSubscribedEvents()
    {
        return array('client.create_request' => array('onRequestCreate', 255));
    }

    /**
     * Add basic auth
     *
     * @param Event $event
     */
    public function onRequestCreate(Event $event)
    {
        $event['request']->setAuth($this->username, $this->password, $this->scheme);
    }
}
{
    "name": "guzzle/plugin-curlauth",
    "description": "Guzzle cURL authorization plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "curl", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\CurlAuth": "" }
    },
    "target-dir": "Guzzle/Plugin/CurlAuth",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\History;

use Guzzle\Common\Event;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Maintains a list of requests and responses sent using a request or client
 */
class HistoryPlugin implements EventSubscriberInterface, \IteratorAggregate, \Countable
{
    /** @var int The maximum number of requests to maintain in the history */
    protected $limit = 10;

    /** @var array Requests and responses that have passed through the plugin */
    protected $transactions = array();

    public static function getSubscribedEvents()
    {
        return array('request.sent' => array('onRequestSent', 9999));
    }

    /**
     * Convert to a string that contains all request and response headers
     *
     * @return string
     */
    public function __toString()
    {
        $lines = array();
        foreach ($this->transactions as $entry) {
            $response = isset($entry['response']) ? $entry['response'] : '';
            $lines[] = '> ' . trim($entry['request']) . "\n\n< " . trim($response) . "\n";
        }

        return implode("\n", $lines);
    }

    /**
     * Add a request to the history
     *
     * @param RequestInterface $request  Request to add
     * @param Response         $response Response of the request
     *
     * @return HistoryPlugin
     */
    public function add(RequestInterface $request, Response $response = null)
    {
        if (!$response && $request->getResponse()) {
            $response = $request->getResponse();
        }

        $this->transactions[] = array('request' => $request, 'response' => $response);
        if (count($this->transactions) > $this->getlimit()) {
            array_shift($this->transactions);
        }

        return $this;
    }

    /**
     * Set the max number of requests to store
     *
     * @param int $limit Limit
     *
     * @return HistoryPlugin
     */
    public function setLimit($limit)
    {
        $this->limit = (int) $limit;

        return $this;
    }

    /**
     * Get the request limit
     *
     * @return int
     */
    public function getLimit()
    {
        return $this->limit;
    }

    /**
     * Get all of the raw transactions in the form of an array of associative arrays containing
     * 'request' and 'response' keys.
     *
     * @return array
     */
    public function getAll()
    {
        return $this->transactions;
    }

    /**
     * Get the requests in the history
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        // Return an iterator just like the old iteration of the HistoryPlugin for BC compatibility (use getAll())
        return new \ArrayIterator(array_map(function ($entry) {
            $entry['request']->getParams()->set('actual_response', $entry['response']);
            return $entry['request'];
        }, $this->transactions));
    }

    /**
     * Get the number of requests in the history
     *
     * @return int
     */
    public function count()
    {
        return count($this->transactions);
    }

    /**
     * Get the last request sent
     *
     * @return RequestInterface
     */
    public function getLastRequest()
    {
        $last = end($this->transactions);

        return $last['request'];
    }

    /**
     * Get the last response in the history
     *
     * @return Response|null
     */
    public function getLastResponse()
    {
        $last = end($this->transactions);

        return isset($last['response']) ? $last['response'] : null;
    }

    /**
     * Clears the history
     *
     * @return HistoryPlugin
     */
    public function clear()
    {
        $this->transactions = array();

        return $this;
    }

    public function onRequestSent(Event $event)
    {
        $this->add($event['request'], $event['response']);
    }
}
{
    "name": "guzzle/plugin-history",
    "description": "Guzzle history plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\History": "" }
    },
    "target-dir": "Guzzle/Plugin/History",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Log;

use Guzzle\Common\Event;
use Guzzle\Log\LogAdapterInterface;
use Guzzle\Log\MessageFormatter;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Plugin class that will add request and response logging to an HTTP request.
 *
 * The log plugin uses a message formatter that allows custom messages via template variable substitution.
 *
 * @see MessageLogger for a list of available log template variable substitutions
 */
class LogPlugin implements EventSubscriberInterface
{
    /** @var LogAdapterInterface Adapter responsible for writing log data */
    protected $logAdapter;

    /** @var MessageFormatter Formatter used to format messages before logging */
    protected $formatter;

    /** @var bool Whether or not to wire request and response bodies */
    protected $wireBodies;

    /**
     * @param LogAdapterInterface     $logAdapter Adapter object used to log message
     * @param string|MessageFormatter $formatter  Formatter used to format log messages or the formatter template
     * @param bool                    $wireBodies Set to true to track request and response bodies using a temporary
     *                                            buffer if the bodies are not repeatable.
     */
    public function __construct(
        LogAdapterInterface $logAdapter,
        $formatter = null,
        $wireBodies = false
    ) {
        $this->logAdapter = $logAdapter;
        $this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter);
        $this->wireBodies = $wireBodies;
    }

    /**
     * Get a log plugin that outputs full request, response, and curl error information to stderr
     *
     * @param bool     $wireBodies Set to false to disable request/response body output when they use are not repeatable
     * @param resource $stream     Stream to write to when logging. Defaults to STDERR when it is available
     *
     * @return self
     */
    public static function getDebugPlugin($wireBodies = true, $stream = null)
    {
        if ($stream === null) {
            if (defined('STDERR')) {
                $stream = STDERR;
            } else {
                $stream = fopen('php://output', 'w');
            }
        }

        return new self(new ClosureLogAdapter(function ($m) use ($stream) {
            fwrite($stream, $m . PHP_EOL);
        }), "# Request:\n{request}\n\n# Response:\n{response}\n\n# Errors: {curl_code} {curl_error}", $wireBodies);
    }

    public static function getSubscribedEvents()
    {
        return array(
            'curl.callback.write' => array('onCurlWrite', 255),
            'curl.callback.read'  => array('onCurlRead', 255),
            'request.before_send' => array('onRequestBeforeSend', 255),
            'request.sent'        => array('onRequestSent', 255)
        );
    }

    /**
     * Event triggered when curl data is read from a request
     *
     * @param Event $event
     */
    public function onCurlRead(Event $event)
    {
        // Stream the request body to the log if the body is not repeatable
        if ($wire = $event['request']->getParams()->get('request_wire')) {
            $wire->write($event['read']);
        }
    }

    /**
     * Event triggered when curl data is written to a response
     *
     * @param Event $event
     */
    public function onCurlWrite(Event $event)
    {
        // Stream the response body to the log if the body is not repeatable
        if ($wire = $event['request']->getParams()->get('response_wire')) {
            $wire->write($event['write']);
        }
    }

    /**
     * Called before a request is sent
     *
     * @param Event $event
     */
    public function onRequestBeforeSend(Event $event)
    {
        if ($this->wireBodies) {
            $request = $event['request'];
            // Ensure that curl IO events are emitted
            $request->getCurlOptions()->set('emit_io', true);
            // We need to make special handling for content wiring and non-repeatable streams.
            if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
                && (!$request->getBody()->isSeekable() || !$request->getBody()->isReadable())
            ) {
                // The body of the request cannot be recalled so logging the body will require us to buffer it
                $request->getParams()->set('request_wire', EntityBody::factory());
            }
            if (!$request->getResponseBody()->isRepeatable()) {
                // The body of the response cannot be recalled so logging the body will require us to buffer it
                $request->getParams()->set('response_wire', EntityBody::factory());
            }
        }
    }

    /**
     * Triggers the actual log write when a request completes
     *
     * @param Event $event
     */
    public function onRequestSent(Event $event)
    {
        $request = $event['request'];
        $response = $event['response'];
        $handle = $event['handle'];

        if ($wire = $request->getParams()->get('request_wire')) {
            $request = clone $request;
            $request->setBody($wire);
        }

        if ($wire = $request->getParams()->get('response_wire')) {
            $response = clone $response;
            $response->setBody($wire);
        }

        // Send the log message to the adapter, adding a category and host
        $priority = $response && $response->isError() ? LOG_ERR : LOG_DEBUG;
        $message = $this->formatter->format($request, $response, $handle);
        $this->logAdapter->log($message, $priority, array(
            'request'  => $request,
            'response' => $response,
            'handle'   => $handle
        ));
    }
}
{
    "name": "guzzle/plugin-log",
    "description": "Guzzle log plugin for over the wire logging",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "log", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version",
        "guzzle/log": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Log": "" }
    },
    "target-dir": "Guzzle/Plugin/Log",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Plugin\Cookie;

use Guzzle\Common\Event;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
use Guzzle\Plugin\Cookie\CookieJar\CookieJarInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Adds, extracts, and persists cookies between HTTP requests
 */
class CookiePlugin implements EventSubscriberInterface
{
    /** @var CookieJarInterface Cookie cookieJar used to hold cookies */
    protected $cookieJar;

    /**
     * @param CookieJarInterface $cookieJar Cookie jar used to hold cookies. Creates an ArrayCookieJar by default.
     */
    public function __construct(CookieJarInterface $cookieJar = null)
    {
        $this->cookieJar = $cookieJar ?: new ArrayCookieJar();
    }

    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send' => array('onRequestBeforeSend', 125),
            'request.sent'        => array('onRequestSent', 125)
        );
    }

    /**
     * Get the cookie cookieJar
     *
     * @return CookieJarInterface
     */
    public function getCookieJar()
    {
        return $this->cookieJar;
    }

    /**
     * Add cookies before a request is sent
     *
     * @param Event $event
     */
    public function onRequestBeforeSend(Event $event)
    {
        $request = $event['request'];
        if (!$request->getParams()->get('cookies.disable')) {
            $request->removeHeader('Cookie');
            // Find cookies that match this request
            foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) {
                $request->addCookie($cookie->getName(), $cookie->getValue());
            }
        }
    }

    /**
     * Extract cookies from a sent request
     *
     * @param Event $event
     */
    public function onRequestSent(Event $event)
    {
        $this->cookieJar->addCookiesFromResponse($event['response'], $event['request']);
    }
}
<?php

namespace Guzzle\Plugin\Cookie;

use Guzzle\Common\ToArrayInterface;

/**
 * Set-Cookie object
 */
class Cookie implements ToArrayInterface
{
    /** @var array Cookie data */
    protected $data;

    /**
     * @var string ASCII codes not valid for for use in a cookie name
     *
     * Cookie names are defined as 'token', according to RFC 2616, Section 2.2
     * A valid token may contain any CHAR except CTLs (ASCII 0 - 31 or 127)
     * or any of the following separators
     */
    protected static $invalidCharString;

    /**
     * Gets an array of invalid cookie characters
     *
     * @return array
     */
    protected static function getInvalidCharacters()
    {
        if (!self::$invalidCharString) {
            self::$invalidCharString = implode('', array_map('chr', array_merge(
                range(0, 32),
                array(34, 40, 41, 44, 47),
                array(58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 123, 125, 127)
            )));
        }

        return self::$invalidCharString;
    }

    /**
     * @param array $data Array of cookie data provided by a Cookie parser
     */
    public function __construct(array $data = array())
    {
        static $defaults = array(
            'name'        => '',
            'value'       => '',
            'domain'      => '',
            'path'        => '/',
            'expires'     => null,
            'max_age'     => 0,
            'comment'     => null,
            'comment_url' => null,
            'port'        => array(),
            'version'     => null,
            'secure'      => false,
            'discard'     => false,
            'http_only'   => false
        );

        $this->data = array_merge($defaults, $data);
        // Extract the expires value and turn it into a UNIX timestamp if needed
        if (!$this->getExpires() && $this->getMaxAge()) {
            // Calculate the expires date
            $this->setExpires(time() + (int) $this->getMaxAge());
        } elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
            $this->setExpires(strtotime($this->getExpires()));
        }
    }

    /**
     * Get the cookie as an array
     *
     * @return array
     */
    public function toArray()
    {
        return $this->data;
    }

    /**
     * Get the cookie name
     *
     * @return string
     */
    public function getName()
    {
        return $this->data['name'];
    }

    /**
     * Set the cookie name
     *
     * @param string $name Cookie name
     *
     * @return Cookie
     */
    public function setName($name)
    {
        return $this->setData('name', $name);
    }

    /**
     * Get the cookie value
     *
     * @return string
     */
    public function getValue()
    {
        return $this->data['value'];
    }

    /**
     * Set the cookie value
     *
     * @param string $value Cookie value
     *
     * @return Cookie
     */
    public function setValue($value)
    {
        return $this->setData('value', $value);
    }

    /**
     * Get the domain
     *
     * @return string|null
     */
    public function getDomain()
    {
        return $this->data['domain'];
    }

    /**
     * Set the domain of the cookie
     *
     * @param string $domain
     *
     * @return Cookie
     */
    public function setDomain($domain)
    {
        return $this->setData('domain', $domain);
    }

    /**
     * Get the path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->data['path'];
    }

    /**
     * Set the path of the cookie
     *
     * @param string $path Path of the cookie
     *
     * @return Cookie
     */
    public function setPath($path)
    {
        return $this->setData('path', $path);
    }

    /**
     * Maximum lifetime of the cookie in seconds
     *
     * @return int|null
     */
    public function getMaxAge()
    {
        return $this->data['max_age'];
    }

    /**
     * Set the max-age of the cookie
     *
     * @param int $maxAge Max age of the cookie in seconds
     *
     * @return Cookie
     */
    public function setMaxAge($maxAge)
    {
        return $this->setData('max_age', $maxAge);
    }

    /**
     * The UNIX timestamp when the cookie expires
     *
     * @return mixed
     */
    public function getExpires()
    {
        return $this->data['expires'];
    }

    /**
     * Set the unix timestamp for which the cookie will expire
     *
     * @param int $timestamp Unix timestamp
     *
     * @return Cookie
     */
    public function setExpires($timestamp)
    {
        return $this->setData('expires', $timestamp);
    }

    /**
     * Version of the cookie specification. RFC 2965 is 1
     *
     * @return mixed
     */
    public function getVersion()
    {
        return $this->data['version'];
    }

    /**
     * Set the cookie version
     *
     * @param string|int $version Version to set
     *
     * @return Cookie
     */
    public function setVersion($version)
    {
        return $this->setData('version', $version);
    }

    /**
     * Get whether or not this is a secure cookie
     *
     * @return null|bool
     */
    public function getSecure()
    {
        return $this->data['secure'];
    }

    /**
     * Set whether or not the cookie is secure
     *
     * @param bool $secure Set to true or false if secure
     *
     * @return Cookie
     */
    public function setSecure($secure)
    {
        return $this->setData('secure', (bool) $secure);
    }

    /**
     * Get whether or not this is a session cookie
     *
     * @return null|bool
     */
    public function getDiscard()
    {
        return $this->data['discard'];
    }

    /**
     * Set whether or not this is a session cookie
     *
     * @param bool $discard Set to true or false if this is a session cookie
     *
     * @return Cookie
     */
    public function setDiscard($discard)
    {
        return $this->setData('discard', $discard);
    }

    /**
     * Get the comment
     *
     * @return string|null
     */
    public function getComment()
    {
        return $this->data['comment'];
    }

    /**
     * Set the comment of the cookie
     *
     * @param string $comment Cookie comment
     *
     * @return Cookie
     */
    public function setComment($comment)
    {
        return $this->setData('comment', $comment);
    }

    /**
     * Get the comment URL of the cookie
     *
     * @return string|null
     */
    public function getCommentUrl()
    {
        return $this->data['comment_url'];
    }

    /**
     * Set the comment URL of the cookie
     *
     * @param string $commentUrl Cookie comment URL for more information
     *
     * @return Cookie
     */
    public function setCommentUrl($commentUrl)
    {
        return $this->setData('comment_url', $commentUrl);
    }

    /**
     * Get an array of acceptable ports this cookie can be used with
     *
     * @return array
     */
    public function getPorts()
    {
        return $this->data['port'];
    }

    /**
     * Set a list of acceptable ports this cookie can be used with
     *
     * @param array $ports Array of acceptable ports
     *
     * @return Cookie
     */
    public function setPorts(array $ports)
    {
        return $this->setData('port', $ports);
    }

    /**
     * Get whether or not this is an HTTP only cookie
     *
     * @return bool
     */
    public function getHttpOnly()
    {
        return $this->data['http_only'];
    }

    /**
     * Set whether or not this is an HTTP only cookie
     *
     * @param bool $httpOnly Set to true or false if this is HTTP only
     *
     * @return Cookie
     */
    public function setHttpOnly($httpOnly)
    {
        return $this->setData('http_only', $httpOnly);
    }

    /**
     * Get an array of extra cookie data
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->data['data'];
    }

    /**
     * Get a specific data point from the extra cookie data
     *
     * @param string $name Name of the data point to retrieve
     *
     * @return null|string
     */
    public function getAttribute($name)
    {
        return array_key_exists($name, $this->data['data']) ? $this->data['data'][$name] : null;
    }

    /**
     * Set a cookie data attribute
     *
     * @param string $name  Name of the attribute to set
     * @param string $value Value to set
     *
     * @return Cookie
     */
    public function setAttribute($name, $value)
    {
        $this->data['data'][$name] = $value;

        return $this;
    }

    /**
     * Check if the cookie matches a path value
     *
     * @param string $path Path to check against
     *
     * @return bool
     */
    public function matchesPath($path)
    {
        // RFC6265 http://tools.ietf.org/search/rfc6265#section-5.1.4
        // A request-path path-matches a given cookie-path if at least one of
        // the following conditions holds:

        // o  The cookie-path and the request-path are identical.
        if ($path == $this->getPath()) {
            return true;
        }

        $pos = stripos($path, $this->getPath());
        if ($pos === 0) {
            // o  The cookie-path is a prefix of the request-path, and the last
            // character of the cookie-path is %x2F ("/").
            if (substr($this->getPath(), -1, 1) === "/") {
                return true;
            }

            // o  The cookie-path is a prefix of the request-path, and the first
            // character of the request-path that is not included in the cookie-
            // path is a %x2F ("/") character.
            if (substr($path, strlen($this->getPath()), 1) === "/") {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if the cookie matches a domain value
     *
     * @param string $domain Domain to check against
     *
     * @return bool
     */
    public function matchesDomain($domain)
    {
        // Remove the leading '.' as per spec in RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.2.3
        $cookieDomain = ltrim($this->getDomain(), '.');

        // Domain not set or exact match.
        if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
            return true;
        }

        // Matching the subdomain according to RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.1.3
        if (filter_var($domain, FILTER_VALIDATE_IP)) {
            return false;
        }

        return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/i', $domain);
    }

    /**
     * Check if the cookie is compatible with a specific port
     *
     * @param int $port Port to check
     *
     * @return bool
     */
    public function matchesPort($port)
    {
        return count($this->getPorts()) == 0 || in_array($port, $this->getPorts());
    }

    /**
     * Check if the cookie is expired
     *
     * @return bool
     */
    public function isExpired()
    {
        return $this->getExpires() && time() > $this->getExpires();
    }

    /**
     * Check if the cookie is valid according to RFC 6265
     *
     * @return bool|string Returns true if valid or an error message if invalid
     */
    public function validate()
    {
        // Names must not be empty, but can be 0
        $name = $this->getName();
        if (empty($name) && !is_numeric($name)) {
            return 'The cookie name must not be empty';
        }

        // Check if any of the invalid characters are present in the cookie name
        if (strpbrk($name, self::getInvalidCharacters()) !== false) {
            return 'The cookie name must not contain invalid characters: ' . $name;
        }

        // Value must not be empty, but can be 0
        $value = $this->getValue();
        if (empty($value) && !is_numeric($value)) {
            return 'The cookie value must not be empty';
        }

        // Domains must not be empty, but can be 0
        // A "0" is not a valid internet domain, but may be used as server name in a private network
        $domain = $this->getDomain();
        if (empty($domain) && !is_numeric($domain)) {
            return 'The cookie domain must not be empty';
        }

        return true;
    }

    /**
     * Set a value and return the cookie object
     *
     * @param string $key   Key to set
     * @param string $value Value to set
     *
     * @return Cookie
     */
    private function setData($key, $value)
    {
        $this->data[$key] = $value;

        return $this;
    }
}
<?php

namespace Guzzle\Plugin\Cookie\CookieJar;

use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Parser\ParserRegistry;
use Guzzle\Plugin\Cookie\Exception\InvalidCookieException;

/**
 * Cookie cookieJar that stores cookies an an array
 */
class ArrayCookieJar implements CookieJarInterface, \Serializable
{
    /** @var array Loaded cookie data */
    protected $cookies = array();

    /** @var bool Whether or not strict mode is enabled. When enabled, exceptions will be thrown for invalid cookies */
    protected $strictMode;

    /**
     * @param bool $strictMode Set to true to throw exceptions when invalid cookies are added to the cookie jar
     */
    public function __construct($strictMode = false)
    {
        $this->strictMode = $strictMode;
    }

    /**
     * Enable or disable strict mode on the cookie jar
     *
     * @param bool $strictMode Set to true to throw exceptions when invalid cookies are added. False to ignore them.
     *
     * @return self
     */
    public function setStrictMode($strictMode)
    {
        $this->strictMode = $strictMode;
    }

    public function remove($domain = null, $path = null, $name = null)
    {
        $cookies = $this->all($domain, $path, $name, false, false);
        $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($cookies) {
            return !in_array($cookie, $cookies, true);
        });

        return $this;
    }

    public function removeTemporary()
    {
        $this->cookies = array_filter($this->cookies, function (Cookie $cookie) {
            return !$cookie->getDiscard() && $cookie->getExpires();
        });

        return $this;
    }

    public function removeExpired()
    {
        $currentTime = time();
        $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($currentTime) {
            return !$cookie->getExpires() || $currentTime < $cookie->getExpires();
        });

        return $this;
    }

    public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true)
    {
        return array_values(array_filter($this->cookies, function (Cookie $cookie) use (
            $domain,
            $path,
            $name,
            $skipDiscardable,
            $skipExpired
        ) {
            return false === (($name && $cookie->getName() != $name) ||
                ($skipExpired && $cookie->isExpired()) ||
                ($skipDiscardable && ($cookie->getDiscard() || !$cookie->getExpires())) ||
                ($path && !$cookie->matchesPath($path)) ||
                ($domain && !$cookie->matchesDomain($domain)));
        }));
    }

    public function add(Cookie $cookie)
    {
        // Only allow cookies with set and valid domain, name, value
        $result = $cookie->validate();
        if ($result !== true) {
            if ($this->strictMode) {
                throw new InvalidCookieException($result);
            } else {
                $this->removeCookieIfEmpty($cookie);
                return false;
            }
        }

        // Resolve conflicts with previously set cookies
        foreach ($this->cookies as $i => $c) {

            // Two cookies are identical, when their path, domain, port and name are identical
            if ($c->getPath() != $cookie->getPath() ||
                $c->getDomain() != $cookie->getDomain() ||
                $c->getPorts() != $cookie->getPorts() ||
                $c->getName() != $cookie->getName()
            ) {
                continue;
            }

            // The previously set cookie is a discard cookie and this one is not so allow the new cookie to be set
            if (!$cookie->getDiscard() && $c->getDiscard()) {
                unset($this->cookies[$i]);
                continue;
            }

            // If the new cookie's expiration is further into the future, then replace the old cookie
            if ($cookie->getExpires() > $c->getExpires()) {
                unset($this->cookies[$i]);
                continue;
            }

            // If the value has changed, we better change it
            if ($cookie->getValue() !== $c->getValue()) {
                unset($this->cookies[$i]);
                continue;
            }

            // The cookie exists, so no need to continue
            return false;
        }

        $this->cookies[] = $cookie;

        return true;
    }

    /**
     * Serializes the cookie cookieJar
     *
     * @return string
     */
    public function serialize()
    {
        // Only serialize long term cookies and unexpired cookies
        return json_encode(array_map(function (Cookie $cookie) {
            return $cookie->toArray();
        }, $this->all(null, null, null, true, true)));
    }

    /**
     * Unserializes the cookie cookieJar
     */
    public function unserialize($data)
    {
        $data = json_decode($data, true);
        if (empty($data)) {
            $this->cookies = array();
        } else {
            $this->cookies = array_map(function (array $cookie) {
                return new Cookie($cookie);
            }, $data);
        }
    }

    /**
     * Returns the total number of stored cookies
     *
     * @return int
     */
    public function count()
    {
        return count($this->cookies);
    }

    /**
     * Returns an iterator
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->cookies);
    }

    public function addCookiesFromResponse(Response $response, RequestInterface $request = null)
    {
        if ($cookieHeader = $response->getHeader('Set-Cookie')) {
            $parser = ParserRegistry::getInstance()->getParser('cookie');
            foreach ($cookieHeader as $cookie) {
                if ($parsed = $request
                    ? $parser->parseCookie($cookie, $request->getHost(), $request->getPath())
                    : $parser->parseCookie($cookie)
                ) {
                    // Break up cookie v2 into multiple cookies
                    foreach ($parsed['cookies'] as $key => $value) {
                        $row = $parsed;
                        $row['name'] = $key;
                        $row['value'] = $value;
                        unset($row['cookies']);
                        $this->add(new Cookie($row));
                    }
                }
            }
        }
    }

    public function getMatchingCookies(RequestInterface $request)
    {
        // Find cookies that match this request
        $cookies = $this->all($request->getHost(), $request->getPath());
        // Remove ineligible cookies
        foreach ($cookies as $index => $cookie) {
            if (!$cookie->matchesPort($request->getPort()) || ($cookie->getSecure() && $request->getScheme() != 'https')) {
                unset($cookies[$index]);
            }
        };

        return $cookies;
    }

    /**
     * If a cookie already exists and the server asks to set it again with a null value, the
     * cookie must be deleted.
     *
     * @param \Guzzle\Plugin\Cookie\Cookie $cookie
     */
    private function removeCookieIfEmpty(Cookie $cookie)
    {
        $cookieValue = $cookie->getValue();
        if ($cookieValue === null || $cookieValue === '') {
            $this->remove($cookie->getDomain(), $cookie->getPath(), $cookie->getName());
        }
    }
}
<?php

namespace Guzzle\Plugin\Cookie\CookieJar;

use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Interface for persisting cookies
 */
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
    /**
     * Remove cookies currently held in the Cookie cookieJar.
     *
     * Invoking this method without arguments will empty the whole Cookie cookieJar.  If given a $domain argument only
     * cookies belonging to that domain will be removed. If given a $domain and $path argument, cookies belonging to
     * the specified path within that domain are removed. If given all three arguments, then the cookie with the
     * specified name, path and domain is removed.
     *
     * @param string $domain Set to clear only cookies matching a domain
     * @param string $path   Set to clear only cookies matching a domain and path
     * @param string $name   Set to clear only cookies matching a domain, path, and name
     *
     * @return CookieJarInterface
     */
    public function remove($domain = null, $path = null, $name = null);

    /**
     * Discard all temporary cookies.
     *
     * Scans for all cookies in the cookieJar with either no expire field or a true discard flag. To be called when the
     * user agent shuts down according to RFC 2965.
     *
     * @return CookieJarInterface
     */
    public function removeTemporary();

    /**
     * Delete any expired cookies
     *
     * @return CookieJarInterface
     */
    public function removeExpired();

    /**
     * Add a cookie to the cookie cookieJar
     *
     * @param Cookie $cookie Cookie to add
     *
     * @return bool Returns true on success or false on failure
     */
    public function add(Cookie $cookie);

    /**
     * Add cookies from a {@see Guzzle\Http\Message\Response} object
     *
     * @param Response         $response Response object
     * @param RequestInterface $request  Request that received the response
     */
    public function addCookiesFromResponse(Response $response, RequestInterface $request = null);

    /**
     * Get cookies matching a request object
     *
     * @param RequestInterface $request Request object to match
     *
     * @return array
     */
    public function getMatchingCookies(RequestInterface $request);

    /**
     * Get all of the matching cookies
     *
     * @param string $domain          Domain of the cookie
     * @param string $path            Path of the cookie
     * @param string $name            Name of the cookie
     * @param bool   $skipDiscardable Set to TRUE to skip cookies with the Discard attribute.
     * @param bool   $skipExpired     Set to FALSE to include expired
     *
     * @return array Returns an array of Cookie objects
     */
    public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true);
}
<?php

namespace Guzzle\Plugin\Cookie\CookieJar;

use Guzzle\Common\Exception\RuntimeException;

/**
 * Persists non-session cookies using a JSON formatted file
 */
class FileCookieJar extends ArrayCookieJar
{
    /** @var string filename */
    protected $filename;

    /**
     * Create a new FileCookieJar object
     *
     * @param string $cookieFile File to store the cookie data
     *
     * @throws RuntimeException if the file cannot be found or created
     */
    public function __construct($cookieFile)
    {
        $this->filename = $cookieFile;
        $this->load();
    }

    /**
     * Saves the file when shutting down
     */
    public function __destruct()
    {
        $this->persist();
    }

    /**
     * Save the contents of the data array to the file
     *
     * @throws RuntimeException if the file cannot be found or created
     */
    protected function persist()
    {
        if (false === file_put_contents($this->filename, $this->serialize())) {
            // @codeCoverageIgnoreStart
            throw new RuntimeException('Unable to open file ' . $this->filename);
            // @codeCoverageIgnoreEnd
        }
    }

    /**
     * Load the contents of the json formatted file into the data array and discard any unsaved state
     */
    protected function load()
    {
        $json = file_get_contents($this->filename);
        if (false === $json) {
            // @codeCoverageIgnoreStart
            throw new RuntimeException('Unable to open file ' . $this->filename);
            // @codeCoverageIgnoreEnd
        }

        $this->unserialize($json);
        $this->cookies = $this->cookies ?: array();
    }
}
<?php

namespace Guzzle\Plugin\Cookie\Exception;

use Guzzle\Common\Exception\InvalidArgumentException;

class InvalidCookieException extends InvalidArgumentException {}
{
    "name": "guzzle/plugin-cookie",
    "description": "Guzzle cookie plugin",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["plugin", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin\\Cookie": "" }
    },
    "target-dir": "Guzzle/Plugin/Cookie",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
{
    "name": "guzzle/plugin",
    "description": "Guzzle plugin component containing all Guzzle HTTP plugins",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["http", "client", "plugin", "extension", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/http": "self.version"
    },
    "suggest": {
        "guzzle/cache": "self.version",
        "guzzle/log": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Plugin": "" }
    },
    "target-dir": "Guzzle/Plugin",
    "replace": {
        "guzzle/plugin-async": "self.version",
        "guzzle/plugin-backoff": "self.version",
        "guzzle/plugin-cache": "self.version",
        "guzzle/plugin-cookie": "self.version",
        "guzzle/plugin-curlauth": "self.version",
        "guzzle/plugin-error-response": "self.version",
        "guzzle/plugin-history": "self.version",
        "guzzle/plugin-log": "self.version",
        "guzzle/plugin-md5": "self.version",
        "guzzle/plugin-mock": "self.version",
        "guzzle/plugin-oauth": "self.version"
    },
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Inflection;

/**
 * Decorator used to add memoization to previously inflected words
 */
class MemoizingInflector implements InflectorInterface
{
    /** @var array Array of cached inflections */
    protected $cache = array(
        'snake' => array(),
        'camel' => array()
    );

    /** @var int Max entries per cache */
    protected $maxCacheSize;

    /** @var InflectorInterface Decorated inflector */
    protected $decoratedInflector;

    /**
     * @param InflectorInterface $inflector    Inflector being decorated
     * @param int                $maxCacheSize Maximum number of cached items to hold per cache
     */
    public function __construct(InflectorInterface $inflector, $maxCacheSize = 500)
    {
        $this->decoratedInflector = $inflector;
        $this->maxCacheSize = $maxCacheSize;
    }

    public function snake($word)
    {
        if (!isset($this->cache['snake'][$word])) {
            $this->pruneCache('snake');
            $this->cache['snake'][$word] = $this->decoratedInflector->snake($word);
        }

        return $this->cache['snake'][$word];
    }

    /**
     * Converts strings from snake_case to upper CamelCase
     *
     * @param string $word Value to convert into upper CamelCase
     *
     * @return string
     */
    public function camel($word)
    {
        if (!isset($this->cache['camel'][$word])) {
            $this->pruneCache('camel');
            $this->cache['camel'][$word] = $this->decoratedInflector->camel($word);
        }

        return $this->cache['camel'][$word];
    }

    /**
     * Prune one of the named caches by removing 20% of the cache if it is full
     *
     * @param string $cache Type of cache to prune
     */
    protected function pruneCache($cache)
    {
        if (count($this->cache[$cache]) == $this->maxCacheSize) {
            $this->cache[$cache] = array_slice($this->cache[$cache], $this->maxCacheSize * 0.2);
        }
    }
}
<?php

namespace Guzzle\Inflection;

/**
 * Decorator used to add pre-computed inflection mappings to an inflector
 */
class PreComputedInflector implements InflectorInterface
{
    /** @var array Array of pre-computed inflections */
    protected $mapping = array(
        'snake' => array(),
        'camel' => array()
    );

    /** @var InflectorInterface Decorated inflector */
    protected $decoratedInflector;

    /**
     * @param InflectorInterface $inflector Inflector being decorated
     * @param array              $snake     Hash of pre-computed camel to snake
     * @param array              $camel     Hash of pre-computed snake to camel
     * @param bool               $mirror    Mirror snake and camel reflections
     */
    public function __construct(InflectorInterface $inflector, array $snake = array(), array $camel = array(), $mirror = false)
    {
        if ($mirror) {
            $camel = array_merge(array_flip($snake), $camel);
            $snake = array_merge(array_flip($camel), $snake);
        }

        $this->decoratedInflector = $inflector;
        $this->mapping = array(
            'snake' => $snake,
            'camel' => $camel
        );
    }

    public function snake($word)
    {
        return isset($this->mapping['snake'][$word])
            ? $this->mapping['snake'][$word]
            : $this->decoratedInflector->snake($word);
    }

    /**
     * Converts strings from snake_case to upper CamelCase
     *
     * @param string $word Value to convert into upper CamelCase
     *
     * @return string
     */
    public function camel($word)
    {
        return isset($this->mapping['camel'][$word])
            ? $this->mapping['camel'][$word]
            : $this->decoratedInflector->camel($word);
    }
}
<?php

namespace Guzzle\Inflection;

/**
 * Inflector interface used to convert the casing of words
 */
interface InflectorInterface
{
    /**
     * Converts strings from camel case to snake case (e.g. CamelCase camel_case).
     *
     * @param string $word Word to convert to snake case
     *
     * @return string
     */
    public function snake($word);

    /**
     * Converts strings from snake_case to upper CamelCase
     *
     * @param string $word Value to convert into upper CamelCase
     *
     * @return string
     */
    public function camel($word);
}
{
    "name": "guzzle/inflection",
    "description": "Guzzle inflection component",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["inflection", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Inflection": "" }
    },
    "target-dir": "Guzzle/Inflection",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Inflection;

/**
 * Default inflection implementation
 */
class Inflector implements InflectorInterface
{
    /** @var InflectorInterface */
    protected static $default;

    /**
     * Get the default inflector object that has support for caching
     *
     * @return MemoizingInflector
     */
    public static function getDefault()
    {
        // @codeCoverageIgnoreStart
        if (!self::$default) {
            self::$default = new MemoizingInflector(new self());
        }
        // @codeCoverageIgnoreEnd

        return self::$default;
    }

    public function snake($word)
    {
        return ctype_lower($word) ? $word : strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", $word));
    }

    public function camel($word)
    {
        return str_replace(' ', '', ucwords(strtr($word, '_-', '  ')));
    }
}
<?php

namespace Guzzle\Parser;

/**
 * Registry of parsers used by the application
 */
class ParserRegistry
{
    /** @var ParserRegistry Singleton instance */
    protected static $instance;

    /** @var array Array of parser instances */
    protected $instances = array();

    /** @var array Mapping of parser name to default class */
    protected $mapping = array(
        'message'      => 'Guzzle\\Parser\\Message\\MessageParser',
        'cookie'       => 'Guzzle\\Parser\\Cookie\\CookieParser',
        'url'          => 'Guzzle\\Parser\\Url\\UrlParser',
        'uri_template' => 'Guzzle\\Parser\\UriTemplate\\UriTemplate',
    );

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new static;
        }

        return self::$instance;
    }

    public function __construct()
    {
        // Use the PECL URI template parser if available
        if (extension_loaded('uri_template')) {
            $this->mapping['uri_template'] = 'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate';
        }
    }

    /**
     * Get a parser by name from an instance
     *
     * @param string $name Name of the parser to retrieve
     *
     * @return mixed|null
     */
    public function getParser($name)
    {
        if (!isset($this->instances[$name])) {
            if (!isset($this->mapping[$name])) {
                return null;
            }
            $class = $this->mapping[$name];
            $this->instances[$name] = new $class();
        }

        return $this->instances[$name];
    }

    /**
     * Register a custom parser by name with the register
     *
     * @param string $name   Name or handle of the parser to register
     * @param mixed  $parser Instantiated parser to register
     */
    public function registerParser($name, $parser)
    {
        $this->instances[$name] = $parser;
    }
}
<?php

namespace Guzzle\Parser\Message;

/**
 * HTTP message parser interface used to parse HTTP messages into an array
 */
interface MessageParserInterface
{
    /**
     * Parse an HTTP request message into an associative array of parts.
     *
     * @param string $message HTTP request to parse
     *
     * @return array|bool Returns false if the message is invalid
     */
    public function parseRequest($message);

    /**
     * Parse an HTTP response message into an associative array of parts.
     *
     * @param string $message HTTP response to parse
     *
     * @return array|bool Returns false if the message is invalid
     */
    public function parseResponse($message);
}
<?php

namespace Guzzle\Parser\Message;

/**
 * Pecl HTTP message parser
 */
class PeclHttpMessageParser extends AbstractMessageParser
{
    public function parseRequest($message)
    {
        if (!$message) {
            return false;
        }

        $parts = http_parse_message($message);

        $parsed = array(
            'method'   => $parts->requestMethod,
            'protocol' => 'HTTP',
            'version'  => number_format($parts->httpVersion, 1),
            'headers'  => $parts->headers,
            'body'     => $parts->body
        );

        $parsed['request_url'] = $this->getUrlPartsFromMessage($parts->requestUrl, $parsed);

        return $parsed;
    }

    public function parseResponse($message)
    {
        if (!$message) {
            return false;
        }

        $parts = http_parse_message($message);

        return array(
            'protocol'      => 'HTTP',
            'version'       => number_format($parts->httpVersion, 1),
            'code'          => $parts->responseCode,
            'reason_phrase' => $parts->responseStatus,
            'headers'       => $parts->headers,
            'body'          => $parts->body
        );
    }
}
<?php

namespace Guzzle\Parser\Message;

/**
 * Implements shared message parsing functionality
 */
abstract class AbstractMessageParser implements MessageParserInterface
{
    /**
     * Create URL parts from HTTP message parts
     *
     * @param string $requestUrl Associated URL
     * @param array  $parts      HTTP message parts
     *
     * @return array
     */
    protected function getUrlPartsFromMessage($requestUrl, array $parts)
    {
        // Parse the URL information from the message
        $urlParts = array(
            'path'   => $requestUrl,
            'scheme' => 'http'
        );

        // Check for the Host header
        if (isset($parts['headers']['Host'])) {
            $urlParts['host'] = $parts['headers']['Host'];
        } elseif (isset($parts['headers']['host'])) {
            $urlParts['host'] = $parts['headers']['host'];
        } else {
            $urlParts['host'] = null;
        }

        if (false === strpos($urlParts['host'], ':')) {
            $urlParts['port'] = '';
        } else {
            $hostParts = explode(':', $urlParts['host']);
            $urlParts['host'] = trim($hostParts[0]);
            $urlParts['port'] = (int) trim($hostParts[1]);
            if ($urlParts['port'] == 443) {
                $urlParts['scheme'] = 'https';
            }
        }

        // Check if a query is present
        $path = $urlParts['path'];
        $qpos = strpos($path, '?');
        if ($qpos) {
            $urlParts['query'] = substr($path, $qpos + 1);
            $urlParts['path'] = substr($path, 0, $qpos);
        } else {
            $urlParts['query'] = '';
        }

        return $urlParts;
    }
}
<?php

namespace Guzzle\Parser\Message;

/**
 * Default request and response parser used by Guzzle. Optimized for speed.
 */
class MessageParser extends AbstractMessageParser
{
    public function parseRequest($message)
    {
        if (!$message) {
            return false;
        }

        $parts = $this->parseMessage($message);

        // Parse the protocol and protocol version
        if (isset($parts['start_line'][2])) {
            $startParts = explode('/', $parts['start_line'][2]);
            $protocol = strtoupper($startParts[0]);
            $version = isset($startParts[1]) ? $startParts[1] : '1.1';
        } else {
            $protocol = 'HTTP';
            $version = '1.1';
        }

        $parsed = array(
            'method'   => strtoupper($parts['start_line'][0]),
            'protocol' => $protocol,
            'version'  => $version,
            'headers'  => $parts['headers'],
            'body'     => $parts['body']
        );

        $parsed['request_url'] = $this->getUrlPartsFromMessage(isset($parts['start_line'][1]) ? $parts['start_line'][1] : '' , $parsed);

        return $parsed;
    }

    public function parseResponse($message)
    {
        if (!$message) {
            return false;
        }

        $parts = $this->parseMessage($message);
        list($protocol, $version) = explode('/', trim($parts['start_line'][0]));

        return array(
            'protocol'      => $protocol,
            'version'       => $version,
            'code'          => $parts['start_line'][1],
            'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '',
            'headers'       => $parts['headers'],
            'body'          => $parts['body']
        );
    }

    /**
     * Parse a message into parts
     *
     * @param string $message Message to parse
     *
     * @return array
     */
    protected function parseMessage($message)
    {
        $startLine = null;
        $headers = array();
        $body = '';

        // Iterate over each line in the message, accounting for line endings
        $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
        for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) {

            $line = $lines[$i];

            // If two line breaks were encountered, then this is the end of body
            if (empty($line)) {
                if ($i < $totalLines - 1) {
                    $body = implode('', array_slice($lines, $i + 2));
                }
                break;
            }

            // Parse message headers
            if (!$startLine) {
                $startLine = explode(' ', $line, 3);
            } elseif (strpos($line, ':')) {
                $parts = explode(':', $line, 2);
                $key = trim($parts[0]);
                $value = isset($parts[1]) ? trim($parts[1]) : '';
                if (!isset($headers[$key])) {
                    $headers[$key] = $value;
                } elseif (!is_array($headers[$key])) {
                    $headers[$key] = array($headers[$key], $value);
                } else {
                    $headers[$key][] = $value;
                }
            }
        }

        return array(
            'start_line' => $startLine,
            'headers'    => $headers,
            'body'       => $body
        );
    }
}
<?php

namespace Guzzle\Parser\Url;

use Guzzle\Common\Version;

/**
 * Parses URLs into parts using PHP's built-in parse_url() function
 * @deprecated Just use parse_url. UTF-8 characters should be percent encoded anyways.
 * @codeCoverageIgnore
 */
class UrlParser implements UrlParserInterface
{
    /** @var bool Whether or not to work with UTF-8 strings */
    protected $utf8 = false;

    /**
     * Set whether or not to attempt to handle UTF-8 strings (still WIP)
     *
     * @param bool $utf8 Set to TRUE to handle UTF string
     */
    public function setUtf8Support($utf8)
    {
        $this->utf8 = $utf8;
    }

    public function parseUrl($url)
    {
        Version::warn(__CLASS__ . ' is deprecated. Just use parse_url()');

        static $defaults = array('scheme' => null, 'host' => null, 'path' => null, 'port' => null, 'query' => null,
            'user' => null, 'pass' => null, 'fragment' => null);

        $parts = parse_url($url);

        // Need to handle query parsing specially for UTF-8 requirements
        if ($this->utf8 && isset($parts['query'])) {
            $queryPos = strpos($url, '?');
            if (isset($parts['fragment'])) {
                $parts['query'] = substr($url, $queryPos + 1, strpos($url, '#') - $queryPos - 1);
            } else {
                $parts['query'] = substr($url, $queryPos + 1);
            }
        }

        return $parts + $defaults;
    }
}
<?php

namespace Guzzle\Parser\Url;

/**
 * URL parser interface
 */
interface UrlParserInterface
{
    /**
     * Parse a URL using special handling for a subset of UTF-8 characters in the query string if needed.
     *
     * @param string $url URL to parse
     *
     * @return array Returns an array identical to what is returned from parse_url().  When an array key is missing from
     *               this array, you must fill it in with NULL to avoid warnings in calling code.
     */
    public function parseUrl($url);
}
<?php

namespace Guzzle\Parser\Cookie;

/**
 * Cookie parser interface
 */
interface CookieParserInterface
{
    /**
     * Parse a cookie string as set in a Set-Cookie HTTP header and return an associative array of data.
     *
     * @param string $cookie Cookie header value to parse
     * @param string $host   Host of an associated request
     * @param string $path   Path of an associated request
     * @param bool   $decode Set to TRUE to urldecode cookie values
     *
     * @return array|bool Returns FALSE on failure or returns an array of arrays, with each of the sub arrays including:
     *     - domain  (string) - Domain of the cookie
     *     - path    (string) - Path of the cookie
     *     - cookies (array)  - Associative array of cookie names and values
     *     - max_age (int)    - Lifetime of the cookie in seconds
     *     - version (int)    - Version of the cookie specification. RFC 2965 is 1
     *     - secure  (bool)   - Whether or not this is a secure cookie
     *     - discard (bool)   - Whether or not this is a discardable cookie
     *     - custom (string)  - Custom cookie data array
     *     - comment (string) - How the cookie is intended to be used
     *     - comment_url (str)- URL that contains info on how it will be used
     *     - port (array|str) - Array of ports or null
     *     - http_only (bool) - HTTP only cookie
     */
    public function parseCookie($cookie, $host = null, $path = null, $decode = false);
}
<?php

namespace Guzzle\Parser\Cookie;

/**
 * Default Guzzle implementation of a Cookie parser
 */
class CookieParser implements CookieParserInterface
{
    /** @var array Cookie part names to snake_case array values */
    protected static $cookieParts = array(
        'domain'      => 'Domain',
        'path'        => 'Path',
        'max_age'     => 'Max-Age',
        'expires'     => 'Expires',
        'version'     => 'Version',
        'secure'      => 'Secure',
        'port'        => 'Port',
        'discard'     => 'Discard',
        'comment'     => 'Comment',
        'comment_url' => 'Comment-Url',
        'http_only'   => 'HttpOnly'
    );

    public function parseCookie($cookie, $host = null, $path = null, $decode = false)
    {
        // Explode the cookie string using a series of semicolons
        $pieces = array_filter(array_map('trim', explode(';', $cookie)));

        // The name of the cookie (first kvp) must include an equal sign.
        if (empty($pieces) || !strpos($pieces[0], '=')) {
            return false;
        }

        // Create the default return array
        $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array(
            'cookies'   => array(),
            'data'      => array(),
            'path'      => null,
            'http_only' => false,
            'discard'   => false,
            'domain'    => $host
        ));
        $foundNonCookies = 0;

        // Add the cookie pieces into the parsed data array
        foreach ($pieces as $part) {

            $cookieParts = explode('=', $part, 2);
            $key = trim($cookieParts[0]);

            if (count($cookieParts) == 1) {
                // Can be a single value (e.g. secure, httpOnly)
                $value = true;
            } else {
                // Be sure to strip wrapping quotes
                $value = trim($cookieParts[1], " \n\r\t\0\x0B\"");
                if ($decode) {
                    $value = urldecode($value);
                }
            }

            // Only check for non-cookies when cookies have been found
            if (!empty($data['cookies'])) {
                foreach (self::$cookieParts as $mapValue => $search) {
                    if (!strcasecmp($search, $key)) {
                        $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value;
                        $foundNonCookies++;
                        continue 2;
                    }
                }
            }

            // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a
            // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data.
            $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value;
        }

        // Calculate the expires date
        if (!$data['expires'] && $data['max_age']) {
            $data['expires'] = time() + (int) $data['max_age'];
        }

        // Check path attribute according RFC6265 http://tools.ietf.org/search/rfc6265#section-5.2.4
        // "If the attribute-value is empty or if the first character of the
        // attribute-value is not %x2F ("/"):
        //   Let cookie-path be the default-path.
        // Otherwise:
        //   Let cookie-path be the attribute-value."
        if (!$data['path'] || substr($data['path'], 0, 1) !== '/') {
            $data['path'] = $this->getDefaultPath($path);
        }

        return $data;
    }

    /**
     * Get default cookie path according to RFC 6265
     * http://tools.ietf.org/search/rfc6265#section-5.1.4 Paths and Path-Match
     *
     * @param string $path Request uri-path
     *
     * @return string
     */
    protected function getDefaultPath($path) {
        // "The user agent MUST use an algorithm equivalent to the following algorithm
        // to compute the default-path of a cookie:"

        // "2. If the uri-path is empty or if the first character of the uri-path is not
        // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
        if (empty($path) || substr($path, 0, 1) !== '/') {
            return '/';
        }

        // "3. If the uri-path contains no more than one %x2F ("/") character, output
        // %x2F ("/") and skip the remaining step."
        if ($path === "/") {
            return $path;
        }

        $rightSlashPos = strrpos($path, '/');
        if ($rightSlashPos === 0) {
            return "/";
        }

        // "4. Output the characters of the uri-path from the first character up to,
        // but not including, the right-most %x2F ("/")."
        return substr($path, 0, $rightSlashPos);

    }
}
{
    "name": "guzzle/parser",
    "homepage": "http://guzzlephp.org/",
    "description": "Interchangeable parsers used by Guzzle",
    "keywords": ["HTTP", "message", "cookie", "URL", "URI Template"],
    "license": "MIT",
    "require": {
        "php": ">=5.3.2"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Parser": "" }
    },
    "target-dir": "Guzzle/Parser",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Parser\UriTemplate;

/**
 * Expands URI templates using an array of variables
 *
 * @link http://tools.ietf.org/html/draft-gregorio-uritemplate-08
 */
class UriTemplate implements UriTemplateInterface
{
    const DEFAULT_PATTERN = '/\{([^\}]+)\}/';

    /** @var string URI template */
    private $template;

    /** @var array Variables to use in the template expansion */
    private $variables;

    /** @var string Regex used to parse expressions */
    private $regex = self::DEFAULT_PATTERN;

    /** @var array Hash for quick operator lookups */
    private static $operatorHash = array(
        '+' => true, '#' => true, '.' => true, '/' => true, ';' => true, '?' => true, '&' => true
    );

    /** @var array Delimiters */
    private static $delims = array(
        ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '='
    );

    /** @var array Percent encoded delimiters */
    private static $delimsPct = array(
        '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C',
        '%3B', '%3D'
    );

    public function expand($template, array $variables)
    {
        if ($this->regex == self::DEFAULT_PATTERN && false === strpos($template, '{')) {
            return $template;
        }

        $this->template = $template;
        $this->variables = $variables;

        return preg_replace_callback($this->regex, array($this, 'expandMatch'), $this->template);
    }

    /**
     * Set the regex patten used to expand URI templates
     *
     * @param string $regexPattern
     */
    public function setRegex($regexPattern)
    {
        $this->regex = $regexPattern;
    }

    /**
     * Parse an expression into parts
     *
     * @param string $expression Expression to parse
     *
     * @return array Returns an associative array of parts
     */
    private function parseExpression($expression)
    {
        // Check for URI operators
        $operator = '';

        if (isset(self::$operatorHash[$expression[0]])) {
            $operator = $expression[0];
            $expression = substr($expression, 1);
        }

        $values = explode(',', $expression);
        foreach ($values as &$value) {
            $value = trim($value);
            $varspec = array();
            $substrPos = strpos($value, ':');
            if ($substrPos) {
                $varspec['value'] = substr($value, 0, $substrPos);
                $varspec['modifier'] = ':';
                $varspec['position'] = (int) substr($value, $substrPos + 1);
            } elseif (substr($value, -1) == '*') {
                $varspec['modifier'] = '*';
                $varspec['value'] = substr($value, 0, -1);
            } else {
                $varspec['value'] = (string) $value;
                $varspec['modifier'] = '';
            }
            $value = $varspec;
        }

        return array(
            'operator' => $operator,
            'values'   => $values
        );
    }

    /**
     * Process an expansion
     *
     * @param array $matches Matches met in the preg_replace_callback
     *
     * @return string Returns the replacement string
     */
    private function expandMatch(array $matches)
    {
        static $rfc1738to3986 = array(
            '+'   => '%20',
            '%7e' => '~'
        );

        $parsed = self::parseExpression($matches[1]);
        $replacements = array();

        $prefix = $parsed['operator'];
        $joiner = $parsed['operator'];
        $useQueryString = false;
        if ($parsed['operator'] == '?') {
            $joiner = '&';
            $useQueryString = true;
        } elseif ($parsed['operator'] == '&') {
            $useQueryString = true;
        } elseif ($parsed['operator'] == '#') {
            $joiner = ',';
        } elseif ($parsed['operator'] == ';') {
            $useQueryString = true;
        } elseif ($parsed['operator'] == '' || $parsed['operator'] == '+') {
            $joiner = ',';
            $prefix = '';
        }

        foreach ($parsed['values'] as $value) {

            if (!array_key_exists($value['value'], $this->variables) || $this->variables[$value['value']] === null) {
                continue;
            }

            $variable = $this->variables[$value['value']];
            $actuallyUseQueryString = $useQueryString;
            $expanded = '';

            if (is_array($variable)) {

                $isAssoc = $this->isAssoc($variable);
                $kvp = array();
                foreach ($variable as $key => $var) {

                    if ($isAssoc) {
                        $key = rawurlencode($key);
                        $isNestedArray = is_array($var);
                    } else {
                        $isNestedArray = false;
                    }

                    if (!$isNestedArray) {
                        $var = rawurlencode($var);
                        if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
                            $var = $this->decodeReserved($var);
                        }
                    }

                    if ($value['modifier'] == '*') {
                        if ($isAssoc) {
                            if ($isNestedArray) {
                                // Nested arrays must allow for deeply nested structures
                                $var = strtr(http_build_query(array($key => $var)), $rfc1738to3986);
                            } else {
                                $var = $key . '=' . $var;
                            }
                        } elseif ($key > 0 && $actuallyUseQueryString) {
                            $var = $value['value'] . '=' . $var;
                        }
                    }

                    $kvp[$key] = $var;
                }

                if (empty($variable)) {
                    $actuallyUseQueryString = false;
                } elseif ($value['modifier'] == '*') {
                    $expanded = implode($joiner, $kvp);
                    if ($isAssoc) {
                        // Don't prepend the value name when using the explode modifier with an associative array
                        $actuallyUseQueryString = false;
                    }
                } else {
                    if ($isAssoc) {
                        // When an associative array is encountered and the explode modifier is not set, then the
                        // result must be a comma separated list of keys followed by their respective values.
                        foreach ($kvp as $k => &$v) {
                            $v = $k . ',' . $v;
                        }
                    }
                    $expanded = implode(',', $kvp);
                }

            } else {
                if ($value['modifier'] == ':') {
                    $variable = substr($variable, 0, $value['position']);
                }
                $expanded = rawurlencode($variable);
                if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
                    $expanded = $this->decodeReserved($expanded);
                }
            }

            if ($actuallyUseQueryString) {
                if (!$expanded && $joiner != '&') {
                    $expanded = $value['value'];
                } else {
                    $expanded = $value['value'] . '=' . $expanded;
                }
            }

            $replacements[] = $expanded;
        }

        $ret = implode($joiner, $replacements);
        if ($ret && $prefix) {
            return $prefix . $ret;
        }

        return $ret;
    }

    /**
     * Determines if an array is associative
     *
     * @param array $array Array to check
     *
     * @return bool
     */
    private function isAssoc(array $array)
    {
        return (bool) count(array_filter(array_keys($array), 'is_string'));
    }

    /**
     * Removes percent encoding on reserved characters (used with + and # modifiers)
     *
     * @param string $string String to fix
     *
     * @return string
     */
    private function decodeReserved($string)
    {
        return str_replace(self::$delimsPct, self::$delims, $string);
    }
}
<?php

namespace Guzzle\Parser\UriTemplate;

use Guzzle\Common\Exception\RuntimeException;

/**
 * Expands URI templates using the uri_template pecl extension (pecl install uri_template-beta)
 *
 * @link http://pecl.php.net/package/uri_template
 * @link https://github.com/ioseb/uri-template
 */
class PeclUriTemplate implements UriTemplateInterface
{
    public function __construct()
    {
        if (!extension_loaded('uri_template')) {
            throw new RuntimeException('uri_template PECL extension must be installed to use PeclUriTemplate');
        }
    }

    public function expand($template, array $variables)
    {
        return uri_template($template, $variables);
    }
}
<?php

namespace Guzzle\Parser\UriTemplate;

/**
 * Expands URI templates using an array of variables
 *
 * @link http://tools.ietf.org/html/rfc6570
 */
interface UriTemplateInterface
{
    /**
     * Expand the URI template using the supplied variables
     *
     * @param string $template  URI Template to expand
     * @param array  $variables Variables to use with the expansion
     *
     * @return string Returns the expanded template
     */
    public function expand($template, array $variables);
}
<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\Event as SymfonyEvent;

/**
 * Default event for Guzzle notifications
 */
class Event extends SymfonyEvent implements ToArrayInterface, \ArrayAccess, \IteratorAggregate
{
    /** @var array */
    private $context;

    /**
     * @param array $context Contextual information
     */
    public function __construct(array $context = array())
    {
        $this->context = $context;
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->context);
    }

    public function offsetGet($offset)
    {
        return isset($this->context[$offset]) ? $this->context[$offset] : null;
    }

    public function offsetSet($offset, $value)
    {
        $this->context[$offset] = $value;
    }

    public function offsetExists($offset)
    {
        return isset($this->context[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->context[$offset]);
    }

    public function toArray()
    {
        return $this->context;
    }
}
<?php

namespace Guzzle\Common;

/**
 * An object that can be represented as an array
 */
interface ToArrayInterface
{
    /**
     * Get the array representation of an object
     *
     * @return array
     */
    public function toArray();
}
<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class that holds an event dispatcher
 */
class AbstractHasDispatcher implements HasDispatcherInterface
{
    /** @var EventDispatcherInterface */
    protected $eventDispatcher;

    public static function getAllEvents()
    {
        return array();
    }

    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;

        return $this;
    }

    public function getEventDispatcher()
    {
        if (!$this->eventDispatcher) {
            $this->eventDispatcher = new EventDispatcher();
        }

        return $this->eventDispatcher;
    }

    public function dispatch($eventName, array $context = array())
    {
        return $this->getEventDispatcher()->dispatch($eventName, new Event($context));
    }

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->getEventDispatcher()->addSubscriber($subscriber);

        return $this;
    }
}
<?php

namespace Guzzle\Common;

/**
 * Guzzle version information
 */
class Version
{
    const VERSION = '3.9.3';

    /**
     * @var bool Set this value to true to enable warnings for deprecated functionality use. This should be on in your
     *           unit tests, but probably not in production.
     */
    public static $emitWarnings = false;

    /**
     * Emit a deprecation warning
     *
     * @param string $message Warning message
     */
    public static function warn($message)
    {
        if (self::$emitWarnings) {
            trigger_error('Deprecation warning: ' . $message, E_USER_DEPRECATED);
        }
    }
}
<?php

namespace Guzzle\Common;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;

/**
 * Key value pair collection object
 */
class Collection implements \ArrayAccess, \IteratorAggregate, \Countable, ToArrayInterface
{
    /** @var array Data associated with the object. */
    protected $data;

    /**
     * @param array $data Associative array of data to set
     */
    public function __construct(array $data = array())
    {
        $this->data = $data;
    }

    /**
     * Create a new collection from an array, validate the keys, and add default values where missing
     *
     * @param array $config   Configuration values to apply.
     * @param array $defaults Default parameters
     * @param array $required Required parameter names
     *
     * @return self
     * @throws InvalidArgumentException if a parameter is missing
     */
    public static function fromConfig(array $config = array(), array $defaults = array(), array $required = array())
    {
        $data = $config + $defaults;

        if ($missing = array_diff($required, array_keys($data))) {
            throw new InvalidArgumentException('Config is missing the following keys: ' . implode(', ', $missing));
        }

        return new self($data);
    }

    public function count()
    {
        return count($this->data);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->data);
    }

    public function toArray()
    {
        return $this->data;
    }

    /**
     * Removes all key value pairs
     *
     * @return Collection
     */
    public function clear()
    {
        $this->data = array();

        return $this;
    }

    /**
     * Get all or a subset of matching key value pairs
     *
     * @param array $keys Pass an array of keys to retrieve only a subset of key value pairs
     *
     * @return array Returns an array of all matching key value pairs
     */
    public function getAll(array $keys = null)
    {
        return $keys ? array_intersect_key($this->data, array_flip($keys)) : $this->data;
    }

    /**
     * Get a specific key value.
     *
     * @param string $key Key to retrieve.
     *
     * @return mixed|null Value of the key or NULL
     */
    public function get($key)
    {
        return isset($this->data[$key]) ? $this->data[$key] : null;
    }

    /**
     * Set a key value pair
     *
     * @param string $key   Key to set
     * @param mixed  $value Value to set
     *
     * @return Collection Returns a reference to the object
     */
    public function set($key, $value)
    {
        $this->data[$key] = $value;

        return $this;
    }

    /**
     * Add a value to a key.  If a key of the same name has already been added, the key value will be converted into an
     * array and the new value will be pushed to the end of the array.
     *
     * @param string $key   Key to add
     * @param mixed  $value Value to add to the key
     *
     * @return Collection Returns a reference to the object.
     */
    public function add($key, $value)
    {
        if (!array_key_exists($key, $this->data)) {
            $this->data[$key] = $value;
        } elseif (is_array($this->data[$key])) {
            $this->data[$key][] = $value;
        } else {
            $this->data[$key] = array($this->data[$key], $value);
        }

        return $this;
    }

    /**
     * Remove a specific key value pair
     *
     * @param string $key A key to remove
     *
     * @return Collection
     */
    public function remove($key)
    {
        unset($this->data[$key]);

        return $this;
    }

    /**
     * Get all keys in the collection
     *
     * @return array
     */
    public function getKeys()
    {
        return array_keys($this->data);
    }

    /**
     * Returns whether or not the specified key is present.
     *
     * @param string $key The key for which to check the existence.
     *
     * @return bool
     */
    public function hasKey($key)
    {
        return array_key_exists($key, $this->data);
    }

    /**
     * Case insensitive search the keys in the collection
     *
     * @param string $key Key to search for
     *
     * @return bool|string Returns false if not found, otherwise returns the key
     */
    public function keySearch($key)
    {
        foreach (array_keys($this->data) as $k) {
            if (!strcasecmp($k, $key)) {
                return $k;
            }
        }

        return false;
    }

    /**
     * Checks if any keys contains a certain value
     *
     * @param string $value Value to search for
     *
     * @return mixed Returns the key if the value was found FALSE if the value was not found.
     */
    public function hasValue($value)
    {
        return array_search($value, $this->data);
    }

    /**
     * Replace the data of the object with the value of an array
     *
     * @param array $data Associative array of data
     *
     * @return Collection Returns a reference to the object
     */
    public function replace(array $data)
    {
        $this->data = $data;

        return $this;
    }

    /**
     * Add and merge in a Collection or array of key value pair data.
     *
     * @param Collection|array $data Associative array of key value pair data
     *
     * @return Collection Returns a reference to the object.
     */
    public function merge($data)
    {
        foreach ($data as $key => $value) {
            $this->add($key, $value);
        }

        return $this;
    }

    /**
     * Over write key value pairs in this collection with all of the data from an array or collection.
     *
     * @param array|\Traversable $data Values to override over this config
     *
     * @return self
     */
    public function overwriteWith($data)
    {
        if (is_array($data)) {
            $this->data = $data + $this->data;
        } elseif ($data instanceof Collection) {
            $this->data = $data->toArray() + $this->data;
        } else {
            foreach ($data as $key => $value) {
                $this->data[$key] = $value;
            }
        }

        return $this;
    }

    /**
     * Returns a Collection containing all the elements of the collection after applying the callback function to each
     * one. The Closure should accept three parameters: (string) $key, (string) $value, (array) $context and return a
     * modified value
     *
     * @param \Closure $closure Closure to apply
     * @param array    $context Context to pass to the closure
     * @param bool     $static  Set to TRUE to use the same class as the return rather than returning a Collection
     *
     * @return Collection
     */
    public function map(\Closure $closure, array $context = array(), $static = true)
    {
        $collection = $static ? new static() : new self();
        foreach ($this as $key => $value) {
            $collection->add($key, $closure($key, $value, $context));
        }

        return $collection;
    }

    /**
     * Iterates over each key value pair in the collection passing them to the Closure. If the  Closure function returns
     * true, the current value from input is returned into the result Collection.  The Closure must accept three
     * parameters: (string) $key, (string) $value and return Boolean TRUE or FALSE for each value.
     *
     * @param \Closure $closure Closure evaluation function
     * @param bool     $static  Set to TRUE to use the same class as the return rather than returning a Collection
     *
     * @return Collection
     */
    public function filter(\Closure $closure, $static = true)
    {
        $collection = ($static) ? new static() : new self();
        foreach ($this->data as $key => $value) {
            if ($closure($key, $value)) {
                $collection->add($key, $value);
            }
        }

        return $collection;
    }

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }

    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }

    /**
     * Set a value into a nested array key. Keys will be created as needed to set the value.
     *
     * @param string $path  Path to set
     * @param mixed  $value Value to set at the key
     *
     * @return self
     * @throws RuntimeException when trying to setPath using a nested path that travels through a scalar value
     */
    public function setPath($path, $value)
    {
        $current =& $this->data;
        $queue = explode('/', $path);
        while (null !== ($key = array_shift($queue))) {
            if (!is_array($current)) {
                throw new RuntimeException("Trying to setPath {$path}, but {$key} is set and is not an array");
            } elseif (!$queue) {
                $current[$key] = $value;
            } elseif (isset($current[$key])) {
                $current =& $current[$key];
            } else {
                $current[$key] = array();
                $current =& $current[$key];
            }
        }

        return $this;
    }

    /**
     * Gets a value from the collection using an array path (e.g. foo/baz/bar would retrieve bar from two nested arrays)
     * Allows for wildcard searches which recursively combine matches up to the level at which the wildcard occurs. This
     * can be useful for accepting any key of a sub-array and combining matching keys from each diverging path.
     *
     * @param string $path      Path to traverse and retrieve a value from
     * @param string $separator Character used to add depth to the search
     * @param mixed  $data      Optional data to descend into (used when wildcards are encountered)
     *
     * @return mixed|null
     */
    public function getPath($path, $separator = '/', $data = null)
    {
        if ($data === null) {
            $data =& $this->data;
        }

        $path = is_array($path) ? $path : explode($separator, $path);
        while (null !== ($part = array_shift($path))) {
            if (!is_array($data)) {
                return null;
            } elseif (isset($data[$part])) {
                $data =& $data[$part];
            } elseif ($part != '*') {
                return null;
            } else {
                // Perform a wildcard search by diverging and merging paths
                $result = array();
                foreach ($data as $value) {
                    if (!$path) {
                        $result = array_merge_recursive($result, (array) $value);
                    } elseif (null !== ($test = $this->getPath($path, $separator, $value))) {
                        $result = array_merge_recursive($result, (array) $test);
                    }
                }
                return $result;
            }
        }

        return $data;
    }

    /**
     * Inject configuration settings into an input string
     *
     * @param string $input Input to inject
     *
     * @return string
     * @deprecated
     */
    public function inject($input)
    {
        Version::warn(__METHOD__ . ' is deprecated');
        $replace = array();
        foreach ($this->data as $key => $val) {
            $replace['{' . $key . '}'] = $val;
        }

        return strtr($input, $replace);
    }
}
<?php

namespace Guzzle\Common;

/**
 * Interfaces that adds a factory method which is used to instantiate a class from an array of configuration options.
 */
interface FromConfigInterface
{
    /**
     * Static factory method used to turn an array or collection of configuration data into an instantiated object.
     *
     * @param array|Collection $config Configuration data
     *
     * @return FromConfigInterface
     */
    public static function factory($config = array());
}
<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Holds an event dispatcher
 */
interface HasDispatcherInterface
{
    /**
     * Get a list of all of the events emitted from the class
     *
     * @return array
     */
    public static function getAllEvents();

    /**
     * Set the EventDispatcher of the request
     *
     * @param EventDispatcherInterface $eventDispatcher
     *
     * @return self
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher);

    /**
     * Get the EventDispatcher of the request
     *
     * @return EventDispatcherInterface
     */
    public function getEventDispatcher();

    /**
     * Helper to dispatch Guzzle events and set the event name on the event
     *
     * @param string $eventName Name of the event to dispatch
     * @param array  $context   Context of the event
     *
     * @return Event Returns the created event object
     */
    public function dispatch($eventName, array $context = array());

    /**
     * Add an event subscriber to the dispatcher
     *
     * @param EventSubscriberInterface $subscriber Event subscriber
     *
     * @return self
     */
    public function addSubscriber(EventSubscriberInterface $subscriber);
}
<?php

namespace Guzzle\Common\Exception;

/**
 * Guzzle exception
 */
interface GuzzleException {}
<?php

namespace Guzzle\Common\Exception;

class UnexpectedValueException extends \UnexpectedValueException implements GuzzleException {}
<?php

namespace Guzzle\Common\Exception;

class RuntimeException extends \RuntimeException implements GuzzleException {}
<?php

namespace Guzzle\Common\Exception;

class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException {}
<?php

namespace Guzzle\Common\Exception;

class BadMethodCallException extends \BadMethodCallException implements GuzzleException {}
<?php

namespace Guzzle\Common\Exception;

/**
 * Collection of exceptions
 */
class ExceptionCollection extends \Exception implements GuzzleException, \IteratorAggregate, \Countable
{
    /** @var array Array of Exceptions */
    protected $exceptions = array();

    /** @var string Succinct exception message not including sub-exceptions */
    private $shortMessage;

    public function __construct($message = '', $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
        $this->shortMessage = $message;
    }

    /**
     * Set all of the exceptions
     *
     * @param array $exceptions Array of exceptions
     *
     * @return self
     */
    public function setExceptions(array $exceptions)
    {
        $this->exceptions = array();
        foreach ($exceptions as $exception) {
            $this->add($exception);
        }

        return $this;
    }

    /**
     * Add exceptions to the collection
     *
     * @param ExceptionCollection|\Exception $e Exception to add
     *
     * @return ExceptionCollection;
     */
    public function add($e)
    {
        $this->exceptions[] = $e;
        if ($this->message) {
            $this->message .= "\n";
        }

        $this->message .= $this->getExceptionMessage($e, 0);

        return $this;
    }

    /**
     * Get the total number of request exceptions
     *
     * @return int
     */
    public function count()
    {
        return count($this->exceptions);
    }

    /**
     * Allows array-like iteration over the request exceptions
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->exceptions);
    }

    /**
     * Get the first exception in the collection
     *
     * @return \Exception
     */
    public function getFirst()
    {
        return $this->exceptions ? $this->exceptions[0] : null;
    }

    private function getExceptionMessage(\Exception $e, $depth = 0)
    {
        static $sp = '    ';
        $prefix = $depth ? str_repeat($sp, $depth) : '';
        $message = "{$prefix}(" . get_class($e) . ') ' . $e->getFile() . ' line ' . $e->getLine() . "\n";

        if ($e instanceof self) {
            if ($e->shortMessage) {
                $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->shortMessage) . "\n";
            }
            foreach ($e as $ee) {
                $message .= "\n" . $this->getExceptionMessage($ee, $depth + 1);
            }
        }  else {
            $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getMessage()) . "\n";
            $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getTraceAsString()) . "\n";
        }

        return str_replace(getcwd(), '.', $message);
    }
}
{
    "name": "guzzle/common",
    "homepage": "http://guzzlephp.org/",
    "description": "Common libraries used by Guzzle",
    "keywords": ["common", "event", "exception", "collection"],
    "license": "MIT",
    "require": {
        "php": ">=5.3.2",
        "symfony/event-dispatcher": ">=2.1"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Common": "" }
    },
    "target-dir": "Guzzle/Common",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Iterator;

/**
 * Pulls out chunks from an inner iterator and yields the chunks as arrays
 */
class ChunkedIterator extends \IteratorIterator
{
    /** @var int Size of each chunk */
    protected $chunkSize;

    /** @var array Current chunk */
    protected $chunk;

    /**
     * @param \Traversable $iterator  Traversable iterator
     * @param int          $chunkSize Size to make each chunk
     * @throws \InvalidArgumentException
     */
    public function __construct(\Traversable $iterator, $chunkSize)
    {
        $chunkSize = (int) $chunkSize;
        if ($chunkSize < 0 ) {
            throw new \InvalidArgumentException("The chunk size must be equal or greater than zero; $chunkSize given");
        }

        parent::__construct($iterator);
        $this->chunkSize = $chunkSize;
    }

    public function rewind()
    {
        parent::rewind();
        $this->next();
    }

    public function next()
    {
        $this->chunk = array();
        for ($i = 0; $i < $this->chunkSize && parent::valid(); $i++) {
            $this->chunk[] = parent::current();
            parent::next();
        }
    }

    public function current()
    {
        return $this->chunk;
    }

    public function valid()
    {
        return (bool) $this->chunk;
    }
}
<?php

namespace Guzzle\Iterator;

/**
 * AppendIterator that is not affected by https://bugs.php.net/bug.php?id=49104
 */
class AppendIterator extends \AppendIterator
{
    /**
     * Works around the bug in which PHP calls rewind() and next() when appending
     *
     * @param \Iterator $iterator Iterator to append
     */
    public function append(\Iterator $iterator)
    {
        $this->getArrayIterator()->append($iterator);
    }
}
<?php

namespace Guzzle\Iterator;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Maps values before yielding
 */
class MapIterator extends \IteratorIterator
{
    /** @var mixed Callback */
    protected $callback;

    /**
     * @param \Traversable   $iterator Traversable iterator
     * @param array|\Closure $callback Callback used for iterating
     *
     * @throws InvalidArgumentException if the callback if not callable
     */
    public function __construct(\Traversable $iterator, $callback)
    {
        parent::__construct($iterator);
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('The callback must be callable');
        }
        $this->callback = $callback;
    }

    public function current()
    {
        return call_user_func($this->callback, parent::current());
    }
}
Guzzle Iterator
===============

Provides useful Iterators and Iterator decorators

- ChunkedIterator: Pulls out chunks from an inner iterator and yields the chunks as arrays
- FilterIterator: Used when PHP 5.4's CallbackFilterIterator is not available
- MapIterator: Maps values before yielding
- MethodProxyIterator: Proxies missing method calls to the innermost iterator

### Installing via Composer

```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php

# Add Guzzle as a dependency
php composer.phar require guzzle/iterator:~3.0
```

After installing, you need to require Composer's autoloader:

```php
require 'vendor/autoload.php';
```
<?php

namespace Guzzle\Iterator;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Filters values using a callback
 *
 * Used when PHP 5.4's {@see \CallbackFilterIterator} is not available
 */
class FilterIterator extends \FilterIterator
{
    /** @var mixed Callback used for filtering */
    protected $callback;

    /**
     * @param \Iterator      $iterator Traversable iterator
     * @param array|\Closure $callback Callback used for filtering. Return true to keep or false to filter.
     *
     * @throws InvalidArgumentException if the callback if not callable
     */
    public function __construct(\Iterator $iterator, $callback)
    {
        parent::__construct($iterator);
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('The callback must be callable');
        }
        $this->callback = $callback;
    }

    public function accept()
    {
        return call_user_func($this->callback, $this->current());
    }
}
<?php

namespace Guzzle\Iterator;

/**
 * Proxies missing method calls to the innermost iterator
 */
class MethodProxyIterator extends \IteratorIterator
{
    /**
     * Proxy method calls to the wrapped iterator
     *
     * @param string $name Name of the method
     * @param array  $args Arguments to proxy
     *
     * @return mixed
     */
    public function __call($name, array $args)
    {
        $i = $this->getInnerIterator();
        while ($i instanceof \OuterIterator) {
            $i = $i->getInnerIterator();
        }

        return call_user_func_array(array($i, $name), $args);
    }
}
{
    "name": "guzzle/iterator",
    "description": "Provides helpful iterators and iterator decorators",
    "keywords": ["iterator", "guzzle"],
    "homepage": "http://guzzlephp.org/",
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/common": ">=2.8.0"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Iterator": "/" }
    },
    "target-dir": "Guzzle/Iterator",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Http;

/**
 * Provides mappings of file extensions to mimetypes
 * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
 */
class Mimetypes
{
    /** @var self */
    protected static $instance;

    /** @var array Mapping of extension to mimetype */
    protected $mimetypes = array(
        '3dml' => 'text/vnd.in3d.3dml',
        '3g2' => 'video/3gpp2',
        '3gp' => 'video/3gpp',
        '7z' => 'application/x-7z-compressed',
        'aab' => 'application/x-authorware-bin',
        'aac' => 'audio/x-aac',
        'aam' => 'application/x-authorware-map',
        'aas' => 'application/x-authorware-seg',
        'abw' => 'application/x-abiword',
        'ac' => 'application/pkix-attr-cert',
        'acc' => 'application/vnd.americandynamics.acc',
        'ace' => 'application/x-ace-compressed',
        'acu' => 'application/vnd.acucobol',
        'acutc' => 'application/vnd.acucorp',
        'adp' => 'audio/adpcm',
        'aep' => 'application/vnd.audiograph',
        'afm' => 'application/x-font-type1',
        'afp' => 'application/vnd.ibm.modcap',
        'ahead' => 'application/vnd.ahead.space',
        'ai' => 'application/postscript',
        'aif' => 'audio/x-aiff',
        'aifc' => 'audio/x-aiff',
        'aiff' => 'audio/x-aiff',
        'air' => 'application/vnd.adobe.air-application-installer-package+zip',
        'ait' => 'application/vnd.dvb.ait',
        'ami' => 'application/vnd.amiga.ami',
        'apk' => 'application/vnd.android.package-archive',
        'application' => 'application/x-ms-application',
        'apr' => 'application/vnd.lotus-approach',
        'asa' => 'text/plain',
        'asax' => 'application/octet-stream',
        'asc' => 'application/pgp-signature',
        'ascx' => 'text/plain',
        'asf' => 'video/x-ms-asf',
        'ashx' => 'text/plain',
        'asm' => 'text/x-asm',
        'asmx' => 'text/plain',
        'aso' => 'application/vnd.accpac.simply.aso',
        'asp' => 'text/plain',
        'aspx' => 'text/plain',
        'asx' => 'video/x-ms-asf',
        'atc' => 'application/vnd.acucorp',
        'atom' => 'application/atom+xml',
        'atomcat' => 'application/atomcat+xml',
        'atomsvc' => 'application/atomsvc+xml',
        'atx' => 'application/vnd.antix.game-component',
        'au' => 'audio/basic',
        'avi' => 'video/x-msvideo',
        'aw' => 'application/applixware',
        'axd' => 'text/plain',
        'azf' => 'application/vnd.airzip.filesecure.azf',
        'azs' => 'application/vnd.airzip.filesecure.azs',
        'azw' => 'application/vnd.amazon.ebook',
        'bat' => 'application/x-msdownload',
        'bcpio' => 'application/x-bcpio',
        'bdf' => 'application/x-font-bdf',
        'bdm' => 'application/vnd.syncml.dm+wbxml',
        'bed' => 'application/vnd.realvnc.bed',
        'bh2' => 'application/vnd.fujitsu.oasysprs',
        'bin' => 'application/octet-stream',
        'bmi' => 'application/vnd.bmi',
        'bmp' => 'image/bmp',
        'book' => 'application/vnd.framemaker',
        'box' => 'application/vnd.previewsystems.box',
        'boz' => 'application/x-bzip2',
        'bpk' => 'application/octet-stream',
        'btif' => 'image/prs.btif',
        'bz' => 'application/x-bzip',
        'bz2' => 'application/x-bzip2',
        'c' => 'text/x-c',
        'c11amc' => 'application/vnd.cluetrust.cartomobile-config',
        'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg',
        'c4d' => 'application/vnd.clonk.c4group',
        'c4f' => 'application/vnd.clonk.c4group',
        'c4g' => 'application/vnd.clonk.c4group',
        'c4p' => 'application/vnd.clonk.c4group',
        'c4u' => 'application/vnd.clonk.c4group',
        'cab' => 'application/vnd.ms-cab-compressed',
        'car' => 'application/vnd.curl.car',
        'cat' => 'application/vnd.ms-pki.seccat',
        'cc' => 'text/x-c',
        'cct' => 'application/x-director',
        'ccxml' => 'application/ccxml+xml',
        'cdbcmsg' => 'application/vnd.contact.cmsg',
        'cdf' => 'application/x-netcdf',
        'cdkey' => 'application/vnd.mediastation.cdkey',
        'cdmia' => 'application/cdmi-capability',
        'cdmic' => 'application/cdmi-container',
        'cdmid' => 'application/cdmi-domain',
        'cdmio' => 'application/cdmi-object',
        'cdmiq' => 'application/cdmi-queue',
        'cdx' => 'chemical/x-cdx',
        'cdxml' => 'application/vnd.chemdraw+xml',
        'cdy' => 'application/vnd.cinderella',
        'cer' => 'application/pkix-cert',
        'cfc' => 'application/x-coldfusion',
        'cfm' => 'application/x-coldfusion',
        'cgm' => 'image/cgm',
        'chat' => 'application/x-chat',
        'chm' => 'application/vnd.ms-htmlhelp',
        'chrt' => 'application/vnd.kde.kchart',
        'cif' => 'chemical/x-cif',
        'cii' => 'application/vnd.anser-web-certificate-issue-initiation',
        'cil' => 'application/vnd.ms-artgalry',
        'cla' => 'application/vnd.claymore',
        'class' => 'application/java-vm',
        'clkk' => 'application/vnd.crick.clicker.keyboard',
        'clkp' => 'application/vnd.crick.clicker.palette',
        'clkt' => 'application/vnd.crick.clicker.template',
        'clkw' => 'application/vnd.crick.clicker.wordbank',
        'clkx' => 'application/vnd.crick.clicker',
        'clp' => 'application/x-msclip',
        'cmc' => 'application/vnd.cosmocaller',
        'cmdf' => 'chemical/x-cmdf',
        'cml' => 'chemical/x-cml',
        'cmp' => 'application/vnd.yellowriver-custom-menu',
        'cmx' => 'image/x-cmx',
        'cod' => 'application/vnd.rim.cod',
        'com' => 'application/x-msdownload',
        'conf' => 'text/plain',
        'cpio' => 'application/x-cpio',
        'cpp' => 'text/x-c',
        'cpt' => 'application/mac-compactpro',
        'crd' => 'application/x-mscardfile',
        'crl' => 'application/pkix-crl',
        'crt' => 'application/x-x509-ca-cert',
        'cryptonote' => 'application/vnd.rig.cryptonote',
        'cs' => 'text/plain',
        'csh' => 'application/x-csh',
        'csml' => 'chemical/x-csml',
        'csp' => 'application/vnd.commonspace',
        'css' => 'text/css',
        'cst' => 'application/x-director',
        'csv' => 'text/csv',
        'cu' => 'application/cu-seeme',
        'curl' => 'text/vnd.curl',
        'cww' => 'application/prs.cww',
        'cxt' => 'application/x-director',
        'cxx' => 'text/x-c',
        'dae' => 'model/vnd.collada+xml',
        'daf' => 'application/vnd.mobius.daf',
        'dataless' => 'application/vnd.fdsn.seed',
        'davmount' => 'application/davmount+xml',
        'dcr' => 'application/x-director',
        'dcurl' => 'text/vnd.curl.dcurl',
        'dd2' => 'application/vnd.oma.dd2+xml',
        'ddd' => 'application/vnd.fujixerox.ddd',
        'deb' => 'application/x-debian-package',
        'def' => 'text/plain',
        'deploy' => 'application/octet-stream',
        'der' => 'application/x-x509-ca-cert',
        'dfac' => 'application/vnd.dreamfactory',
        'dic' => 'text/x-c',
        'dir' => 'application/x-director',
        'dis' => 'application/vnd.mobius.dis',
        'dist' => 'application/octet-stream',
        'distz' => 'application/octet-stream',
        'djv' => 'image/vnd.djvu',
        'djvu' => 'image/vnd.djvu',
        'dll' => 'application/x-msdownload',
        'dmg' => 'application/octet-stream',
        'dms' => 'application/octet-stream',
        'dna' => 'application/vnd.dna',
        'doc' => 'application/msword',
        'docm' => 'application/vnd.ms-word.document.macroenabled.12',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'dot' => 'application/msword',
        'dotm' => 'application/vnd.ms-word.template.macroenabled.12',
        'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
        'dp' => 'application/vnd.osgi.dp',
        'dpg' => 'application/vnd.dpgraph',
        'dra' => 'audio/vnd.dra',
        'dsc' => 'text/prs.lines.tag',
        'dssc' => 'application/dssc+der',
        'dtb' => 'application/x-dtbook+xml',
        'dtd' => 'application/xml-dtd',
        'dts' => 'audio/vnd.dts',
        'dtshd' => 'audio/vnd.dts.hd',
        'dump' => 'application/octet-stream',
        'dvi' => 'application/x-dvi',
        'dwf' => 'model/vnd.dwf',
        'dwg' => 'image/vnd.dwg',
        'dxf' => 'image/vnd.dxf',
        'dxp' => 'application/vnd.spotfire.dxp',
        'dxr' => 'application/x-director',
        'ecelp4800' => 'audio/vnd.nuera.ecelp4800',
        'ecelp7470' => 'audio/vnd.nuera.ecelp7470',
        'ecelp9600' => 'audio/vnd.nuera.ecelp9600',
        'ecma' => 'application/ecmascript',
        'edm' => 'application/vnd.novadigm.edm',
        'edx' => 'application/vnd.novadigm.edx',
        'efif' => 'application/vnd.picsel',
        'ei6' => 'application/vnd.pg.osasli',
        'elc' => 'application/octet-stream',
        'eml' => 'message/rfc822',
        'emma' => 'application/emma+xml',
        'eol' => 'audio/vnd.digital-winds',
        'eot' => 'application/vnd.ms-fontobject',
        'eps' => 'application/postscript',
        'epub' => 'application/epub+zip',
        'es3' => 'application/vnd.eszigno3+xml',
        'esf' => 'application/vnd.epson.esf',
        'et3' => 'application/vnd.eszigno3+xml',
        'etx' => 'text/x-setext',
        'exe' => 'application/x-msdownload',
        'exi' => 'application/exi',
        'ext' => 'application/vnd.novadigm.ext',
        'ez' => 'application/andrew-inset',
        'ez2' => 'application/vnd.ezpix-album',
        'ez3' => 'application/vnd.ezpix-package',
        'f' => 'text/x-fortran',
        'f4v' => 'video/x-f4v',
        'f77' => 'text/x-fortran',
        'f90' => 'text/x-fortran',
        'fbs' => 'image/vnd.fastbidsheet',
        'fcs' => 'application/vnd.isac.fcs',
        'fdf' => 'application/vnd.fdf',
        'fe_launch' => 'application/vnd.denovo.fcselayout-link',
        'fg5' => 'application/vnd.fujitsu.oasysgp',
        'fgd' => 'application/x-director',
        'fh' => 'image/x-freehand',
        'fh4' => 'image/x-freehand',
        'fh5' => 'image/x-freehand',
        'fh7' => 'image/x-freehand',
        'fhc' => 'image/x-freehand',
        'fig' => 'application/x-xfig',
        'fli' => 'video/x-fli',
        'flo' => 'application/vnd.micrografx.flo',
        'flv' => 'video/x-flv',
        'flw' => 'application/vnd.kde.kivio',
        'flx' => 'text/vnd.fmi.flexstor',
        'fly' => 'text/vnd.fly',
        'fm' => 'application/vnd.framemaker',
        'fnc' => 'application/vnd.frogans.fnc',
        'for' => 'text/x-fortran',
        'fpx' => 'image/vnd.fpx',
        'frame' => 'application/vnd.framemaker',
        'fsc' => 'application/vnd.fsc.weblaunch',
        'fst' => 'image/vnd.fst',
        'ftc' => 'application/vnd.fluxtime.clip',
        'fti' => 'application/vnd.anser-web-funds-transfer-initiation',
        'fvt' => 'video/vnd.fvt',
        'fxp' => 'application/vnd.adobe.fxp',
        'fxpl' => 'application/vnd.adobe.fxp',
        'fzs' => 'application/vnd.fuzzysheet',
        'g2w' => 'application/vnd.geoplan',
        'g3' => 'image/g3fax',
        'g3w' => 'application/vnd.geospace',
        'gac' => 'application/vnd.groove-account',
        'gdl' => 'model/vnd.gdl',
        'geo' => 'application/vnd.dynageo',
        'gex' => 'application/vnd.geometry-explorer',
        'ggb' => 'application/vnd.geogebra.file',
        'ggt' => 'application/vnd.geogebra.tool',
        'ghf' => 'application/vnd.groove-help',
        'gif' => 'image/gif',
        'gim' => 'application/vnd.groove-identity-message',
        'gmx' => 'application/vnd.gmx',
        'gnumeric' => 'application/x-gnumeric',
        'gph' => 'application/vnd.flographit',
        'gqf' => 'application/vnd.grafeq',
        'gqs' => 'application/vnd.grafeq',
        'gram' => 'application/srgs',
        'gre' => 'application/vnd.geometry-explorer',
        'grv' => 'application/vnd.groove-injector',
        'grxml' => 'application/srgs+xml',
        'gsf' => 'application/x-font-ghostscript',
        'gtar' => 'application/x-gtar',
        'gtm' => 'application/vnd.groove-tool-message',
        'gtw' => 'model/vnd.gtw',
        'gv' => 'text/vnd.graphviz',
        'gxt' => 'application/vnd.geonext',
        'h' => 'text/x-c',
        'h261' => 'video/h261',
        'h263' => 'video/h263',
        'h264' => 'video/h264',
        'hal' => 'application/vnd.hal+xml',
        'hbci' => 'application/vnd.hbci',
        'hdf' => 'application/x-hdf',
        'hh' => 'text/x-c',
        'hlp' => 'application/winhlp',
        'hpgl' => 'application/vnd.hp-hpgl',
        'hpid' => 'application/vnd.hp-hpid',
        'hps' => 'application/vnd.hp-hps',
        'hqx' => 'application/mac-binhex40',
        'hta' => 'application/octet-stream',
        'htc' => 'text/html',
        'htke' => 'application/vnd.kenameaapp',
        'htm' => 'text/html',
        'html' => 'text/html',
        'hvd' => 'application/vnd.yamaha.hv-dic',
        'hvp' => 'application/vnd.yamaha.hv-voice',
        'hvs' => 'application/vnd.yamaha.hv-script',
        'i2g' => 'application/vnd.intergeo',
        'icc' => 'application/vnd.iccprofile',
        'ice' => 'x-conference/x-cooltalk',
        'icm' => 'application/vnd.iccprofile',
        'ico' => 'image/x-icon',
        'ics' => 'text/calendar',
        'ief' => 'image/ief',
        'ifb' => 'text/calendar',
        'ifm' => 'application/vnd.shana.informed.formdata',
        'iges' => 'model/iges',
        'igl' => 'application/vnd.igloader',
        'igm' => 'application/vnd.insors.igm',
        'igs' => 'model/iges',
        'igx' => 'application/vnd.micrografx.igx',
        'iif' => 'application/vnd.shana.informed.interchange',
        'imp' => 'application/vnd.accpac.simply.imp',
        'ims' => 'application/vnd.ms-ims',
        'in' => 'text/plain',
        'ini' => 'text/plain',
        'ipfix' => 'application/ipfix',
        'ipk' => 'application/vnd.shana.informed.package',
        'irm' => 'application/vnd.ibm.rights-management',
        'irp' => 'application/vnd.irepository.package+xml',
        'iso' => 'application/octet-stream',
        'itp' => 'application/vnd.shana.informed.formtemplate',
        'ivp' => 'application/vnd.immervision-ivp',
        'ivu' => 'application/vnd.immervision-ivu',
        'jad' => 'text/vnd.sun.j2me.app-descriptor',
        'jam' => 'application/vnd.jam',
        'jar' => 'application/java-archive',
        'java' => 'text/x-java-source',
        'jisp' => 'application/vnd.jisp',
        'jlt' => 'application/vnd.hp-jlyt',
        'jnlp' => 'application/x-java-jnlp-file',
        'joda' => 'application/vnd.joost.joda-archive',
        'jpe' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'jpg' => 'image/jpeg',
        'jpgm' => 'video/jpm',
        'jpgv' => 'video/jpeg',
        'jpm' => 'video/jpm',
        'js' => 'text/javascript',
        'json' => 'application/json',
        'kar' => 'audio/midi',
        'karbon' => 'application/vnd.kde.karbon',
        'kfo' => 'application/vnd.kde.kformula',
        'kia' => 'application/vnd.kidspiration',
        'kml' => 'application/vnd.google-earth.kml+xml',
        'kmz' => 'application/vnd.google-earth.kmz',
        'kne' => 'application/vnd.kinar',
        'knp' => 'application/vnd.kinar',
        'kon' => 'application/vnd.kde.kontour',
        'kpr' => 'application/vnd.kde.kpresenter',
        'kpt' => 'application/vnd.kde.kpresenter',
        'ksp' => 'application/vnd.kde.kspread',
        'ktr' => 'application/vnd.kahootz',
        'ktx' => 'image/ktx',
        'ktz' => 'application/vnd.kahootz',
        'kwd' => 'application/vnd.kde.kword',
        'kwt' => 'application/vnd.kde.kword',
        'lasxml' => 'application/vnd.las.las+xml',
        'latex' => 'application/x-latex',
        'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',
        'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',
        'les' => 'application/vnd.hhe.lesson-player',
        'lha' => 'application/octet-stream',
        'link66' => 'application/vnd.route66.link66+xml',
        'list' => 'text/plain',
        'list3820' => 'application/vnd.ibm.modcap',
        'listafp' => 'application/vnd.ibm.modcap',
        'log' => 'text/plain',
        'lostxml' => 'application/lost+xml',
        'lrf' => 'application/octet-stream',
        'lrm' => 'application/vnd.ms-lrm',
        'ltf' => 'application/vnd.frogans.ltf',
        'lvp' => 'audio/vnd.lucent.voice',
        'lwp' => 'application/vnd.lotus-wordpro',
        'lzh' => 'application/octet-stream',
        'm13' => 'application/x-msmediaview',
        'm14' => 'application/x-msmediaview',
        'm1v' => 'video/mpeg',
        'm21' => 'application/mp21',
        'm2a' => 'audio/mpeg',
        'm2v' => 'video/mpeg',
        'm3a' => 'audio/mpeg',
        'm3u' => 'audio/x-mpegurl',
        'm3u8' => 'application/vnd.apple.mpegurl',
        'm4a' => 'audio/mp4',
        'm4u' => 'video/vnd.mpegurl',
        'm4v' => 'video/mp4',
        'ma' => 'application/mathematica',
        'mads' => 'application/mads+xml',
        'mag' => 'application/vnd.ecowin.chart',
        'maker' => 'application/vnd.framemaker',
        'man' => 'text/troff',
        'mathml' => 'application/mathml+xml',
        'mb' => 'application/mathematica',
        'mbk' => 'application/vnd.mobius.mbk',
        'mbox' => 'application/mbox',
        'mc1' => 'application/vnd.medcalcdata',
        'mcd' => 'application/vnd.mcd',
        'mcurl' => 'text/vnd.curl.mcurl',
        'mdb' => 'application/x-msaccess',
        'mdi' => 'image/vnd.ms-modi',
        'me' => 'text/troff',
        'mesh' => 'model/mesh',
        'meta4' => 'application/metalink4+xml',
        'mets' => 'application/mets+xml',
        'mfm' => 'application/vnd.mfmp',
        'mgp' => 'application/vnd.osgeo.mapguide.package',
        'mgz' => 'application/vnd.proteus.magazine',
        'mid' => 'audio/midi',
        'midi' => 'audio/midi',
        'mif' => 'application/vnd.mif',
        'mime' => 'message/rfc822',
        'mj2' => 'video/mj2',
        'mjp2' => 'video/mj2',
        'mlp' => 'application/vnd.dolby.mlp',
        'mmd' => 'application/vnd.chipnuts.karaoke-mmd',
        'mmf' => 'application/vnd.smaf',
        'mmr' => 'image/vnd.fujixerox.edmics-mmr',
        'mny' => 'application/x-msmoney',
        'mobi' => 'application/x-mobipocket-ebook',
        'mods' => 'application/mods+xml',
        'mov' => 'video/quicktime',
        'movie' => 'video/x-sgi-movie',
        'mp2' => 'audio/mpeg',
        'mp21' => 'application/mp21',
        'mp2a' => 'audio/mpeg',
        'mp3' => 'audio/mpeg',
        'mp4' => 'video/mp4',
        'mp4a' => 'audio/mp4',
        'mp4s' => 'application/mp4',
        'mp4v' => 'video/mp4',
        'mpc' => 'application/vnd.mophun.certificate',
        'mpe' => 'video/mpeg',
        'mpeg' => 'video/mpeg',
        'mpg' => 'video/mpeg',
        'mpg4' => 'video/mp4',
        'mpga' => 'audio/mpeg',
        'mpkg' => 'application/vnd.apple.installer+xml',
        'mpm' => 'application/vnd.blueice.multipass',
        'mpn' => 'application/vnd.mophun.application',
        'mpp' => 'application/vnd.ms-project',
        'mpt' => 'application/vnd.ms-project',
        'mpy' => 'application/vnd.ibm.minipay',
        'mqy' => 'application/vnd.mobius.mqy',
        'mrc' => 'application/marc',
        'mrcx' => 'application/marcxml+xml',
        'ms' => 'text/troff',
        'mscml' => 'application/mediaservercontrol+xml',
        'mseed' => 'application/vnd.fdsn.mseed',
        'mseq' => 'application/vnd.mseq',
        'msf' => 'application/vnd.epson.msf',
        'msh' => 'model/mesh',
        'msi' => 'application/x-msdownload',
        'msl' => 'application/vnd.mobius.msl',
        'msty' => 'application/vnd.muvee.style',
        'mts' => 'model/vnd.mts',
        'mus' => 'application/vnd.musician',
        'musicxml' => 'application/vnd.recordare.musicxml+xml',
        'mvb' => 'application/x-msmediaview',
        'mwf' => 'application/vnd.mfer',
        'mxf' => 'application/mxf',
        'mxl' => 'application/vnd.recordare.musicxml',
        'mxml' => 'application/xv+xml',
        'mxs' => 'application/vnd.triscape.mxs',
        'mxu' => 'video/vnd.mpegurl',
        'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',
        'n3' => 'text/n3',
        'nb' => 'application/mathematica',
        'nbp' => 'application/vnd.wolfram.player',
        'nc' => 'application/x-netcdf',
        'ncx' => 'application/x-dtbncx+xml',
        'ngdat' => 'application/vnd.nokia.n-gage.data',
        'nlu' => 'application/vnd.neurolanguage.nlu',
        'nml' => 'application/vnd.enliven',
        'nnd' => 'application/vnd.noblenet-directory',
        'nns' => 'application/vnd.noblenet-sealer',
        'nnw' => 'application/vnd.noblenet-web',
        'npx' => 'image/vnd.net-fpx',
        'nsf' => 'application/vnd.lotus-notes',
        'oa2' => 'application/vnd.fujitsu.oasys2',
        'oa3' => 'application/vnd.fujitsu.oasys3',
        'oas' => 'application/vnd.fujitsu.oasys',
        'obd' => 'application/x-msbinder',
        'oda' => 'application/oda',
        'odb' => 'application/vnd.oasis.opendocument.database',
        'odc' => 'application/vnd.oasis.opendocument.chart',
        'odf' => 'application/vnd.oasis.opendocument.formula',
        'odft' => 'application/vnd.oasis.opendocument.formula-template',
        'odg' => 'application/vnd.oasis.opendocument.graphics',
        'odi' => 'application/vnd.oasis.opendocument.image',
        'odm' => 'application/vnd.oasis.opendocument.text-master',
        'odp' => 'application/vnd.oasis.opendocument.presentation',
        'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        'odt' => 'application/vnd.oasis.opendocument.text',
        'oga' => 'audio/ogg',
        'ogg' => 'audio/ogg',
        'ogv' => 'video/ogg',
        'ogx' => 'application/ogg',
        'onepkg' => 'application/onenote',
        'onetmp' => 'application/onenote',
        'onetoc' => 'application/onenote',
        'onetoc2' => 'application/onenote',
        'opf' => 'application/oebps-package+xml',
        'oprc' => 'application/vnd.palm',
        'org' => 'application/vnd.lotus-organizer',
        'osf' => 'application/vnd.yamaha.openscoreformat',
        'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml',
        'otc' => 'application/vnd.oasis.opendocument.chart-template',
        'otf' => 'application/x-font-otf',
        'otg' => 'application/vnd.oasis.opendocument.graphics-template',
        'oth' => 'application/vnd.oasis.opendocument.text-web',
        'oti' => 'application/vnd.oasis.opendocument.image-template',
        'otp' => 'application/vnd.oasis.opendocument.presentation-template',
        'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
        'ott' => 'application/vnd.oasis.opendocument.text-template',
        'oxt' => 'application/vnd.openofficeorg.extension',
        'p' => 'text/x-pascal',
        'p10' => 'application/pkcs10',
        'p12' => 'application/x-pkcs12',
        'p7b' => 'application/x-pkcs7-certificates',
        'p7c' => 'application/pkcs7-mime',
        'p7m' => 'application/pkcs7-mime',
        'p7r' => 'application/x-pkcs7-certreqresp',
        'p7s' => 'application/pkcs7-signature',
        'p8' => 'application/pkcs8',
        'pas' => 'text/x-pascal',
        'paw' => 'application/vnd.pawaafile',
        'pbd' => 'application/vnd.powerbuilder6',
        'pbm' => 'image/x-portable-bitmap',
        'pcf' => 'application/x-font-pcf',
        'pcl' => 'application/vnd.hp-pcl',
        'pclxl' => 'application/vnd.hp-pclxl',
        'pct' => 'image/x-pict',
        'pcurl' => 'application/vnd.curl.pcurl',
        'pcx' => 'image/x-pcx',
        'pdb' => 'application/vnd.palm',
        'pdf' => 'application/pdf',
        'pfa' => 'application/x-font-type1',
        'pfb' => 'application/x-font-type1',
        'pfm' => 'application/x-font-type1',
        'pfr' => 'application/font-tdpfr',
        'pfx' => 'application/x-pkcs12',
        'pgm' => 'image/x-portable-graymap',
        'pgn' => 'application/x-chess-pgn',
        'pgp' => 'application/pgp-encrypted',
        'php' => 'text/x-php',
        'phps' => 'application/x-httpd-phps',
        'pic' => 'image/x-pict',
        'pkg' => 'application/octet-stream',
        'pki' => 'application/pkixcmp',
        'pkipath' => 'application/pkix-pkipath',
        'plb' => 'application/vnd.3gpp.pic-bw-large',
        'plc' => 'application/vnd.mobius.plc',
        'plf' => 'application/vnd.pocketlearn',
        'pls' => 'application/pls+xml',
        'pml' => 'application/vnd.ctc-posml',
        'png' => 'image/png',
        'pnm' => 'image/x-portable-anymap',
        'portpkg' => 'application/vnd.macports.portpkg',
        'pot' => 'application/vnd.ms-powerpoint',
        'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12',
        'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
        'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12',
        'ppd' => 'application/vnd.cups-ppd',
        'ppm' => 'image/x-portable-pixmap',
        'pps' => 'application/vnd.ms-powerpoint',
        'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
        'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
        'ppt' => 'application/vnd.ms-powerpoint',
        'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
        'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'pqa' => 'application/vnd.palm',
        'prc' => 'application/x-mobipocket-ebook',
        'pre' => 'application/vnd.lotus-freelance',
        'prf' => 'application/pics-rules',
        'ps' => 'application/postscript',
        'psb' => 'application/vnd.3gpp.pic-bw-small',
        'psd' => 'image/vnd.adobe.photoshop',
        'psf' => 'application/x-font-linux-psf',
        'pskcxml' => 'application/pskc+xml',
        'ptid' => 'application/vnd.pvi.ptid1',
        'pub' => 'application/x-mspublisher',
        'pvb' => 'application/vnd.3gpp.pic-bw-var',
        'pwn' => 'application/vnd.3m.post-it-notes',
        'pya' => 'audio/vnd.ms-playready.media.pya',
        'pyv' => 'video/vnd.ms-playready.media.pyv',
        'qam' => 'application/vnd.epson.quickanime',
        'qbo' => 'application/vnd.intu.qbo',
        'qfx' => 'application/vnd.intu.qfx',
        'qps' => 'application/vnd.publishare-delta-tree',
        'qt' => 'video/quicktime',
        'qwd' => 'application/vnd.quark.quarkxpress',
        'qwt' => 'application/vnd.quark.quarkxpress',
        'qxb' => 'application/vnd.quark.quarkxpress',
        'qxd' => 'application/vnd.quark.quarkxpress',
        'qxl' => 'application/vnd.quark.quarkxpress',
        'qxt' => 'application/vnd.quark.quarkxpress',
        'ra' => 'audio/x-pn-realaudio',
        'ram' => 'audio/x-pn-realaudio',
        'rar' => 'application/x-rar-compressed',
        'ras' => 'image/x-cmu-raster',
        'rb' => 'text/plain',
        'rcprofile' => 'application/vnd.ipunplugged.rcprofile',
        'rdf' => 'application/rdf+xml',
        'rdz' => 'application/vnd.data-vision.rdz',
        'rep' => 'application/vnd.businessobjects',
        'res' => 'application/x-dtbresource+xml',
        'resx' => 'text/xml',
        'rgb' => 'image/x-rgb',
        'rif' => 'application/reginfo+xml',
        'rip' => 'audio/vnd.rip',
        'rl' => 'application/resource-lists+xml',
        'rlc' => 'image/vnd.fujixerox.edmics-rlc',
        'rld' => 'application/resource-lists-diff+xml',
        'rm' => 'application/vnd.rn-realmedia',
        'rmi' => 'audio/midi',
        'rmp' => 'audio/x-pn-realaudio-plugin',
        'rms' => 'application/vnd.jcp.javame.midlet-rms',
        'rnc' => 'application/relax-ng-compact-syntax',
        'roff' => 'text/troff',
        'rp9' => 'application/vnd.cloanto.rp9',
        'rpss' => 'application/vnd.nokia.radio-presets',
        'rpst' => 'application/vnd.nokia.radio-preset',
        'rq' => 'application/sparql-query',
        'rs' => 'application/rls-services+xml',
        'rsd' => 'application/rsd+xml',
        'rss' => 'application/rss+xml',
        'rtf' => 'application/rtf',
        'rtx' => 'text/richtext',
        's' => 'text/x-asm',
        'saf' => 'application/vnd.yamaha.smaf-audio',
        'sbml' => 'application/sbml+xml',
        'sc' => 'application/vnd.ibm.secure-container',
        'scd' => 'application/x-msschedule',
        'scm' => 'application/vnd.lotus-screencam',
        'scq' => 'application/scvp-cv-request',
        'scs' => 'application/scvp-cv-response',
        'scurl' => 'text/vnd.curl.scurl',
        'sda' => 'application/vnd.stardivision.draw',
        'sdc' => 'application/vnd.stardivision.calc',
        'sdd' => 'application/vnd.stardivision.impress',
        'sdkd' => 'application/vnd.solent.sdkm+xml',
        'sdkm' => 'application/vnd.solent.sdkm+xml',
        'sdp' => 'application/sdp',
        'sdw' => 'application/vnd.stardivision.writer',
        'see' => 'application/vnd.seemail',
        'seed' => 'application/vnd.fdsn.seed',
        'sema' => 'application/vnd.sema',
        'semd' => 'application/vnd.semd',
        'semf' => 'application/vnd.semf',
        'ser' => 'application/java-serialized-object',
        'setpay' => 'application/set-payment-initiation',
        'setreg' => 'application/set-registration-initiation',
        'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data',
        'sfs' => 'application/vnd.spotfire.sfs',
        'sgl' => 'application/vnd.stardivision.writer-global',
        'sgm' => 'text/sgml',
        'sgml' => 'text/sgml',
        'sh' => 'application/x-sh',
        'shar' => 'application/x-shar',
        'shf' => 'application/shf+xml',
        'sig' => 'application/pgp-signature',
        'silo' => 'model/mesh',
        'sis' => 'application/vnd.symbian.install',
        'sisx' => 'application/vnd.symbian.install',
        'sit' => 'application/x-stuffit',
        'sitx' => 'application/x-stuffitx',
        'skd' => 'application/vnd.koan',
        'skm' => 'application/vnd.koan',
        'skp' => 'application/vnd.koan',
        'skt' => 'application/vnd.koan',
        'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12',
        'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
        'slt' => 'application/vnd.epson.salt',
        'sm' => 'application/vnd.stepmania.stepchart',
        'smf' => 'application/vnd.stardivision.math',
        'smi' => 'application/smil+xml',
        'smil' => 'application/smil+xml',
        'snd' => 'audio/basic',
        'snf' => 'application/x-font-snf',
        'so' => 'application/octet-stream',
        'spc' => 'application/x-pkcs7-certificates',
        'spf' => 'application/vnd.yamaha.smaf-phrase',
        'spl' => 'application/x-futuresplash',
        'spot' => 'text/vnd.in3d.spot',
        'spp' => 'application/scvp-vp-response',
        'spq' => 'application/scvp-vp-request',
        'spx' => 'audio/ogg',
        'src' => 'application/x-wais-source',
        'sru' => 'application/sru+xml',
        'srx' => 'application/sparql-results+xml',
        'sse' => 'application/vnd.kodak-descriptor',
        'ssf' => 'application/vnd.epson.ssf',
        'ssml' => 'application/ssml+xml',
        'st' => 'application/vnd.sailingtracker.track',
        'stc' => 'application/vnd.sun.xml.calc.template',
        'std' => 'application/vnd.sun.xml.draw.template',
        'stf' => 'application/vnd.wt.stf',
        'sti' => 'application/vnd.sun.xml.impress.template',
        'stk' => 'application/hyperstudio',
        'stl' => 'application/vnd.ms-pki.stl',
        'str' => 'application/vnd.pg.format',
        'stw' => 'application/vnd.sun.xml.writer.template',
        'sub' => 'image/vnd.dvb.subtitle',
        'sus' => 'application/vnd.sus-calendar',
        'susp' => 'application/vnd.sus-calendar',
        'sv4cpio' => 'application/x-sv4cpio',
        'sv4crc' => 'application/x-sv4crc',
        'svc' => 'application/vnd.dvb.service',
        'svd' => 'application/vnd.svd',
        'svg' => 'image/svg+xml',
        'svgz' => 'image/svg+xml',
        'swa' => 'application/x-director',
        'swf' => 'application/x-shockwave-flash',
        'swi' => 'application/vnd.aristanetworks.swi',
        'sxc' => 'application/vnd.sun.xml.calc',
        'sxd' => 'application/vnd.sun.xml.draw',
        'sxg' => 'application/vnd.sun.xml.writer.global',
        'sxi' => 'application/vnd.sun.xml.impress',
        'sxm' => 'application/vnd.sun.xml.math',
        'sxw' => 'application/vnd.sun.xml.writer',
        't' => 'text/troff',
        'tao' => 'application/vnd.tao.intent-module-archive',
        'tar' => 'application/x-tar',
        'tcap' => 'application/vnd.3gpp2.tcap',
        'tcl' => 'application/x-tcl',
        'teacher' => 'application/vnd.smart.teacher',
        'tei' => 'application/tei+xml',
        'teicorpus' => 'application/tei+xml',
        'tex' => 'application/x-tex',
        'texi' => 'application/x-texinfo',
        'texinfo' => 'application/x-texinfo',
        'text' => 'text/plain',
        'tfi' => 'application/thraud+xml',
        'tfm' => 'application/x-tex-tfm',
        'thmx' => 'application/vnd.ms-officetheme',
        'tif' => 'image/tiff',
        'tiff' => 'image/tiff',
        'tmo' => 'application/vnd.tmobile-livetv',
        'torrent' => 'application/x-bittorrent',
        'tpl' => 'application/vnd.groove-tool-template',
        'tpt' => 'application/vnd.trid.tpt',
        'tr' => 'text/troff',
        'tra' => 'application/vnd.trueapp',
        'trm' => 'application/x-msterminal',
        'tsd' => 'application/timestamped-data',
        'tsv' => 'text/tab-separated-values',
        'ttc' => 'application/x-font-ttf',
        'ttf' => 'application/x-font-ttf',
        'ttl' => 'text/turtle',
        'twd' => 'application/vnd.simtech-mindmapper',
        'twds' => 'application/vnd.simtech-mindmapper',
        'txd' => 'application/vnd.genomatix.tuxedo',
        'txf' => 'application/vnd.mobius.txf',
        'txt' => 'text/plain',
        'u32' => 'application/x-authorware-bin',
        'udeb' => 'application/x-debian-package',
        'ufd' => 'application/vnd.ufdl',
        'ufdl' => 'application/vnd.ufdl',
        'umj' => 'application/vnd.umajin',
        'unityweb' => 'application/vnd.unity',
        'uoml' => 'application/vnd.uoml+xml',
        'uri' => 'text/uri-list',
        'uris' => 'text/uri-list',
        'urls' => 'text/uri-list',
        'ustar' => 'application/x-ustar',
        'utz' => 'application/vnd.uiq.theme',
        'uu' => 'text/x-uuencode',
        'uva' => 'audio/vnd.dece.audio',
        'uvd' => 'application/vnd.dece.data',
        'uvf' => 'application/vnd.dece.data',
        'uvg' => 'image/vnd.dece.graphic',
        'uvh' => 'video/vnd.dece.hd',
        'uvi' => 'image/vnd.dece.graphic',
        'uvm' => 'video/vnd.dece.mobile',
        'uvp' => 'video/vnd.dece.pd',
        'uvs' => 'video/vnd.dece.sd',
        'uvt' => 'application/vnd.dece.ttml+xml',
        'uvu' => 'video/vnd.uvvu.mp4',
        'uvv' => 'video/vnd.dece.video',
        'uvva' => 'audio/vnd.dece.audio',
        'uvvd' => 'application/vnd.dece.data',
        'uvvf' => 'application/vnd.dece.data',
        'uvvg' => 'image/vnd.dece.graphic',
        'uvvh' => 'video/vnd.dece.hd',
        'uvvi' => 'image/vnd.dece.graphic',
        'uvvm' => 'video/vnd.dece.mobile',
        'uvvp' => 'video/vnd.dece.pd',
        'uvvs' => 'video/vnd.dece.sd',
        'uvvt' => 'application/vnd.dece.ttml+xml',
        'uvvu' => 'video/vnd.uvvu.mp4',
        'uvvv' => 'video/vnd.dece.video',
        'uvvx' => 'application/vnd.dece.unspecified',
        'uvx' => 'application/vnd.dece.unspecified',
        'vcd' => 'application/x-cdlink',
        'vcf' => 'text/x-vcard',
        'vcg' => 'application/vnd.groove-vcard',
        'vcs' => 'text/x-vcalendar',
        'vcx' => 'application/vnd.vcx',
        'vis' => 'application/vnd.visionary',
        'viv' => 'video/vnd.vivo',
        'vor' => 'application/vnd.stardivision.writer',
        'vox' => 'application/x-authorware-bin',
        'vrml' => 'model/vrml',
        'vsd' => 'application/vnd.visio',
        'vsf' => 'application/vnd.vsf',
        'vss' => 'application/vnd.visio',
        'vst' => 'application/vnd.visio',
        'vsw' => 'application/vnd.visio',
        'vtu' => 'model/vnd.vtu',
        'vxml' => 'application/voicexml+xml',
        'w3d' => 'application/x-director',
        'wad' => 'application/x-doom',
        'wav' => 'audio/x-wav',
        'wax' => 'audio/x-ms-wax',
        'wbmp' => 'image/vnd.wap.wbmp',
        'wbs' => 'application/vnd.criticaltools.wbs+xml',
        'wbxml' => 'application/vnd.wap.wbxml',
        'wcm' => 'application/vnd.ms-works',
        'wdb' => 'application/vnd.ms-works',
        'weba' => 'audio/webm',
        'webm' => 'video/webm',
        'webp' => 'image/webp',
        'wg' => 'application/vnd.pmi.widget',
        'wgt' => 'application/widget',
        'wks' => 'application/vnd.ms-works',
        'wm' => 'video/x-ms-wm',
        'wma' => 'audio/x-ms-wma',
        'wmd' => 'application/x-ms-wmd',
        'wmf' => 'application/x-msmetafile',
        'wml' => 'text/vnd.wap.wml',
        'wmlc' => 'application/vnd.wap.wmlc',
        'wmls' => 'text/vnd.wap.wmlscript',
        'wmlsc' => 'application/vnd.wap.wmlscriptc',
        'wmv' => 'video/x-ms-wmv',
        'wmx' => 'video/x-ms-wmx',
        'wmz' => 'application/x-ms-wmz',
        'woff' => 'application/x-font-woff',
        'wpd' => 'application/vnd.wordperfect',
        'wpl' => 'application/vnd.ms-wpl',
        'wps' => 'application/vnd.ms-works',
        'wqd' => 'application/vnd.wqd',
        'wri' => 'application/x-mswrite',
        'wrl' => 'model/vrml',
        'wsdl' => 'application/wsdl+xml',
        'wspolicy' => 'application/wspolicy+xml',
        'wtb' => 'application/vnd.webturbo',
        'wvx' => 'video/x-ms-wvx',
        'x32' => 'application/x-authorware-bin',
        'x3d' => 'application/vnd.hzn-3d-crossword',
        'xap' => 'application/x-silverlight-app',
        'xar' => 'application/vnd.xara',
        'xbap' => 'application/x-ms-xbap',
        'xbd' => 'application/vnd.fujixerox.docuworks.binder',
        'xbm' => 'image/x-xbitmap',
        'xdf' => 'application/xcap-diff+xml',
        'xdm' => 'application/vnd.syncml.dm+xml',
        'xdp' => 'application/vnd.adobe.xdp+xml',
        'xdssc' => 'application/dssc+xml',
        'xdw' => 'application/vnd.fujixerox.docuworks',
        'xenc' => 'application/xenc+xml',
        'xer' => 'application/patch-ops-error+xml',
        'xfdf' => 'application/vnd.adobe.xfdf',
        'xfdl' => 'application/vnd.xfdl',
        'xht' => 'application/xhtml+xml',
        'xhtml' => 'application/xhtml+xml',
        'xhvml' => 'application/xv+xml',
        'xif' => 'image/vnd.xiff',
        'xla' => 'application/vnd.ms-excel',
        'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12',
        'xlc' => 'application/vnd.ms-excel',
        'xlm' => 'application/vnd.ms-excel',
        'xls' => 'application/vnd.ms-excel',
        'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
        'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xlt' => 'application/vnd.ms-excel',
        'xltm' => 'application/vnd.ms-excel.template.macroenabled.12',
        'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
        'xlw' => 'application/vnd.ms-excel',
        'xml' => 'application/xml',
        'xo' => 'application/vnd.olpc-sugar',
        'xop' => 'application/xop+xml',
        'xpi' => 'application/x-xpinstall',
        'xpm' => 'image/x-xpixmap',
        'xpr' => 'application/vnd.is-xpr',
        'xps' => 'application/vnd.ms-xpsdocument',
        'xpw' => 'application/vnd.intercon.formnet',
        'xpx' => 'application/vnd.intercon.formnet',
        'xsl' => 'application/xml',
        'xslt' => 'application/xslt+xml',
        'xsm' => 'application/vnd.syncml+xml',
        'xspf' => 'application/xspf+xml',
        'xul' => 'application/vnd.mozilla.xul+xml',
        'xvm' => 'application/xv+xml',
        'xvml' => 'application/xv+xml',
        'xwd' => 'image/x-xwindowdump',
        'xyz' => 'chemical/x-xyz',
        'yaml' => 'text/yaml',
        'yang' => 'application/yang',
        'yin' => 'application/yin+xml',
        'yml' => 'text/yaml',
        'zaz' => 'application/vnd.zzazz.deck+xml',
        'zip' => 'application/zip',
        'zir' => 'application/vnd.zul',
        'zirz' => 'application/vnd.zul',
        'zmm' => 'application/vnd.handheld-entertainment+xml'
    );

    /**
     * Get a singleton instance of the class
     *
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Get a mimetype value from a file extension
     *
     * @param string $extension File extension
     *
     * @return string|null
     *
     */
    public function fromExtension($extension)
    {
        $extension = strtolower($extension);

        return isset($this->mimetypes[$extension]) ? $this->mimetypes[$extension] : null;
    }

    /**
     * Get a mimetype from a filename
     *
     * @param string $filename Filename to generate a mimetype from
     *
     * @return string|null
     */
    public function fromFilename($filename)
    {
        return $this->fromExtension(pathinfo($filename, PATHINFO_EXTENSION));
    }
}
<?php

namespace Guzzle\Http\QueryAggregator;

use Guzzle\Http\QueryString;

/**
 * Interface used for aggregating nested query string variables into a flattened array of key value pairs
 */
interface QueryAggregatorInterface
{
    /**
     * Aggregate multi-valued parameters into a flattened associative array
     *
     * @param string      $key   The name of the query string parameter
     * @param array       $value The values of the parameter
     * @param QueryString $query The query string that is being aggregated
     *
     * @return array Returns an array of the combined values
     */
    public function aggregate($key, $value, QueryString $query);
}
<?php

namespace Guzzle\Http\QueryAggregator;

use Guzzle\Http\QueryString;

/**
 * Aggregates nested query string variables using commas
 */
class CommaAggregator implements QueryAggregatorInterface
{
    public function aggregate($key, $value, QueryString $query)
    {
        if ($query->isUrlEncoding()) {
            return array($query->encodeValue($key) => implode(',', array_map(array($query, 'encodeValue'), $value)));
        } else {
            return array($key => implode(',', $value));
        }
    }
}
<?php

namespace Guzzle\Http\QueryAggregator;

use Guzzle\Http\QueryString;

/**
 * Aggregates nested query string variables using PHP style []
 */
class PhpAggregator implements QueryAggregatorInterface
{
    public function aggregate($key, $value, QueryString $query)
    {
        $ret = array();

        foreach ($value as $k => $v) {
            $k = "{$key}[{$k}]";
            if (is_array($v)) {
                $ret = array_merge($ret, self::aggregate($k, $v, $query));
            } else {
                $ret[$query->encodeValue($k)] = $query->encodeValue($v);
            }
        }

        return $ret;
    }
}
<?php

namespace Guzzle\Http\QueryAggregator;

use Guzzle\Http\QueryString;

/**
 * Does not aggregate nested query string values and allows duplicates in the resulting array
 *
 * Example: http://test.com?q=1&q=2
 */
class DuplicateAggregator implements QueryAggregatorInterface
{
    public function aggregate($key, $value, QueryString $query)
    {
        if ($query->isUrlEncoding()) {
            return array($query->encodeValue($key) => array_map(array($query, 'encodeValue'), $value));
        } else {
            return array($key => $value);
        }
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Version;
use Guzzle\Stream\Stream;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Mimetypes;

/**
 * Entity body used with an HTTP request or response
 */
class EntityBody extends Stream implements EntityBodyInterface
{
    /** @var bool Content-Encoding of the entity body if known */
    protected $contentEncoding = false;

    /** @var callable Method to invoke for rewinding a stream */
    protected $rewindFunction;

    /**
     * Create a new EntityBody based on the input type
     *
     * @param resource|string|EntityBody $resource Entity body data
     * @param int                        $size     Size of the data contained in the resource
     *
     * @return EntityBody
     * @throws InvalidArgumentException if the $resource arg is not a resource or string
     */
    public static function factory($resource = '', $size = null)
    {
        if ($resource instanceof EntityBodyInterface) {
            return $resource;
        }

        switch (gettype($resource)) {
            case 'string':
                return self::fromString($resource);
            case 'resource':
                return new static($resource, $size);
            case 'object':
                if (method_exists($resource, '__toString')) {
                    return self::fromString((string) $resource);
                }
                break;
            case 'array':
                return self::fromString(http_build_query($resource));
        }

        throw new InvalidArgumentException('Invalid resource type');
    }

    public function setRewindFunction($callable)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('Must specify a callable');
        }

        $this->rewindFunction = $callable;

        return $this;
    }

    public function rewind()
    {
        return $this->rewindFunction ? call_user_func($this->rewindFunction, $this) : parent::rewind();
    }

    /**
     * Create a new EntityBody from a string
     *
     * @param string $string String of data
     *
     * @return EntityBody
     */
    public static function fromString($string)
    {
        $stream = fopen('php://temp', 'r+');
        if ($string !== '') {
            fwrite($stream, $string);
            rewind($stream);
        }

        return new static($stream);
    }

    public function compress($filter = 'zlib.deflate')
    {
        $result = $this->handleCompression($filter);
        $this->contentEncoding = $result ? $filter : false;

        return $result;
    }

    public function uncompress($filter = 'zlib.inflate')
    {
        $offsetStart = 0;

        // When inflating gzipped data, the first 10 bytes must be stripped
        // if a gzip header is present
        if ($filter == 'zlib.inflate') {
            // @codeCoverageIgnoreStart
            if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
                return false;
            }
            // @codeCoverageIgnoreEnd
            if (stream_get_contents($this->stream, 3, 0) === "\x1f\x8b\x08") {
                $offsetStart = 10;
            }
        }

        $this->contentEncoding = false;

        return $this->handleCompression($filter, $offsetStart);
    }

    public function getContentLength()
    {
        return $this->getSize();
    }

    public function getContentType()
    {
        return $this->getUri() ? Mimetypes::getInstance()->fromFilename($this->getUri()) : null;
    }

    public function getContentMd5($rawOutput = false, $base64Encode = false)
    {
        if ($hash = self::getHash($this, 'md5', $rawOutput)) {
            return $hash && $base64Encode ? base64_encode($hash) : $hash;
        } else {
            return false;
        }
    }

    /**
     * Calculate the MD5 hash of an entity body
     *
     * @param EntityBodyInterface $body         Entity body to calculate the hash for
     * @param bool                $rawOutput    Whether or not to use raw output
     * @param bool                $base64Encode Whether or not to base64 encode raw output (only if raw output is true)
     *
     * @return bool|string Returns an MD5 string on success or FALSE on failure
     * @deprecated This will be deprecated soon
     * @codeCoverageIgnore
     */
    public static function calculateMd5(EntityBodyInterface $body, $rawOutput = false, $base64Encode = false)
    {
        Version::warn(__CLASS__ . ' is deprecated. Use getContentMd5()');
        return $body->getContentMd5($rawOutput, $base64Encode);
    }

    public function setStreamFilterContentEncoding($streamFilterContentEncoding)
    {
        $this->contentEncoding = $streamFilterContentEncoding;

        return $this;
    }

    public function getContentEncoding()
    {
        return strtr($this->contentEncoding, array(
            'zlib.deflate' => 'gzip',
            'bzip2.compress' => 'compress'
        )) ?: false;
    }

    protected function handleCompression($filter, $offsetStart = 0)
    {
        // @codeCoverageIgnoreStart
        if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
            return false;
        }
        // @codeCoverageIgnoreEnd

        $handle = fopen('php://temp', 'r+');
        $filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE);
        if (!$filter) {
            return false;
        }

        // Seek to the offset start if possible
        $this->seek($offsetStart);
        while ($data = fread($this->stream, 8096)) {
            fwrite($handle, $data);
        }

        fclose($this->stream);
        $this->stream = $handle;
        stream_filter_remove($filter);
        $stat = fstat($this->stream);
        $this->size = $stat['size'];
        $this->rebuildCache();
        $this->seek(0);

        // Remove any existing rewind function as the underlying stream has been replaced
        $this->rewindFunction = null;

        return true;
    }
}
##
## Bundle of CA Root Certificates
##
## Certificate data from Mozilla downloaded on: Wed Aug 13 21:49:32 2014
##
## This is a bundle of X.509 certificates of public Certificate Authorities
## (CA). These were automatically extracted from Mozilla's root certificates
## file (certdata.txt).  This file can be found in the mozilla source tree:
## http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt
##
## It contains the certificates in PEM format and therefore
## can be directly used with curl / libcurl / php_curl, or with
## an Apache+mod_ssl webserver for SSL client authentication.
## Just configure this file as the SSLCACertificateFile.
##
## Conversion done with mk-ca-bundle.pl verison 1.22.
## SHA1: bf2c15b3019e696660321d2227d942936dc50aa7
##


GTE CyberTrust Global Root
==========================
-----BEGIN CERTIFICATE-----
MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUg
Q29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEG
A1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEz
MjM1OTAwWjB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQL
Ex5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0
IEdsb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrHiM3dFw4u
sJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTSr41tiGeA5u2ylc9yMcql
HHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X404Wqk2kmhXBIgD8SFcd5tB8FLztimQID
AQABMA0GCSqGSIb3DQEBBAUAA4GBAG3rGwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMW
M4ETCJ57NE7fQMh017l93PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OF
NMQkpw0PlZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/
-----END CERTIFICATE-----

Thawte Server CA
================
-----BEGIN CERTIFICATE-----
MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT
DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs
dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UE
AxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5j
b20wHhcNOTYwODAxMDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNV
BAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29u
c3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcG
A1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0
ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl
/Kj0R1HahbUgdJSGHg91yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg7
1CcEJRCXL+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGjEzAR
MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG7oWDTSEwjsrZqG9J
GubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6eQNuozDJ0uW8NxuOzRAvZim+aKZuZ
GCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZqdq5snUb9kLy78fyGPmJvKP/iiMucEc=
-----END CERTIFICATE-----

Thawte Premium Server CA
========================
-----BEGIN CERTIFICATE-----
MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkExFTATBgNVBAgT
DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs
dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UE
AxMYVGhhd3RlIFByZW1pdW0gU2VydmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZl
ckB0aGF3dGUuY29tMB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYT
AlpBMRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsGA1UEChMU
VGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2
aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNlcnZlciBDQTEoMCYGCSqGSIb3DQEJARYZ
cHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2
aovXwlue2oFBYo847kkEVdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIh
Udib0GfQug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMRuHM/
qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAm
SCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUIhfzJATj/Tb7yFkJD57taRvvBxhEf
8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JMpAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7t
UCemDaYj+bvLpgcUQg==
-----END CERTIFICATE-----

Equifax Secure CA
=================
-----BEGIN CERTIFICATE-----
MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEQMA4GA1UE
ChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoT
B0VxdWlmYXgxLTArBgNVBAsTJEVxdWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPR
fM6fBeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+AcJkVV5MW
8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kCAwEAAaOCAQkwggEFMHAG
A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UE
CxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoG
A1UdEAQTMBGBDzIwMTgwODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvS
spXXR9gjIBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQFMAMB
Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAFjOKer89961
zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y7qj/WsjTVbJmcVfewCHrPSqnI0kB
BIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee95
70+sB3c4
-----END CERTIFICATE-----

Verisign Class 3 Public Primary Certification Authority
=======================================================
-----BEGIN CERTIFICATE-----
MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMx
FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVow
XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBAgUAA4GBALtMEivPLCYA
TxQT3ab7/AoRhIzzKBxnki98tsX63/Dolbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59Ah
WM1pF+NEHJwZRDmJXNycAA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2Omuf
Tqj/ZA1k
-----END CERTIFICATE-----

Verisign Class 3 Public Primary Certification Authority - G2
============================================================
-----BEGIN CERTIFICATE-----
MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT
MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT
MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO
FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71
lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB
MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT
1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD
Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9
-----END CERTIFICATE-----

GlobalSign Root CA
==================
-----BEGIN CERTIFICATE-----
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx
GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds
b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV
BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD
VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa
DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc
THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb
Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP
c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX
gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF
AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj
Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG
j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH
hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC
X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
-----END CERTIFICATE-----

GlobalSign Root CA - R2
=======================
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv
YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh
bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT
aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6
ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp
s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN
S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL
TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C
ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i
YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN
BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp
9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu
01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7
9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
-----END CERTIFICATE-----

ValiCert Class 1 VA
===================
-----BEGIN CERTIFICATE-----
MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIy
MjM0OFoXDTE5MDYyNTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEg
UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9YLqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIi
GQj4/xEjm84H9b9pGib+TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCm
DuJWBQ8YTfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0LBwG
lN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLWI8sogTLDAHkY7FkX
icnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPwnXS3qT6gpf+2SQMT2iLM7XGCK5nP
Orf1LXLI
-----END CERTIFICATE-----

ValiCert Class 2 VA
===================
-----BEGIN CERTIFICATE-----
MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw
MTk1NFoXDTE5MDYyNjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIg
UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDOOnHK5avIWZJV16vYdA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVC
CSRrCl6zfN1SLUzm1NZ9WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7Rf
ZHM047QSv4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9vUJSZ
SWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTuIYEZoDJJKPTEjlbV
UjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwCW/POuZ6lcg5Ktz885hZo+L7tdEy8
W9ViH0Pd
-----END CERTIFICATE-----

RSA Root Certificate 1
======================
-----BEGIN CERTIFICATE-----
MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw
MjIzM1oXDTE5MDYyNjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMg
UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDjmFGWHOjVsQaBalfDcnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td
3zZxFJmP3MKS8edgkpfs2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89H
BFx1cQqYJJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliEZwgs
3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJn0WuPIqpsHEzXcjF
V9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/APhmcGcwTTYJBtYze4D1gCCAPRX5r
on+jjBXu
-----END CERTIFICATE-----

Verisign Class 3 Public Primary Certification Authority - G3
============================================================
-----BEGIN CERTIFICATE-----
MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1
EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc
cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw
EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj
055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f
j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC
/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0
xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa
t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ==
-----END CERTIFICATE-----

Verisign Class 4 Public Primary Certification Authority - G3
============================================================
-----BEGIN CERTIFICATE-----
MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkg
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAK3LpRFpxlmr8Y+1GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaS
tBO3IFsJ+mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0GbdU6LM
8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLmNxdLMEYH5IBtptiW
Lugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XYufTsgsbSPZUd5cBPhMnZo0QoBmrX
Razwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
j/ola09b5KROJ1WrIhVZPMq1CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXtt
mhwwjIDLk5Mqg6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm
fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c2NU8Qh0XwRJd
RTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/bLvSHgCwIe34QWKCudiyxLtG
UPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg==
-----END CERTIFICATE-----

Entrust.net Secure Server CA
============================
-----BEGIN CERTIFICATE-----
MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMCVVMxFDASBgNV
BAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5uZXQvQ1BTIGluY29ycC4gYnkg
cmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRl
ZDE6MDgGA1UEAxMxRW50cnVzdC5uZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhv
cml0eTAeFw05OTA1MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIG
A1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBi
eSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1p
dGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQ
aO2f55M28Qpku0f1BBc/I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5
gXpa0zf3wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OCAdcw
ggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHboIHYpIHVMIHSMQsw
CQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5l
dC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF
bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENl
cnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu
dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0MFqBDzIwMTkw
NTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7UISX8+1i0Bow
HQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAaMAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EA
BAwwChsEVjQuMAMCBJAwDQYJKoZIhvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyN
Ewr75Ji174z4xRAN95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9
n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI=
-----END CERTIFICATE-----

Entrust.net Premium 2048 Secure Server CA
=========================================
-----BEGIN CERTIFICATE-----
MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChMLRW50cnVzdC5u
ZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBpbmNvcnAuIGJ5IHJlZi4gKGxp
bWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNV
BAMTKkVudHJ1c3QubmV0IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQx
NzUwNTFaFw0yOTA3MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3
d3d3LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTEl
MCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5u
ZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEArU1LqRKGsuqjIAcVFmQqK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOL
Gp18EzoOH1u3Hs/lJBQesYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSr
hRSGlVuXMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVTXTzW
nLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/HoZdenoVve8AjhUi
VBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH4QIDAQABo0IwQDAOBgNVHQ8BAf8E
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJ
KoZIhvcNAQEFBQADggEBADubj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPy
T/4xmf3IDExoU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf
zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5bu/8j72gZyxKT
J1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+bYQLCIt+jerXmCHG8+c8eS9e
nNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/ErfF6adulZkMV8gzURZVE=
-----END CERTIFICATE-----

Baltimore CyberTrust Root
=========================
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE
ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li
ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC
SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs
dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME
uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB
UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C
G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9
XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr
l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI
VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB
BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh
cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5
hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa
Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H
RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp
-----END CERTIFICATE-----

Equifax Secure Global eBusiness CA
==================================
-----BEGIN CERTIFICATE-----
MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
RXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBTZWN1cmUgR2xvYmFsIGVCdXNp
bmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIwMDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMx
HDAaBgNVBAoTE0VxdWlmYXggU2VjdXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEds
b2JhbCBlQnVzaW5lc3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRV
PEnCUdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc58O/gGzN
qfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/o5brhTMhHD4ePmBudpxn
hcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAHMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j
BBgwFoAUvqigdHJQa0S3ySPY+6j/s1draGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hs
MA0GCSqGSIb3DQEBBAUAA4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okEN
I7SS+RkAZ70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv8qIY
NMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV
-----END CERTIFICATE-----

Equifax Secure eBusiness CA 1
=============================
-----BEGIN CERTIFICATE-----
MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
RXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENB
LTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQwMDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UE
ChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNz
IENBLTEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ
1MRoRvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBuWqDZQu4a
IZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKwEnv+j6YDAgMBAAGjZjBk
MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEp4MlIR21kW
Nl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRKeDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQF
AAOBgQB1W6ibAxHm6VZMzfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5
lSE/9dR+WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN/Bf+
KpYrtWKmpj29f5JZzVoqgrI3eQ==
-----END CERTIFICATE-----

AddTrust Low-Value Services Root
================================
-----BEGIN CERTIFICATE-----
MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRU
cnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMwMTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQsw
CQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBO
ZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ulCDtbKRY6
54eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6ntGO0/7Gcrjyvd7ZWxbWr
oulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyldI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1
Zmne3yzxbrww2ywkEtvrNTVokMsAsJchPXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJui
GMx1I4S+6+JNM3GOGvDC+Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8w
HQYDVR0OBBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8EBTAD
AQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBlMQswCQYDVQQGEwJT
RTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEw
HwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxt
ZBsfzQ3duQH6lmM0MkhHma6X7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0Ph
iVYrqW9yTkkz43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY
eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJlpz/+0WatC7xr
mYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOAWiFeIc9TVPC6b4nbqKqVz4vj
ccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk=
-----END CERTIFICATE-----

AddTrust External Root
======================
-----BEGIN CERTIFICATE-----
MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD
VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw
NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU
cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg
Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821
+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw
Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo
aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy
2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7
7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P
BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL
VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk
VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB
IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl
j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5
6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355
e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u
G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ=
-----END CERTIFICATE-----

AddTrust Public Services Root
=============================
-----BEGIN CERTIFICATE-----
MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSAwHgYDVQQDExdBZGRU
cnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAxMDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJ
BgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5l
dHdvcmsxIDAeBgNVBAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV6tsfSlbu
nyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nXGCwwfQ56HmIexkvA/X1i
d9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnPdzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSG
Aa2Il+tmzV7R/9x98oTaunet3IAIx6eH1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAw
HM+A+WD+eeSI8t0A65RF62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0G
A1UdDgQWBBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDELMAkGA1UEBhMCU0Ux
FDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29yazEgMB4G
A1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4
JNojVhaTdt02KLmuG7jD8WS6IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL
+YPoRNWyQSW/iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao
GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh4SINhwBk/ox9
Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQmXiLsks3/QppEIW1cxeMiHV9H
EufOX1362KqxMy3ZdvJOOjMMK7MtkAY=
-----END CERTIFICATE-----

AddTrust Qualified Certificates Root
====================================
-----BEGIN CERTIFICATE-----
MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSMwIQYDVQQDExpBZGRU
cnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcx
CzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQ
IE5ldHdvcmsxIzAhBgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwqxBb/4Oxx
64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G87B4pfYOQnrjfxvM0PC3
KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i2O+tCBGaKZnhqkRFmhJePp1tUvznoD1o
L/BLcHwTOK28FSXx1s6rosAx1i+f4P8UWfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GR
wVY18BTcZTYJbqukB8c10cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HU
MIHRMB0GA1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/
BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6FrpGkwZzELMAkGA1UE
BhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29y
azEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlmaWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQAD
ggEBABmrder4i2VhlRO6aQTvhsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxG
GuoYQ992zPlmhpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X
dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3P6CxB9bpT9ze
RXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9YiQBCYz95OdBEsIJuQRno3eDB
iFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5noxqE=
-----END CERTIFICATE-----

Entrust Root Certification Authority
====================================
-----BEGIN CERTIFICATE-----
MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAUBgNV
BAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0Lm5ldC9DUFMgaXMgaW5jb3Jw
b3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMWKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsG
A1UEAxMkRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0
MloXDTI2MTEyNzIwNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMu
MTkwNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSByZWZlcmVu
Y2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNVBAMTJEVudHJ1c3QgUm9v
dCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ALaVtkNC+sZtKm9I35RMOVcF7sN5EUFoNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYsz
A9u3g3s+IIRe7bJWKKf44LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOww
Cj0Yzfv9KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGIrb68
j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi94DkZfs0Nw4pgHBN
rziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOBsDCBrTAOBgNVHQ8BAf8EBAMCAQYw
DwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAigA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1
MzQyWjAfBgNVHSMEGDAWgBRokORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DH
hmak8fdLQ/uEvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA
A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9tO1KzKtvn1ISM
Y/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6ZuaAGAT/3B+XxFNSRuzFVJ7yVTa
v52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTS
W3iDVuycNsMm4hH2Z0kdkquM++v/eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0
tHuu2guQOHXvgR1m0vdXcDazv/wor3ElhVsT/h5/WrQ8
-----END CERTIFICATE-----

RSA Security 2048 v3
====================
-----BEGIN CERTIFICATE-----
MIIDYTCCAkmgAwIBAgIQCgEBAQAAAnwAAAAKAAAAAjANBgkqhkiG9w0BAQUFADA6MRkwFwYDVQQK
ExBSU0EgU2VjdXJpdHkgSW5jMR0wGwYDVQQLExRSU0EgU2VjdXJpdHkgMjA0OCBWMzAeFw0wMTAy
MjIyMDM5MjNaFw0yNjAyMjIyMDM5MjNaMDoxGTAXBgNVBAoTEFJTQSBTZWN1cml0eSBJbmMxHTAb
BgNVBAsTFFJTQSBTZWN1cml0eSAyMDQ4IFYzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAt49VcdKA3XtpeafwGFAyPGJn9gqVB93mG/Oe2dJBVGutn3y+Gc37RqtBaB4Y6lXIL5F4iSj7
Jylg/9+PjDvJSZu1pJTOAeo+tWN7fyb9Gd3AIb2E0S1PRsNO3Ng3OTsor8udGuorryGlwSMiuLgb
WhOHV4PR8CDn6E8jQrAApX2J6elhc5SYcSa8LWrg903w8bYqODGBDSnhAMFRD0xS+ARaqn1y07iH
KrtjEAMqs6FPDVpeRrc9DvV07Jmf+T0kgYim3WBU6JU2PcYJk5qjEoAAVZkZR73QpXzDuvsf9/UP
+Ky5tfQ3mBMY3oVbtwyCO4dvlTlYMNpuAWgXIszACwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/
MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQHw1EwpKrpRa41JPr/JCwz0LGdjDAdBgNVHQ4E
FgQUB8NRMKSq6UWuNST6/yQsM9CxnYwwDQYJKoZIhvcNAQEFBQADggEBAF8+hnZuuDU8TjYcHnmY
v/3VEhF5Ug7uMYm83X/50cYVIeiKAVQNOvtUudZj1LGqlk2iQk3UUx+LEN5/Zb5gEydxiKRz44Rj
0aRV4VCT5hsOedBnvEbIvz8XDZXmxpBp3ue0L96VfdASPz0+f00/FGj1EVDVwfSQpQgdMWD/YIwj
VAqv/qFuxdF6Kmh4zx6CCiC0H63lhbJqaHVOrSU3lIW+vaHU6rcMSzyd6BIA8F+sDeGscGNz9395
nzIlQnQFgCi/vcEkllgVsRch6YlL2weIZ/QVrXA+L02FO8K32/6YaCOJ4XQP3vTFhGMpG8zLB8kA
pKnXwiJPZ9d37CAFYd4=
-----END CERTIFICATE-----

GeoTrust Global CA
==================
-----BEGIN CERTIFICATE-----
MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK
Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMDIwNTIxMDQw
MDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j
LjEbMBkGA1UEAxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjo
BbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDviS2Aelet
8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU1XupGc1V3sjs0l44U+Vc
T4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU
vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD
AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk
DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q
zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4
d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2
mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p
XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm
Mw==
-----END CERTIFICATE-----

GeoTrust Global CA 2
====================
-----BEGIN CERTIFICATE-----
MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
R2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwHhcNMDQwMzA0MDUw
MDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j
LjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQDvPE1APRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/
NTL8Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hLTytCOb1k
LUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL5mkWRxHCJ1kDs6ZgwiFA
Vvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7S4wMcoKK+xfNAGw6EzywhIdLFnopsk/b
HdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQF
MAMBAf8wHQYDVR0OBBYEFHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNH
K266ZUapEBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6tdEPx7
srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv/NgdRN3ggX+d6Yvh
ZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywNA0ZF66D0f0hExghAzN4bcLUprbqL
OzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkC
x1YAzUm5s2x7UwQa4qjJqhIFI8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqF
H4z1Ir+rzoPz4iIprn2DQKi6bA==
-----END CERTIFICATE-----

GeoTrust Universal CA
=====================
-----BEGIN CERTIFICATE-----
MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1
MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu
Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP
ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t
JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjOgNB0e
RXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFhF7em6fgemdtzbvQKoiFs
7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2vc7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d
8Lsrlh/eezJS/R27tQahsiFepdaVaH/wmZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7V
qnJNk22CDtucvc+081xdVHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3Cga
Rr0BHdCXteGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZf9hB
Z3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfReBi9Fi1jUIxaS5BZu
KGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+nhutxx9z3SxPGWX9f5NAEC7S8O08
ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0
XG0D08DYj3rWMB8GA1UdIwQYMBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIB
hjANBgkqhkiG9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc
aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fXIwjhmF7DWgh2
qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzynANXH/KttgCJwpQzgXQQpAvvL
oJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0zuzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsK
xr2EoyNB3tZ3b4XUhRxQ4K5RirqNPnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxF
KyDuSN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2
DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK
xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU
p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI
P/rmMuGNG2+k5o7Y+SlIis5z/iw=
-----END CERTIFICATE-----

GeoTrust Universal CA 2
=======================
-----BEGIN CERTIFICATE-----
MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0
MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg
SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA
A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0
DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17
j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q
JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a
QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2
WP0+GfPtDCapkzj4T8FdIgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP
20gaXT73y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRthAAn
ZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgocQIgfksILAAX/8sgC
SqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4Lt1ZrtmhN79UNdxzMk+MBB4zsslG
8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2
+/CfXGJx7Tz0RzgQKzAfBgNVHSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8E
BAMCAYYwDQYJKoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z
dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQL1EuxBRa3ugZ
4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgrFg5fNuH8KrUwJM/gYwx7WBr+
mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSoag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpq
A1Ihn0CoZ1Dy81of398j9tx4TuaYT1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpg
Y+RdM4kX2TGq2tbzGDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiP
pm8m1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJVOCiNUW7d
FGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH6aLcr34YEoP9VhdBLtUp
gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm
X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS
-----END CERTIFICATE-----

America Online Root Certification Authority 1
=============================================
-----BEGIN CERTIFICATE-----
MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp
Y2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkG
A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg
T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lkhsmj76CG
v2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym1BW32J/X3HGrfpq/m44z
DyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsWOqMFf6Dch9Wc/HKpoH145LcxVR5lu9Rh
sCFg7RAycsWSJR74kEoYeEfffjA3PlAb2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP
8c9GsEsPPt2IYriMqQkoO3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0T
AQH/BAUwAwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAUAK3Z
o/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IBAQB8itEf
GDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkFZu90821fnZmv9ov761KyBZiibyrF
VL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAbLjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft
3OJvx8Fi8eNy1gTIdGcL+oiroQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43g
Kd8hdIaC2y+CMMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds
sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7
-----END CERTIFICATE-----

America Online Root Certification Authority 2
=============================================
-----BEGIN CERTIFICATE-----
MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp
Y2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkG
A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg
T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQAD
ggIPADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC206B89en
fHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFciKtZHgVdEglZTvYYUAQv8
f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2JxhP7JsowtS013wMPgwr38oE18aO6lhO
qKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JN
RvCAOVIyD+OEsnpD8l7eXz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0
gBe4lL8BPeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67Xnfn
6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEqZ8A9W6Wa6897Gqid
FEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZo2C7HK2JNDJiuEMhBnIMoVxtRsX6
Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3+L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnj
B453cMor9H124HhnAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3Op
aaEg5+31IqEjFNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE
AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmnxPBUlgtk87FY
T15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2LHo1YGwRgJfMqZJS5ivmae2p
+DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzcccobGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXg
JXUjhx5c3LqdsKyzadsXg8n33gy8CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//Zoy
zH1kUQ7rVyZ2OuMeIjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgO
ZtMADjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2FAjgQ5ANh
1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUXOm/9riW99XJZZLF0Kjhf
GEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPbAZO1XB4Y3WRayhgoPmMEEf0cjQAPuDff
Z4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQlZvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuP
cX/9XhmgD0uRuMRUvAawRY8mkaKO/qk=
-----END CERTIFICATE-----

Visa eCommerce Root
===================
-----BEGIN CERTIFICATE-----
MIIDojCCAoqgAwIBAgIQE4Y1TR0/BvLB+WUF1ZAcYjANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQG
EwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2Ug
QXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNvbW1lcmNlIFJvb3QwHhcNMDIwNjI2MDIxODM2
WhcNMjIwNjI0MDAxNjEyWjBrMQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMm
VmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNv
bW1lcmNlIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvV95WHm6h2mCxlCfL
F9sHP4CFT8icttD0b0/Pmdjh28JIXDqsOTPHH2qLJj0rNfVIsZHBAk4ElpF7sDPwsRROEW+1QK8b
RaVK7362rPKgH1g/EkZgPI2h4H3PVz4zHvtH8aoVlwdVZqW1LS7YgFmypw23RuwhY/81q6UCzyr0
TP579ZRdhE2o8mCP2w4lPJ9zcc+U30rq299yOIzzlr3xF7zSujtFWsan9sYXiwGd/BmoKoMWuDpI
/k4+oKsGGelT84ATB+0tvz8KPFUgOSwsAGl0lUq8ILKpeeUYiZGo3BxN77t+Nwtd/jmliFKMAGzs
GHxBvfaLdXe6YJ2E5/4tAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEG
MB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUFAAOCAQEAX/FBfXxc
CLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcRzCSs00Rsca4BIGsDoo8Ytyk6feUW
YFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pz
zkWKsKZJ/0x9nXGIxHYdkFsd7v3M9+79YKWxehZx0RbQfBI8bGmX265fOZpwLwU8GUYEmSA20GBu
YQa7FkKMcPcw++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt
398znM/jra6O1I7mT1GvFpLgXPYHDw==
-----END CERTIFICATE-----

Certum Root CA
==============
-----BEGIN CERTIFICATE-----
MIIDDDCCAfSgAwIBAgIDAQAgMA0GCSqGSIb3DQEBBQUAMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQK
ExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBDQTAeFw0wMjA2MTExMDQ2Mzla
Fw0yNzA2MTExMDQ2MzlaMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8u
by4xEjAQBgNVBAMTCUNlcnR1bSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM6x
wS7TT3zNJc4YPk/EjG+AanPIW1H4m9LcuwBcsaD8dQPugfCI7iNS6eYVM42sLQnFdvkrOYCJ5JdL
kKWoePhzQ3ukYbDYWMzhbGZ+nPMJXlVjhNWo7/OxLjBos8Q82KxujZlakE403Daaj4GIULdtlkIJ
89eVgw1BS7Bqa/j8D35in2fE7SZfECYPCE/wpFcozo+47UX2bu4lXapuOb7kky/ZR6By6/qmW6/K
Uz/iDsaWVhFu9+lmqSbYf5VT7QqFiLpPKaVCjF62/IUgAKpoC6EahQGcxEZjgoi2IrHu/qpGWX7P
NSzVttpd90gzFFS269lvzs2I1qsb2pY7HVkCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkq
hkiG9w0BAQUFAAOCAQEAuI3O7+cUus/usESSbLQ5PqKEbq24IXfS1HeCh+YgQYHu4vgRt2PRFze+
GXYkHAQaTOs9qmdvLdTN/mUxcMUbpgIKumB7bVjCmkn+YzILa+M6wKyrO7Do0wlRjBCDxjTgxSvg
GrZgFCdsMneMvLJymM/NzD+5yCRCFNZX/OYmQ6kd5YCQzgNUKD73P9P4Te1qCjqTE5s7FCMTY5w/
0YcneeVMUeMBrYVdGjux1XMQpNPyvG5k9VpWkKjHDkx0Dy5xO/fIR/RpbxXyEV6DHpx8Uq79AtoS
qFlnGNu8cN2bsWntgM6JQEhqDjXKKWYVIZQs6GAqm4VKQPNriiTsBhYscw==
-----END CERTIFICATE-----

Comodo AAA Services root
========================
-----BEGIN CERTIFICATE-----
MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw
MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl
c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV
BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG
C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs
i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW
Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH
Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK
Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wewYDVR0f
BHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20vQUFBQ2VydGlmaWNhdGVTZXJ2aWNl
cy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29tb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2Vz
LmNybDANBgkqhkiG9w0BAQUFAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm
7l3sAg9g1o1QGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz
Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2G9w84FoVxp7Z
8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsil2D4kF501KKaU73yqWjgom7C
12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==
-----END CERTIFICATE-----

Comodo Secure Services root
===========================
-----BEGIN CERTIFICATE-----
MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
TGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAw
MDAwMFoXDTI4MTIzMTIzNTk1OVowfjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFu
Y2hlc3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAi
BgNVBAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPMcm3ye5drswfxdySRXyWP
9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3SHpR7LZQdqnXXs5jLrLxkU0C8j6ysNstc
rbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rC
oznl2yY4rYsK7hljxxwk3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3V
p6ea5EQz6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNVHQ4E
FgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w
gYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL1NlY3VyZUNlcnRpZmlj
YXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRwOi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlm
aWNhdGVTZXJ2aWNlcy5jcmwwDQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm
4J4oqF7Tt/Q05qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj
Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtIgKvcnDe4IRRL
DXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJaD61JlfutuC23bkpgHl9j6Pw
pCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDlizeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1H
RR3B7Hzs/Sk=
-----END CERTIFICATE-----

Comodo Trusted Services root
============================
-----BEGIN CERTIFICATE-----
MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
TGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEw
MDAwMDBaFw0yODEyMzEyMzU5NTlaMH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1h
bmNoZXN0ZXIxEDAOBgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUw
IwYDVQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWWfnJSoBVC21ndZHoa0Lh7
3TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMtTGo87IvDktJTdyR0nAducPy9C1t2ul/y
/9c3S0pgePfw+spwtOpZqqPOSC+pw7ILfhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6
juljatEPmsbS9Is6FARW1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsS
ivnkBbA7kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0GA1Ud
DgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21vZG9jYS5jb20vVHJ1c3RlZENlcnRp
ZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRodHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENl
cnRpZmljYXRlU2VydmljZXMuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8Ntw
uleGFTQQuS9/HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32
pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxISjBc/lDb+XbDA
BHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+xqFx7D+gIIxmOom0jtTYsU0l
R+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/AtyjcndBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O
9y5Xt5hwXsjEeLBi
-----END CERTIFICATE-----

QuoVadis Root CA
================
-----BEGIN CERTIFICATE-----
MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJCTTEZMBcGA1UE
ChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0
eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAz
MTkxODMzMzNaFw0yMTAzMTcxODMzMzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRp
cyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQD
EyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Ypli4kVEAkOPcahdxYTMuk
J0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2DrOpm2RgbaIr1VxqYuvXtdj182d6UajtL
F8HVj71lODqV0D1VNk7feVcxKh7YWWVJWCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeL
YzcS19Dsw3sgQUSj7cugF+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWen
AScOospUxbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCCAk4w
PQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVvdmFkaXNvZmZzaG9y
ZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREwggENMIIBCQYJKwYBBAG+WAABMIH7
MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNlIG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmlj
YXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJs
ZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh
Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYIKwYBBQUHAgEW
Fmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3TKbkGGew5Oanwl4Rqy+/fMIGu
BgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rqy+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkw
FwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6
tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo
fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul
LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x
gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi
5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi
5nrQNiOKSnQ2+Q==
-----END CERTIFICATE-----

QuoVadis Root CA 2
==================
-----BEGIN CERTIFICATE-----
MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT
EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx
ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC
DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6
XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk
lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB
lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8un+XJiM9XOva7R+zdRcAitMOeGy
lZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt
66/3FsvbzSUr5R/7mp/iUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1Jdxn
wQ5hYIizPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og/zOh
D7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UHoycR7hYQe7xFSkyy
BNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuIyV77zGHcizN300QyNQliBJIWENie
J0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1Ud
DgQWBBQahGK8SEwzJQTU7tD2A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGU
a6FJpEcwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT
ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2fBluornFdLwUv
Z+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzng/iN/Ae42l9NLmeyhP3ZRPx3
UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2BlfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodm
VjB3pjd4M1IQWK4/YY7yarHvGH5KWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK
+JDSV6IZUaUtl0HaB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrW
IozchLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPRTUIZ3Ph1
WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X
f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II
4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8
VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u
-----END CERTIFICATE-----

QuoVadis Root CA 3
==================
-----BEGIN CERTIFICATE-----
MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT
EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx
OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC
DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg
DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij
KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K
DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv
BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp
p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8
nT8KKdjcT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDtWAEX
MJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZc6tsgLjoC2SToJyM
Gf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A4iLItLRkT9a6fUg+qGkM17uGcclz
uD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYDVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHT
BgkrBgEEAb5YAAMwgcUwgZMGCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmlj
YXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0
aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVudC4wLQYIKwYB
BQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2NwczALBgNVHQ8EBAMCAQYwHQYD
VR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4GA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4
ywLQoUmkRzBFMQswCQYDVQQGEwJCTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UE
AxMSUXVvVmFkaXMgUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZV
qyM07ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSemd1o417+s
hvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd+LJ2w/w4E6oM3kJpK27z
POuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2
Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp
8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC
bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu
g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p
vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr
qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto=
-----END CERTIFICATE-----

Security Communication Root CA
==============================
-----BEGIN CERTIFICATE-----
MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP
U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw
HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP
U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw
8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM
DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX
5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd
DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2
JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw
DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g
0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a
mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ
s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ
6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi
FL39vmwLAw==
-----END CERTIFICATE-----

Sonera Class 2 Root CA
======================
-----BEGIN CERTIFICATE-----
MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG
U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw
NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh
IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3
/Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT
dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG
f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P
tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH
nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT
XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt
0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI
cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph
Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx
EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH
llpwrN9M
-----END CERTIFICATE-----

Staat der Nederlanden Root CA
=============================
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgIEAJiWijANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJOTDEeMBwGA1UE
ChMVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSYwJAYDVQQDEx1TdGFhdCBkZXIgTmVkZXJsYW5kZW4g
Um9vdCBDQTAeFw0wMjEyMTcwOTIzNDlaFw0xNTEyMTYwOTE1MzhaMFUxCzAJBgNVBAYTAk5MMR4w
HAYDVQQKExVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xJjAkBgNVBAMTHVN0YWF0IGRlciBOZWRlcmxh
bmRlbiBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmNK1URF6gaYUmHFt
vsznExvWJw56s2oYHLZhWtVhCb/ekBPHZ+7d89rFDBKeNVU+LCeIQGv33N0iYfXCxw719tV2U02P
jLwYdjeFnejKScfST5gTCaI+Ioicf9byEGW07l8Y1Rfj+MX94p2i71MOhXeiD+EwR+4A5zN9RGca
C1Hoi6CeUJhoNFIfLm0B8mBF8jHrqTFoKbt6QZ7GGX+UtFE5A3+y3qcym7RHjm+0Sq7lr7HcsBth
vJly3uSJt3omXdozSVtSnA71iq3DuD3oBmrC1SoLbHuEvVYFy4ZlkuxEK7COudxwC0barbxjiDn6
22r+I/q85Ej0ZytqERAhSQIDAQABo4GRMIGOMAwGA1UdEwQFMAMBAf8wTwYDVR0gBEgwRjBEBgRV
HSAAMDwwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cucGtpb3ZlcmhlaWQubmwvcG9saWNpZXMvcm9v
dC1wb2xpY3kwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSofeu8Y6R0E3QA7Jbg0zTBLL9s+DAN
BgkqhkiG9w0BAQUFAAOCAQEABYSHVXQ2YcG70dTGFagTtJ+k/rvuFbQvBgwp8qiSpGEN/KtcCFtR
EytNwiphyPgJWPwtArI5fZlmgb9uXJVFIGzmeafR2Bwp/MIgJ1HI8XxdNGdphREwxgDS1/PTfLbw
MVcoEoJz6TMvplW0C5GUR5z6u3pCMuiufi3IvKwUv9kP2Vv8wfl6leF9fpb8cbDCTMjfRTTJzg3y
nGQI0DvDKcWy7ZAEwbEpkcUwb8GpcjPM/l0WFywRaed+/sWDCN+83CI6LiBpIzlWYGeQiy52OfsR
iJf2fL1LuCAWZwWN4jvBcj+UlTfHXbme2JOhF4//DGYVwSR8MnwDHTuhWEUykw==
-----END CERTIFICATE-----

TDC Internet Root CA
====================
-----BEGIN CERTIFICATE-----
MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJESzEVMBMGA1UE
ChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTAeFw0wMTA0MDUx
NjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNVBAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJu
ZXQxHTAbBgNVBAsTFFREQyBJbnRlcm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAxLhAvJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20j
xsNuZp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a0vnRrEvL
znWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc14izbSysseLlJ28TQx5yc
5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGNeGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6
otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcDR0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZI
AYb4QgEBBAQDAgAHMGUGA1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMM
VERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxMEQ1JM
MTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3WjALBgNVHQ8EBAMC
AQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAwHQYDVR0OBBYEFGxkAcf9hW2syNqe
UAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJKoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0G
CSqGSIb3DQEBBQUAA4IBAQBOQ8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540m
gwV5dOy0uaOXwTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+
2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm899qNLPg7kbWzb
O0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0jUNAE4z9mQNUecYu6oah9jrU
Cbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38aQNiuJkFBT1reBK9sG9l
-----END CERTIFICATE-----

UTN DATACorp SGC Root CA
========================
-----BEGIN CERTIFICATE-----
MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UE
BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl
IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZ
BgNVBAMTElVUTiAtIERBVEFDb3JwIFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBa
MIGTMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4w
HAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cudXNlcnRy
dXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ys
raP6LnD43m77VkIVni5c7yPeIbkFdicZD0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlo
wHDyUwDAXlCCpVZvNvlK4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA
9P4yPykqlXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulWbfXv
33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQABo4GrMIGoMAsGA1Ud
DwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRTMtGzz3/64PGgXYVOktKeRR20TzA9
BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dD
LmNybDAqBgNVHSUEIzAhBggrBgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3
DQEBBQUAA4IBAQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft
Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyjj98C5OBxOvG0
I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVHKWss5nbZqSl9Mt3JNjy9rjXx
EZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwP
DPafepE39peC4N1xaf92P2BNPM/3mfnGV/TJVTl4uix5yaaIK/QI
-----END CERTIFICATE-----

UTN USERFirst Hardware Root CA
==============================
-----BEGIN CERTIFICATE-----
MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UE
BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl
IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAd
BgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgx
OTIyWjCBlzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0
eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVz
ZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlI
wrthdBKWHTxqctU8EGc6Oe0rE81m65UJM6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFd
tqdt++BxF2uiiPsA3/4aMXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8
i4fDidNdoI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqIDsjf
Pe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9KsyoUhbAgMBAAGjgbkw
gbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFKFyXyYbKJhDlV0HN9WF
lp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNF
UkZpcnN0LUhhcmR3YXJlLmNybDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUF
BwMGBggrBgEFBQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM
//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28GpgoiskliCE7/yMgUsogW
XecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gECJChicsZUN/KHAG8HQQZexB2
lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kn
iCrVWFCVH/A7HFe7fRQ5YiuayZSSKqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67
nfhmqA==
-----END CERTIFICATE-----

Camerfirma Chambers of Commerce Root
====================================
-----BEGIN CERTIFICATE-----
MIIEvTCCA6WgAwIBAgIBADANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe
QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i
ZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdDAeFw0wMzA5MzAx
NjEzNDNaFw0zNzA5MzAxNjEzNDRaMH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZp
cm1hIFNBIENJRiBBODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3Jn
MSIwIAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290MIIBIDANBgkqhkiG9w0BAQEFAAOC
AQ0AMIIBCAKCAQEAtzZV5aVdGDDg2olUkfzIx1L4L1DZ77F1c2VHfRtbunXF/KGIJPov7coISjlU
xFF6tdpg6jg8gbLL8bvZkSM/SAFwdakFKq0fcfPJVD0dBmpAPrMMhe5cG3nCYsS4No41XQEMIwRH
NaqbYE6gZj3LJgqcQKH0XZi/caulAGgq7YN6D6IUtdQis4CwPAxaUWktWBiP7Zme8a7ileb2R6jW
DA+wWFjbw2Y3npuRVDM30pQcakjJyfKl2qUMI/cjDpwyVV5xnIQFUZot/eZOKjRa3spAN2cMVCFV
d9oKDMyXroDclDZK9D7ONhMeU+SsTjoF7Nuucpw4i9A5O4kKPnf+dQIBA6OCAUQwggFAMBIGA1Ud
EwEB/wQIMAYBAf8CAQwwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL2NybC5jaGFtYmVyc2lnbi5v
cmcvY2hhbWJlcnNyb290LmNybDAdBgNVHQ4EFgQU45T1sU3p26EpW1eLTXYGduHRooowDgYDVR0P
AQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzAnBgNVHREEIDAegRxjaGFtYmVyc3Jvb3RAY2hh
bWJlcnNpZ24ub3JnMCcGA1UdEgQgMB6BHGNoYW1iZXJzcm9vdEBjaGFtYmVyc2lnbi5vcmcwWAYD
VR0gBFEwTzBNBgsrBgEEAYGHLgoDATA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY3BzLmNoYW1iZXJz
aWduLm9yZy9jcHMvY2hhbWJlcnNyb290Lmh0bWwwDQYJKoZIhvcNAQEFBQADggEBAAxBl8IahsAi
fJ/7kPMa0QOx7xP5IV8EnNrJpY0nbJaHkb5BkAFyk+cefV/2icZdp0AJPaxJRUXcLo0waLIJuvvD
L8y6C98/d3tGfToSJI6WjzwFCm/SlCgdbQzALogi1djPHRPH8EjX1wWnz8dHnjs8NMiAT9QUu/wN
UPf6s+xCX6ndbcj0dc97wXImsQEcXCz9ek60AcUFV7nnPKoF2YjpB0ZBzu9Bga5Y34OirsrXdx/n
ADydb47kMgkdTXg0eDQ8lJsm7U9xxhl6vSAiSFr+S30Dt+dYvsYyTnQeaN2oaFuzPu5ifdmA6Ap1
erfutGWaIZDgqtCYvDi1czyL+Nw=
-----END CERTIFICATE-----

Camerfirma Global Chambersign Root
==================================
-----BEGIN CERTIFICATE-----
MIIExTCCA62gAwIBAgIBADANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe
QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i
ZXJzaWduLm9yZzEgMB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwHhcNMDMwOTMwMTYx
NDE4WhcNMzcwOTMwMTYxNDE4WjB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJt
YSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEg
MB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwggEgMA0GCSqGSIb3DQEBAQUAA4IBDQAw
ggEIAoIBAQCicKLQn0KuWxfH2H3PFIP8T8mhtxOviteePgQKkotgVvq0Mi+ITaFgCPS3CU6gSS9J
1tPfnZdan5QEcOw/Wdm3zGaLmFIoCQLfxS+EjXqXd7/sQJ0lcqu1PzKY+7e3/HKE5TWH+VX6ox8O
by4o3Wmg2UIQxvi1RMLQQ3/bvOSiPGpVeAp3qdjqGTK3L/5cPxvusZjsyq16aUXjlg9V9ubtdepl
6DJWk0aJqCWKZQbua795B9Dxt6/tLE2Su8CoX6dnfQTyFQhwrJLWfQTSM/tMtgsL+xrJxI0DqX5c
8lCrEqWhz0hQpe/SyBoT+rB/sYIcd2oPX9wLlY/vQ37mRQklAgEDo4IBUDCCAUwwEgYDVR0TAQH/
BAgwBgEB/wIBDDA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLmNoYW1iZXJzaWduLm9yZy9j
aGFtYmVyc2lnbnJvb3QuY3JsMB0GA1UdDgQWBBRDnDafsJ4wTcbOX60Qq+UDpfqpFDAOBgNVHQ8B
Af8EBAMCAQYwEQYJYIZIAYb4QgEBBAQDAgAHMCoGA1UdEQQjMCGBH2NoYW1iZXJzaWducm9vdEBj
aGFtYmVyc2lnbi5vcmcwKgYDVR0SBCMwIYEfY2hhbWJlcnNpZ25yb290QGNoYW1iZXJzaWduLm9y
ZzBbBgNVHSAEVDBSMFAGCysGAQQBgYcuCgEBMEEwPwYIKwYBBQUHAgEWM2h0dHA6Ly9jcHMuY2hh
bWJlcnNpZ24ub3JnL2Nwcy9jaGFtYmVyc2lnbnJvb3QuaHRtbDANBgkqhkiG9w0BAQUFAAOCAQEA
PDtwkfkEVCeR4e3t/mh/YV3lQWVPMvEYBZRqHN4fcNs+ezICNLUMbKGKfKX0j//U2K0X1S0E0T9Y
gOKBWYi+wONGkyT+kL0mojAt6JcmVzWJdJYY9hXiryQZVgICsroPFOrGimbBhkVVi76SvpykBMdJ
PJ7oKXqJ1/6v/2j1pReQvayZzKWGVwlnRtvWFsJG8eSpUPWP0ZIV018+xgBJOm5YstHRJw0lyDL4
IBHNfTIzSJRUTN3cecQwn+uOuFW114hcxWokPbLTBQNRxgfvzBRydD1ucs4YKIxKoHflCStFREes
t2d/AYoFWpO+ocH/+OcOZ6RHSXZddZAa9SaP8A==
-----END CERTIFICATE-----

NetLock Notary (Class A) Root
=============================
-----BEGIN CERTIFICATE-----
MIIGfTCCBWWgAwIBAgICAQMwDQYJKoZIhvcNAQEEBQAwga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQI
EwdIdW5nYXJ5MREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6
dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9j
ayBLb3pqZWd5em9pIChDbGFzcyBBKSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNDIzMTQ0N1oX
DTE5MDIxOTIzMTQ0N1owga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQIEwdIdW5nYXJ5MREwDwYDVQQH
EwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9uc2FnaSBLZnQuMRowGAYD
VQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9jayBLb3pqZWd5em9pIChDbGFz
cyBBKSBUYW51c2l0dmFueWtpYWRvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvHSM
D7tM9DceqQWC2ObhbHDqeLVu0ThEDaiDzl3S1tWBxdRL51uUcCbbO51qTGL3cfNk1mE7PetzozfZ
z+qMkjvN9wfcZnSX9EUi3fRc4L9t875lM+QVOr/bmJBVOMTtplVjC7B4BPTjbsE/jvxReB+SnoPC
/tmwqcm8WgD/qaiYdPv2LD4VOQ22BFWoDpggQrOxJa1+mm9dU7GrDPzr4PN6s6iz/0b2Y6LYOph7
tqyF/7AlT3Rj5xMHpQqPBffAZG9+pyeAlt7ULoZgx2srXnN7F+eRP2QM2EsiNCubMvJIH5+hCoR6
4sKtlz2O1cH5VqNQ6ca0+pii7pXmKgOM3wIDAQABo4ICnzCCApswDgYDVR0PAQH/BAQDAgAGMBIG
A1UdEwEB/wQIMAYBAf8CAQQwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaC
Ak1GSUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pv
bGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQu
IEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2Vn
LWJpenRvc2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0
ZXRlbGUgYXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFz
IGxlaXJhc2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBh
IGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVu
b3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBh
bmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sg
Q1BTIGF2YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFp
bCBhdCBjcHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4IBAQBIJEb3ulZv+sgoA0BO5TE5
ayZrU3/b39/zcT0mwBQOxmd7I6gMc90Bu8bKbjc5VdXHjFYgDigKDtIqpLBJUsY4B/6+CgmM0ZjP
ytoUMaFP0jn8DxEsQ8Pdq5PHVT5HfBgaANzze9jyf1JsIPQLX2lS9O74silg6+NJMSEN1rUQQeJB
CWziGppWS3cC9qCbmieH6FUpccKQn0V4GuEVZD3QDtigdp+uxdAu6tYPVuxkf1qbFFgBJ34TUMdr
KuZoPL9coAob4Q566eKAw+np9v1sEZ7Q5SgnK1QyQhSCdeZK8CtmdWOMovsEPoMOmzbwGOQmIMOM
8CgHrTwXZoi1/baI
-----END CERTIFICATE-----

NetLock Business (Class B) Root
===============================
-----BEGIN CERTIFICATE-----
MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUxETAPBgNVBAcT
CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV
BAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQDEylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikg
VGFudXNpdHZhbnlraWFkbzAeFw05OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYD
VQQGEwJIVTERMA8GA1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRv
bnNhZ2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5ldExvY2sg
VXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
iQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xKgZjupNTKihe5In+DCnVMm8Bp2GQ5o+2S
o/1bXHQawEfKOml2mrriRBf8TKPV/riXiK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr
1nGTLbO/CVRY7QbrqHvcQ7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNV
HQ8BAf8EBAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1GSUdZ
RUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pvbGdhbHRh
dGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQuIEEgaGl0
ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRv
c2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUg
YXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh
c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBhIGh0dHBz
Oi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVub3J6ZXNA
bmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhl
IHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2
YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBj
cHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06sPgzTEdM
43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXan3BukxowOR0w2y7jfLKR
stE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKSNitjrFgBazMpUIaD8QFI
-----END CERTIFICATE-----

NetLock Express (Class C) Root
==============================
-----BEGIN CERTIFICATE-----
MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUxETAPBgNVBAcT
CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV
BAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQDEytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBD
KSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJ
BgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6
dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMrTmV0TG9j
ayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzANBgkqhkiG9w0BAQEFAAOB
jQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNAOoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3Z
W3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63
euyucYT2BDMIJTLrdKwWRMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQw
DgYDVR0PAQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEWggJN
RklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0YWxhbm9zIFN6b2xn
YWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFzb2sgYWxhcGphbiBrZXN6dWx0LiBB
IGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBOZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1i
aXp0b3NpdGFzYSB2ZWRpLiBBIGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0
ZWxlIGF6IGVsb2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs
ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25sYXBqYW4gYSBo
dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kga2VyaGV0byBheiBlbGxlbm9y
emVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4gSU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5k
IHRoZSB1c2Ugb2YgdGhpcyBjZXJ0aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQ
UyBhdmFpbGFibGUgYXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwg
YXQgY3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmYta3UzbM2
xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2gpO0u9f38vf5NNwgMvOOW
gyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4Fp1hBWeAyNDYpQcCNJgEjTME1A==
-----END CERTIFICATE-----

XRamp Global CA Root
====================
-----BEGIN CERTIFICATE-----
MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE
BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj
dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB
dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx
HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkg
U2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
dHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS638eMpSe2OAtp87ZOqCwu
IR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCPKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMx
foArtYzAQDsRhtDLooY2YKTVMIJt2W7QDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FE
zG+gSqmUsE3a56k0enI4qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqs
AxcZZPRaJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNViPvry
xS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud
EwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASsjVy16bYbMDYGA1UdHwQvMC0wK6Ap
oCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMC
AQEwDQYJKoZIhvcNAQEFBQADggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc
/Kh4ZzXxHfARvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt
qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLaIR9NmXmd4c8n
nxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSyi6mx5O+aGtA9aZnuqCij4Tyz
8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQO+7ETPTsJ3xCwnR8gooJybQDJbw=
-----END CERTIFICATE-----

Go Daddy Class 2 CA
===================
-----BEGIN CERTIFICATE-----
MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY
VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp
ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG
A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g
RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD
ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv
2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32
qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j
YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY
vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O
BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o
atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu
MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG
A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim
PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt
I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ
HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI
Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b
vZ8=
-----END CERTIFICATE-----

Starfield Class 2 CA
====================
-----BEGIN CERTIFICATE-----
MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc
U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo
MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG
A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG
SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY
bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ
JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm
epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN
F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF
MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f
hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo
bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g
QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs
afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM
PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl
xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD
KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3
QBFGmh95DmK/D5fs4C8fF5Q=
-----END CERTIFICATE-----

StartCom Certification Authority
================================
-----BEGIN CERTIFICATE-----
MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN
U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu
ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0
NjM2WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk
LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg
U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y
o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/
Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d
eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt
2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z
6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ
osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/
untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc
UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT
37uMdBNSSwIDAQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE
FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9jZXJ0LnN0YXJ0
Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0Y29tLm9yZy9zZnNj
YS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFMBgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUH
AgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRw
Oi8vY2VydC5zdGFydGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYg
U3RhcnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlhYmlsaXR5
LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2YgdGhlIFN0YXJ0Q29tIENl
cnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFpbGFibGUgYXQgaHR0cDovL2NlcnQuc3Rh
cnRjb20ub3JnL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilT
dGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOC
AgEAFmyZ9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8jhvh
3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUWFjgKXlf2Ysd6AgXm
vB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJzewT4F+irsfMuXGRuczE6Eri8sxHk
fY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3
fsNrarnDy0RLrHiQi+fHLB5LEUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZ
EoalHmdkrQYuL6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq
yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuCO3NJo2pXh5Tl
1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6Vum0ABj6y6koQOdjQK/W/7HW/
lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkyShNOsF/5oirpt9P/FlUQqmMGqz9IgcgA38coro
g14=
-----END CERTIFICATE-----

Taiwan GRCA
===========
-----BEGIN CERTIFICATE-----
MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG
EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X
DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv
dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD
ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qN
w8XRIePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1qgQdW8or5
BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKyyhwOeYHWtXBiCAEuTk8O
1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAtsF/tnyMKtsc2AtJfcdgEWFelq16TheEfO
htX7MfP6Mb40qij7cEwdScevLJ1tZqa2jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wov
J5pGfaENda1UhhXcSTvxls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7
Q3hub/FCVGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHKYS1t
B6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoHEgKXTiCQ8P8NHuJB
O9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThNXo+EHWbNxWCWtFJaBYmOlXqYwZE8
lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1UdDgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNV
HRMEBTADAQH/MDkGBGcqBwAEMTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg2
09yewDL7MTqKUWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ
TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyfqzvS/3WXy6Tj
Zwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaKZEk9GhiHkASfQlK3T8v+R0F2
Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFEJPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlU
D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz
DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk
Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk
7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ
CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy
+fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS
-----END CERTIFICATE-----

Swisscom Root CA 1
==================
-----BEGIN CERTIFICATE-----
MIIF2TCCA8GgAwIBAgIQXAuFXAvnWUHfV8w/f52oNjANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQG
EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy
dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMTAeFw0wNTA4MTgxMjA2MjBaFw0yNTA4
MTgyMjA2MjBaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln
aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAxMIIC
IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0LmwqAzZuz8h+BvVM5OAFmUgdbI9m2BtRsiM
MW8Xw/qabFbtPMWRV8PNq5ZJkCoZSx6jbVfd8StiKHVFXqrWW/oLJdihFvkcxC7mlSpnzNApbjyF
NDhhSbEAn9Y6cV9Nbc5fuankiX9qUvrKm/LcqfmdmUc/TilftKaNXXsLmREDA/7n29uj/x2lzZAe
AR81sH8A25Bvxn570e56eqeqDFdvpG3FEzuwpdntMhy0XmeLVNxzh+XTF3xmUHJd1BpYwdnP2IkC
b6dJtDZd0KTeByy2dbcokdaXvij1mB7qWybJvbCXc9qukSbraMH5ORXWZ0sKbU/Lz7DkQnGMU3nn
7uHbHaBuHYwadzVcFh4rUx80i9Fs/PJnB3r1re3WmquhsUvhzDdf/X/NTa64H5xD+SpYVUNFvJbN
cA78yeNmuk6NO4HLFWR7uZToXTNShXEuT46iBhFRyePLoW4xCGQMwtI89Tbo19AOeCMgkckkKmUp
WyL3Ic6DXqTz3kvTaI9GdVyDCW4pa8RwjPWd1yAv/0bSKzjCL3UcPX7ape8eYIVpQtPM+GP+HkM5
haa2Y0EQs3MevNP6yn0WR+Kn1dCjigoIlmJWbjTb2QK5MHXjBNLnj8KwEUAKrNVxAmKLMb7dxiNY
MUJDLXT5xp6mig/p/r+D5kNXJLrvRjSq1xIBOO0CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw
HQYDVR0hBBYwFDASBgdghXQBUwABBgdghXQBUwABMBIGA1UdEwEB/wQIMAYBAf8CAQcwHwYDVR0j
BBgwFoAUAyUv3m+CATpcLNwroWm1Z9SM0/0wHQYDVR0OBBYEFAMlL95vggE6XCzcK6FptWfUjNP9
MA0GCSqGSIb3DQEBBQUAA4ICAQA1EMvspgQNDQ/NwNurqPKIlwzfky9NfEBWMXrrpA9gzXrzvsMn
jgM+pN0S734edAY8PzHyHHuRMSG08NBsl9Tpl7IkVh5WwzW9iAUPWxAaZOHHgjD5Mq2eUCzneAXQ
MbFamIp1TpBcahQq4FJHgmDmHtqBsfsUC1rxn9KVuj7QG9YVHaO+htXbD8BJZLsuUBlL0iT43R4H
VtA4oJVwIHaM190e3p9xxCPvgxNcoyQVTSlAPGrEqdi3pkSlDfTgnXceQHAm/NrZNuR55LU/vJtl
vrsRls/bxig5OgjOR1tTWsWZ/l2p3e9M1MalrQLmjAcSHm8D0W+go/MpvRLHUKKwf4ipmXeascCl
OS5cfGniLLDqN2qk4Vrh9VDlg++luyqI54zb/W1elxmofmZ1a3Hqv7HHb6D0jqTsNFFbjCYDcKF3
1QESVwA12yPeDooomf2xEG9L/zgtYE4snOtnta1J7ksfrK/7DZBaZmBwXarNeNQk7shBoJMBkpxq
nvy5JMWzFYJ+vq6VK+uxwNrjAWALXmmshFZhvnEX/h0TD/7Gh0Xp/jKgGg0TpJRVcaUWi7rKibCy
x/yP2FS1k2Kdzs9Z+z0YzirLNRWCXf9UIltxUvu3yf5gmwBBZPCqKuy2QkPOiWaByIufOVQDJdMW
NY6E0F/6MBr1mmz0DlP5OlvRHA==
-----END CERTIFICATE-----

DigiCert Assured ID Root CA
===========================
-----BEGIN CERTIFICATE-----
MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG
EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw
IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx
MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL
ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO
9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy
UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW
/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy
oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf
GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF
66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq
hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc
EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn
SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i
8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe
+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==
-----END CERTIFICATE-----

DigiCert Global Root CA
=======================
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG
EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw
HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw
MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3
dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq
hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn
TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5
BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H
4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y
7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB
o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm
8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF
BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr
EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt
tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886
UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----

DigiCert High Assurance EV Root CA
==================================
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG
EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw
KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw
MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ
MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu
Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t
Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS
OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3
MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ
NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe
h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB
Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY
JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ
V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp
myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK
mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K
-----END CERTIFICATE-----

Certplus Class 2 Primary CA
===========================
-----BEGIN CERTIFICATE-----
MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE
BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN
OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy
dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR
5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ
Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO
YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e
e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME
CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ
YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t
L0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/AN9WM2K191EBkOvD
P9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8yfFC82x/xXp8HVGIutIKPidd3i1R
TtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMRFcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+
7UCmnYR0ObncHoUW2ikbhiMAybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW
//1IMwrh3KWBkJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7
l7+ijrRU
-----END CERTIFICATE-----

DST Root CA X3
==============
-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/MSQwIgYDVQQK
ExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMTDkRTVCBSb290IENBIFgzMB4X
DTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVowPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1
cmUgVHJ1c3QgQ28uMRcwFQYDVQQDEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmT
rE4Orz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEqOLl5CjH9
UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9bxiqKqy69cK3FCxolkHRy
xXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40d
utolucbY38EVAjqr2m7xPi71XAicPNaDaeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T
AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ
MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug
dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE
GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw
RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS
fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
-----END CERTIFICATE-----

DST ACES CA X6
==============
-----BEGIN CERTIFICATE-----
MIIECTCCAvGgAwIBAgIQDV6ZCtadt3js2AdWO4YV2TANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQG
EwJVUzEgMB4GA1UEChMXRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QxETAPBgNVBAsTCERTVCBBQ0VT
MRcwFQYDVQQDEw5EU1QgQUNFUyBDQSBYNjAeFw0wMzExMjAyMTE5NThaFw0xNzExMjAyMTE5NTha
MFsxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdDERMA8GA1UE
CxMIRFNUIEFDRVMxFzAVBgNVBAMTDkRTVCBBQ0VTIENBIFg2MIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAuT31LMmU3HWKlV1j6IR3dma5WZFcRt2SPp/5DgO0PWGSvSMmtWPuktKe1jzI
DZBfZIGxqAgNTNj50wUoUrQBJcWVHAx+PhCEdc/BGZFjz+iokYi5Q1K7gLFViYsx+tC3dr5BPTCa
pCIlF3PoHuLTrCq9Wzgh1SpL11V94zpVvddtawJXa+ZHfAjIgrrep4c9oW24MFbCswKBXy314pow
GCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4aahELfrd755jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPy
MjwmR/onJALJfh1biEITajV8fTXpLmaRcpPVMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1Ud
EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rkc3Qu
Y29tMGIGA1UdIARbMFkwVwYKYIZIAWUDAgEBATBJMEcGCCsGAQUFBwIBFjtodHRwOi8vd3d3LnRy
dXN0ZHN0LmNvbS9jZXJ0aWZpY2F0ZXMvcG9saWN5L0FDRVMtaW5kZXguaHRtbDAdBgNVHQ4EFgQU
CXIGThhDD+XWzMNqizF7eI+og7gwDQYJKoZIhvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V2
5FYrnJmQ6AgwbN99Pe7lv7UkQIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6t
Fr8hlxCBPeP/h40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQq
nExaBqXpIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpRrscL9yuwNwXs
vFcj4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf29w4LTJxoeHtxMcfrHuBnQfO3
oKfN5XozNmr6mis=
-----END CERTIFICATE-----

TURKTRUST Certificate Services Provider Root 1
==============================================
-----BEGIN CERTIFICATE-----
MIID+zCCAuOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBtzE/MD0GA1UEAww2VMOcUktUUlVTVCBF
bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGDAJUUjEP
MA0GA1UEBwwGQU5LQVJBMVYwVAYDVQQKDE0oYykgMjAwNSBUw5xSS1RSVVNUIEJpbGdpIMSwbGV0
acWfaW0gdmUgQmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLjAeFw0wNTA1MTMx
MDI3MTdaFw0xNTAzMjIxMDI3MTdaMIG3MT8wPQYDVQQDDDZUw5xSS1RSVVNUIEVsZWt0cm9uaWsg
U2VydGlmaWthIEhpem1ldCBTYcSfbGF5xLFjxLFzxLExCzAJBgNVBAYMAlRSMQ8wDQYDVQQHDAZB
TktBUkExVjBUBgNVBAoMTShjKSAyMDA1IFTDnFJLVFJVU1QgQmlsZ2kgxLBsZXRpxZ9pbSB2ZSBC
aWxpxZ9pbSBHw7x2ZW5sacSfaSBIaXptZXRsZXJpIEEuxZ4uMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEAylIF1mMD2Bxf3dJ7XfIMYGFbazt0K3gNfUW9InTojAPBxhEqPZW8qZSwu5GX
yGl8hMW0kWxsE2qkVa2kheiVfrMArwDCBRj1cJ02i67L5BuBf5OI+2pVu32Fks66WJ/bMsW9Xe8i
Si9BB35JYbOG7E6mQW6EvAPs9TscyB/C7qju6hJKjRTP8wrgUDn5CDX4EVmt5yLqS8oUBt5CurKZ
8y1UiBAG6uEaPj1nH/vO+3yC6BFdSsG5FOpU2WabfIl9BJpiyelSPJ6c79L1JuTm5Rh8i27fbMx4
W09ysstcP4wFjdFMjK2Sx+F4f2VsSQZQLJ4ywtdKxnWKWU51b0dewQIDAQABoxAwDjAMBgNVHRME
BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAV9VX/N5aAWSGk/KEVTCD21F/aAyT8z5Aa9CEKmu46
sWrv7/hg0Uw2ZkUd82YCdAR7kjCo3gp2D++Vbr3JN+YaDayJSFvMgzbC9UZcWYJWtNX+I7TYVBxE
q8Sn5RTOPEFhfEPmzcSBCYsk+1Ql1haolgxnB2+zUEfjHCQo3SqYpGH+2+oSN7wBGjSFvW5P55Fy
B0SFHljKVETd96y5y4khctuPwGkplyqjrhgjlxxBKot8KsF8kOipKMDTkcatKIdAaLX/7KfS0zgY
nNN9aV3wxqUeJBujR/xpB2jn5Jq07Q+hh4cCzofSSE7hvP/L8XKSRGQDJereW26fyfJOrN3H
-----END CERTIFICATE-----

TURKTRUST Certificate Services Provider Root 2
==============================================
-----BEGIN CERTIFICATE-----
MIIEPDCCAySgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBF
bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP
MA0GA1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg
QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwHhcN
MDUxMTA3MTAwNzU3WhcNMTUwOTE2MTAwNzU3WjCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBFbGVr
dHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEPMA0G
A1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmls
acWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpNn7DkUNMwxmYCMjHWHtPFoylzkkBH3MOrHUTpvqe
LCDe2JAOCtFp0if7qnefJ1Il4std2NiDUBd9irWCPwSOtNXwSadktx4uXyCcUHVPr+G1QRT0mJKI
x+XlZEdhR3n9wFHxwZnn3M5q+6+1ATDcRhzviuyV79z/rxAc653YsKpqhRgNF8k+v/Gb0AmJQv2g
QrSdiVFVKc8bcLyEVK3BEx+Y9C52YItdP5qtygy/p1Zbj3e41Z55SZI/4PGXJHpsmxcPbe9TmJEr
5A++WXkHeLuXlfSfadRYhwqp48y2WBmfJiGxxFmNskF1wK1pzpwACPI2/z7woQ8arBT9pmAPAgMB
AAGjQzBBMB0GA1UdDgQWBBTZN7NOBf3Zz58SFq62iS/rJTqIHDAPBgNVHQ8BAf8EBQMDBwYAMA8G
A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAHJglrfJ3NgpXiOFX7KzLXb7iNcX/ntt
Rbj2hWyfIvwqECLsqrkw9qtY1jkQMZkpAL2JZkH7dN6RwRgLn7Vhy506vvWolKMiVW4XSf/SKfE4
Jl3vpao6+XF75tpYHdN0wgH6PmlYX63LaL4ULptswLbcoCb6dxriJNoaN+BnrdFzgw2lGh1uEpJ+
hGIAF728JRhX8tepb1mIvDS3LoV4nZbcFMMsilKbloxSZj2GFotHuFEJjOp9zYhys2AzsfAKRO8P
9Qk3iCQOLGsgOqL6EfJANZxEaGM7rDNvY7wsu/LSy3Z9fYjYHcgFHW68lKlmjHdxx/qR+i9Rnuk5
UrbnBEI=
-----END CERTIFICATE-----

SwissSign Gold CA - G2
======================
-----BEGIN CERTIFICATE-----
MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw
EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN
MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp
c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq
t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C
jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg
vd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqEemA8atufK+ze3gE/bk3lUIbLtK/tREDF
ylqM2tIrfKjuvqblCqoOpd8FUrdVxyJdMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvR
AiTysybUa9oEVeXBCsdtMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuend
jIj3o02yMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69yFGkO
peUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPiaG59je883WX0XaxR
7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxMgI93e2CaHt+28kgeDrpOVG2Y4OGi
GqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw
AwEB/zAdBgNVHQ4EFgQUWyV7lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64
OfPAeGZe6Drn8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov
L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe645R88a7A3hfm
5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczOUYrHUDFu4Up+GC9pWbY9ZIEr
44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOf
Mke6UiI0HTJ6CVanfCU2qT1L2sCCbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6m
Gu6uLftIdxf+u+yvGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxp
mo/a77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk
vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf
KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br
NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj
viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ
-----END CERTIFICATE-----

SwissSign Silver CA - G2
========================
-----BEGIN CERTIFICATE-----
MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT
BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X
DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3
aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG
9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644
N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm
+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH
6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu
MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5h
qAaEuSh6XzjZG6k4sIN/c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5
FZGkECwJMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRHHTBs
ROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTfjNFusB3hB48IHpmc
celM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb65i/4z3GcRm25xBWNOHkDRUjvxF3X
CO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
BAUwAwEB/zAdBgNVHQ4EFgQUF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRB
tjpbO8tFnb0cwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0
cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBAHPGgeAn0i0P
4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShpWJHckRE1qTodvBqlYJ7YH39F
kWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L
3XWgwF15kIwb4FDm3jH+mHtwX6WQ2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx
/uNncqCxv1yL5PqZIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFa
DGi8aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2Xem1ZqSqP
e97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQRdAtq/gsD/KNVV4n+Ssuu
WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ
DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub
DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u
-----END CERTIFICATE-----

GeoTrust Primary Certification Authority
========================================
-----BEGIN CERTIFICATE-----
MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG
EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD
ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx
CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ
cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN
b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9
nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge
RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt
tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD
AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJKoZI
hvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ16CePbJC/kRYkRj5K
Ts4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl4b7UVXGYNTq+k+qurUKykG/g/CFN
NWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6KoKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHa
Floxt/m0cYASSJlyc1pZU8FjUjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG
1riR/aYNKxoUAT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk=
-----END CERTIFICATE-----

thawte Primary Root CA
======================
-----BEGIN CERTIFICATE-----
MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UE
BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2
aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3
MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwg
SW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMv
KGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMT
FnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCs
oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ
1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc
q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K
aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p
afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD
VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF
AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE
uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX
xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89
jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH
z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA==
-----END CERTIFICATE-----

VeriSign Class 3 Public Primary Certification Authority - G5
============================================================
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp
ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln
biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh
dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt
YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz
j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD
Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/
Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r
fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/
BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv
Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG
SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+
X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE
KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC
Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE
ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
-----END CERTIFICATE-----

SecureTrust CA
==============
-----BEGIN CERTIFICATE-----
MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBIMQswCQYDVQQG
EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xFzAVBgNVBAMTDlNlY3VyZVRy
dXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIzMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAe
BgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCC
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQX
OZEzZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO0gMdA+9t
DWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIaowW8xQmxSPmjL8xk037uH
GFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b
01k/unK8RCSc43Oz969XL0Imnal0ugBS8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmH
ursCAwEAAaOBnTCBmjATBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/
BAUwAwEB/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCegJYYj
aHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ
KoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt36Z3q059c4EVlew3KW+JwULKUBRSu
SceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHf
mbx8IVQr5Fiiu1cprp6poxkmD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZ
nMUFdAvnZyPSCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR
3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE=
-----END CERTIFICATE-----

Secure Global CA
================
-----BEGIN CERTIFICATE-----
MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQG
EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBH
bG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkxMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEg
MB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwg
Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx
YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ
bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g
8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV
HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi
0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud
EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn
oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA
MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+
OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn
CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5
3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc
f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW
-----END CERTIFICATE-----

COMODO Certification Authority
==============================
-----BEGIN CERTIFICATE-----
MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE
BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG
A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNVBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1
dGhvcml0eTAeFw0wNjEyMDEwMDAwMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEb
MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFD
T01PRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3UcEbVASY06m/weaKXTuH
+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI2GqGd0S7WWaXUF601CxwRM/aN5VCaTww
xHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV
4EajcNxo2f8ESIl33rXp+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA
1KGzqSX+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5OnKVI
rLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAOBgNVHQ8BAf8E
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9k
b2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOC
AQEAPpiem/Yb6dc5t3iuHXIYSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CP
OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/
RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc
IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN
+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ==
-----END CERTIFICATE-----

Network Solutions Certificate Authority
=======================================
-----BEGIN CERTIFICATE-----
MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG
EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr
IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx
MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu
MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx
jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT
aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT
crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc
/Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB
AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP
BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv
bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA
A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q
4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/
GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv
wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD
ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey
-----END CERTIFICATE-----

WellsSecure Public Root Certificate Authority
=============================================
-----BEGIN CERTIFICATE-----
MIIEvTCCA6WgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoM
F1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYw
NAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN
MDcxMjEzMTcwNzU0WhcNMjIxMjE0MDAwNzU0WjCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dl
bGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYD
VQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDub7S9eeKPCCGeOARBJe+rWxxTkqxtnt3CxC5FlAM1
iGd0V+PfjLindo8796jE2yljDpFoNoqXjopxaAkH5OjUDk/41itMpBb570OYj7OeUt9tkTmPOL13
i0Nj67eT/DBMHAGTthP796EfvyXhdDcsHqRePGj4S78NuR4uNuip5Kf4D8uCdXw1LSLWwr8L87T8
bJVhHlfXBIEyg1J55oNjz7fLY4sR4r1e6/aN7ZVyKLSsEmLpSjPmgzKuBXWVvYSV2ypcm44uDLiB
K0HmOFafSZtsdvqKXfcBeYF8wYNABf5x/Qw/zE5gCQ5lRxAvAcAFP4/4s0HvWkJ+We/SlwxlAgMB
AAGjggE0MIIBMDAPBgNVHRMBAf8EBTADAQH/MDkGA1UdHwQyMDAwLqAsoCqGKGh0dHA6Ly9jcmwu
cGtpLndlbGxzZmFyZ28uY29tL3dzcHJjYS5jcmwwDgYDVR0PAQH/BAQDAgHGMB0GA1UdDgQWBBQm
lRkQ2eihl5H/3BnZtQQ+0nMKajCBsgYDVR0jBIGqMIGngBQmlRkQ2eihl5H/3BnZtQQ+0nMKaqGB
i6SBiDCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRww
GgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMg
Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCAQEwDQYJKoZIhvcNAQEFBQADggEBALkVsUSRzCPI
K0134/iaeycNzXK7mQDKfGYZUMbVmO2rvwNa5U3lHshPcZeG1eMd/ZDJPHV3V3p9+N701NX3leZ0
bh08rnyd2wIDBSxxSyU+B+NemvVmFymIGjifz6pBA4SXa5M4esowRBskRDPQ5NHcKDj0E0M1NSlj
qHyita04pO2t/caaH/+Xc/77szWnk4bGdpEA5qxRFsQnMlzbc9qlk1eOPm01JghZ1edE13YgY+es
E2fDbbFwRnzVlhE9iW9dqKHrjQrawx0zbKPqZxmamX9LPYNRKh3KL4YMon4QLSvUFpULB6ouFJJJ
tylv2G0xffX8oRAHh84vWdw+WNs=
-----END CERTIFICATE-----

COMODO ECC Certification Authority
==================================
-----BEGIN CERTIFICATE-----
MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC
R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE
ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB
dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix
GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo
b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X
4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni
wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG
FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA
U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=
-----END CERTIFICATE-----

IGC/A
=====
-----BEGIN CERTIFICATE-----
MIIEAjCCAuqgAwIBAgIFORFFEJQwDQYJKoZIhvcNAQEFBQAwgYUxCzAJBgNVBAYTAkZSMQ8wDQYD
VQQIEwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVE
Q1NTSTEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZy
MB4XDTAyMTIxMzE0MjkyM1oXDTIwMTAxNzE0MjkyMlowgYUxCzAJBgNVBAYTAkZSMQ8wDQYDVQQI
EwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVEQ1NT
STEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZyMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsh/R0GLFMzvABIaIs9z4iPf930Pfeo2aSVz2
TqrMHLmh6yeJ8kbpO0px1R2OLc/mratjUMdUC24SyZA2xtgv2pGqaMVy/hcKshd+ebUyiHDKcMCW
So7kVc0dJ5S/znIq7Fz5cyD+vfcuiWe4u0dzEvfRNWk68gq5rv9GQkaiv6GFGvm/5P9JhfejcIYy
HF2fYPepraX/z9E0+X1bF8bc1g4oa8Ld8fUzaJ1O/Id8NhLWo4DoQw1VYZTqZDdH6nfK0LJYBcNd
frGoRpAxVs5wKpayMLh35nnAvSk7/ZR3TL0gzUEl4C7HG7vupARB0l2tEmqKm0f7yd1GQOGdPDPQ
tQIDAQABo3cwdTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBRjAVBgNVHSAEDjAMMAoGCCqB
egF5AQEBMB0GA1UdDgQWBBSjBS8YYFDCiQrdKyFP/45OqDAxNjAfBgNVHSMEGDAWgBSjBS8YYFDC
iQrdKyFP/45OqDAxNjANBgkqhkiG9w0BAQUFAAOCAQEABdwm2Pp3FURo/C9mOnTgXeQp/wYHE4RK
q89toB9RlPhJy3Q2FLwV3duJL92PoF189RLrn544pEfMs5bZvpwlqwN+Mw+VgQ39FuCIvjfwbF3Q
MZsyK10XZZOYYLxuj7GoPB7ZHPOpJkL5ZB3C55L29B5aqhlSXa/oovdgoPaN8In1buAKBQGVyYsg
Crpa/JosPL3Dt8ldeCUFP1YUmwza+zpI/pdpXsoQhvdOlgQITeywvl3cO45Pwf2aNjSaTFR+FwNI
lQgRHAdvhQh+XU3Endv7rs6y0bO4g2wdsrN58dhwmX7wEwLOXt1R0982gaEbeC9xs/FZTEYYKKuF
0mBWWg==
-----END CERTIFICATE-----

Security Communication EV RootCA1
=================================
-----BEGIN CERTIFICATE-----
MIIDfTCCAmWgAwIBAgIBADANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJKUDElMCMGA1UEChMc
U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEqMCgGA1UECxMhU2VjdXJpdHkgQ29tbXVuaWNh
dGlvbiBFViBSb290Q0ExMB4XDTA3MDYwNjAyMTIzMloXDTM3MDYwNjAyMTIzMlowYDELMAkGA1UE
BhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKjAoBgNVBAsTIVNl
Y3VyaXR5IENvbW11bmljYXRpb24gRVYgUm9vdENBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBALx/7FebJOD+nLpCeamIivqA4PUHKUPqjgo0No0c+qe1OXj/l3X3L+SqawSERMqm4miO
/VVQYg+kcQ7OBzgtQoVQrTyWb4vVog7P3kmJPdZkLjjlHmy1V4qe70gOzXppFodEtZDkBp2uoQSX
WHnvIEqCa4wiv+wfD+mEce3xDuS4GBPMVjZd0ZoeUWs5bmB2iDQL87PRsJ3KYeJkHcFGB7hj3R4z
ZbOOCVVSPbW9/wfrrWFVGCypaZhKqkDFMxRldAD5kd6vA0jFQFTcD4SQaCDFkpbcLuUCRarAX1T4
bepJz11sS6/vmsJWXMY1VkJqMF/Cq/biPT+zyRGPMUzXn0kCAwEAAaNCMEAwHQYDVR0OBBYEFDVK
9U2vP9eCOKyrcWUXdYydVZPmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqG
SIb3DQEBBQUAA4IBAQCoh+ns+EBnXcPBZsdAS5f8hxOQWsTvoMpfi7ent/HWtWS3irO4G8za+6xm
iEHO6Pzk2x6Ipu0nUBsCMCRGef4Eh3CXQHPRwMFXGZpppSeZq51ihPZRwSzJIxXYKLerJRO1RuGG
Av8mjMSIkh1W/hln8lXkgKNrnKt34VFxDSDbEJrbvXZ5B3eZKK2aXtqxT0QsNY6llsf9g/BYxnnW
mHyojf6GPgcWkuF75x3sM3Z+Qi5KhfmRiWiEA4Glm5q+4zfFVKtWOxgtQaQM+ELbmaDgcm+7XeEW
T1MKZPlO9L9OVL14bIjqv5wTJMJwaaJ/D8g8rQjJsJhAoyrniIPtd490
-----END CERTIFICATE-----

OISTE WISeKey Global Root GA CA
===============================
-----BEGIN CERTIFICATE-----
MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE
BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG
A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH
bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD
VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw
IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5
IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9
Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxRVVuuk+g3/ytr6dTqvirdqFEr12bDYVxg
Asj1znJ7O7jyTmUIms2kahnBAbtzptf2w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbD
d50kc3vkDIzh2TbhmYsFmQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ
/yxViJGg4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t94B3R
LoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw
AwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ
KoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOxSPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vIm
MMkQyh2I+3QZH4VFvbBsUfk2ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4
+vg1YFkCExh8vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa
hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZiFj4A4xylNoEY
okxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ/L7fCg0=
-----END CERTIFICATE-----

Microsec e-Szigno Root CA
=========================
-----BEGIN CERTIFICATE-----
MIIHqDCCBpCgAwIBAgIRAMy4579OKRr9otxmpRwsDxEwDQYJKoZIhvcNAQEFBQAwcjELMAkGA1UE
BhMCSFUxETAPBgNVBAcTCEJ1ZGFwZXN0MRYwFAYDVQQKEw1NaWNyb3NlYyBMdGQuMRQwEgYDVQQL
EwtlLVN6aWdubyBDQTEiMCAGA1UEAxMZTWljcm9zZWMgZS1Temlnbm8gUm9vdCBDQTAeFw0wNTA0
MDYxMjI4NDRaFw0xNzA0MDYxMjI4NDRaMHIxCzAJBgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVz
dDEWMBQGA1UEChMNTWljcm9zZWMgTHRkLjEUMBIGA1UECxMLZS1Temlnbm8gQ0ExIjAgBgNVBAMT
GU1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
AQDtyADVgXvNOABHzNuEwSFpLHSQDCHZU4ftPkNEU6+r+ICbPHiN1I2uuO/TEdyB5s87lozWbxXG
d36hL+BfkrYn13aaHUM86tnsL+4582pnS4uCzyL4ZVX+LMsvfUh6PXX5qqAnu3jCBspRwn5mS6/N
oqdNAoI/gqyFxuEPkEeZlApxcpMqyabAvjxWTHOSJ/FrtfX9/DAFYJLG65Z+AZHCabEeHXtTRbjc
QR/Ji3HWVBTji1R4P770Yjtb9aPs1ZJ04nQw7wHb4dSrmZsqa/i9phyGI0Jf7Enemotb9HI6QMVJ
PqW+jqpx62z69Rrkav17fVVA71hu5tnVvCSrwe+3AgMBAAGjggQ3MIIEMzBnBggrBgEFBQcBAQRb
MFkwKAYIKwYBBQUHMAGGHGh0dHBzOi8vcmNhLmUtc3ppZ25vLmh1L29jc3AwLQYIKwYBBQUHMAKG
IWh0dHA6Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNydDAPBgNVHRMBAf8EBTADAQH/MIIBcwYD
VR0gBIIBajCCAWYwggFiBgwrBgEEAYGoGAIBAQEwggFQMCgGCCsGAQUFBwIBFhxodHRwOi8vd3d3
LmUtc3ppZ25vLmh1L1NaU1ovMIIBIgYIKwYBBQUHAgIwggEUHoIBEABBACAAdABhAG4A+gBzAO0A
dAB2AOEAbgB5ACAA6QByAHQAZQBsAG0AZQB6AOkAcwDpAGgAZQB6ACAA6QBzACAAZQBsAGYAbwBn
AGEAZADhAHMA4QBoAG8AegAgAGEAIABTAHoAbwBsAGcA4QBsAHQAYQB0APMAIABTAHoAbwBsAGcA
4QBsAHQAYQB0AOEAcwBpACAAUwB6AGEAYgDhAGwAeQB6AGEAdABhACAAcwB6AGUAcgBpAG4AdAAg
AGsAZQBsAGwAIABlAGwAagDhAHIAbgBpADoAIABoAHQAdABwADoALwAvAHcAdwB3AC4AZQAtAHMA
egBpAGcAbgBvAC4AaAB1AC8AUwBaAFMAWgAvMIHIBgNVHR8EgcAwgb0wgbqggbeggbSGIWh0dHA6
Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNybIaBjmxkYXA6Ly9sZGFwLmUtc3ppZ25vLmh1L0NO
PU1pY3Jvc2VjJTIwZS1Temlnbm8lMjBSb290JTIwQ0EsT1U9ZS1Temlnbm8lMjBDQSxPPU1pY3Jv
c2VjJTIwTHRkLixMPUJ1ZGFwZXN0LEM9SFU/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDtiaW5h
cnkwDgYDVR0PAQH/BAQDAgEGMIGWBgNVHREEgY4wgYuBEGluZm9AZS1zemlnbm8uaHWkdzB1MSMw
IQYDVQQDDBpNaWNyb3NlYyBlLVN6aWduw7MgUm9vdCBDQTEWMBQGA1UECwwNZS1TemlnbsOzIEhT
WjEWMBQGA1UEChMNTWljcm9zZWMgS2Z0LjERMA8GA1UEBxMIQnVkYXBlc3QxCzAJBgNVBAYTAkhV
MIGsBgNVHSMEgaQwgaGAFMegSXUWYYTbMUuE0vE3QJDvTtz3oXakdDByMQswCQYDVQQGEwJIVTER
MA8GA1UEBxMIQnVkYXBlc3QxFjAUBgNVBAoTDU1pY3Jvc2VjIEx0ZC4xFDASBgNVBAsTC2UtU3pp
Z25vIENBMSIwIAYDVQQDExlNaWNyb3NlYyBlLVN6aWdubyBSb290IENBghEAzLjnv04pGv2i3Gal
HCwPETAdBgNVHQ4EFgQUx6BJdRZhhNsxS4TS8TdAkO9O3PcwDQYJKoZIhvcNAQEFBQADggEBANMT
nGZjWS7KXHAM/IO8VbH0jgdsZifOwTsgqRy7RlRw7lrMoHfqaEQn6/Ip3Xep1fvj1KcExJW4C+FE
aGAHQzAxQmHl7tnlJNUb3+FKG6qfx1/4ehHqE5MAyopYse7tDk2016g2JnzgOsHVV4Lxdbb9iV/a
86g4nzUGCM4ilb7N1fy+W955a9x6qWVmvrElWl/tftOsRm1M9DKHtCAE4Gx4sHfRhUZLphK3dehK
yVZs15KrnfVJONJPU+NVkBHbmJbGSfI+9J8b4PeI3CVimUTYc78/MPMMNz7UwiiAc7EBt51alhQB
S6kRnSlqLtBdgcDPsiBDxwPgN05dCtxZICU=
-----END CERTIFICATE-----

Certigna
========
-----BEGIN CERTIFICATE-----
MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNVBAYTAkZSMRIw
EAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4XDTA3MDYyOTE1MTMwNVoXDTI3
MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwI
Q2VydGlnbmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7q
XOEm7RFHYeGifBZ4QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyH
GxnygQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbwzBfsV1/p
ogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q130yGLMLLGq/jj8UEYkg
DncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKf
Irjxwo1p3Po6WAbfAgMBAAGjgbwwgbkwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQ
tCRZvgHyUtVF9lo53BEwZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJ
BgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzjAQ/J
SP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG9w0BAQUFAAOCAQEA
hQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8hbV6lUmPOEvjvKtpv6zf+EwLHyzs+
ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFncfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1klu
PBS1xp81HlDQwY9qcEQCYsuuHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY
1gkIl2PlwS6wt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw
WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg==
-----END CERTIFICATE-----

AC Ra\xC3\xADz Certic\xC3\xA1mara S.A.
======================================
-----BEGIN CERTIFICATE-----
MIIGZjCCBE6gAwIBAgIPB35Sk3vgFeNX8GmMy+wMMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNVBAYT
AkNPMUcwRQYDVQQKDD5Tb2NpZWRhZCBDYW1lcmFsIGRlIENlcnRpZmljYWNpw7NuIERpZ2l0YWwg
LSBDZXJ0aWPDoW1hcmEgUy5BLjEjMCEGA1UEAwwaQUMgUmHDrXogQ2VydGljw6FtYXJhIFMuQS4w
HhcNMDYxMTI3MjA0NjI5WhcNMzAwNDAyMjE0MjAyWjB7MQswCQYDVQQGEwJDTzFHMEUGA1UECgw+
U29jaWVkYWQgQ2FtZXJhbCBkZSBDZXJ0aWZpY2FjacOzbiBEaWdpdGFsIC0gQ2VydGljw6FtYXJh
IFMuQS4xIzAhBgNVBAMMGkFDIFJhw616IENlcnRpY8OhbWFyYSBTLkEuMIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAq2uJo1PMSCMI+8PPUZYILrgIem08kBeGqentLhM0R7LQcNzJPNCN
yu5LF6vQhbCnIwTLqKL85XXbQMpiiY9QngE9JlsYhBzLfDe3fezTf3MZsGqy2IiKLUV0qPezuMDU
2s0iiXRNWhU5cxh0T7XrmafBHoi0wpOQY5fzp6cSsgkiBzPZkc0OnB8OIMfuuzONj8LSWKdf/WU3
4ojC2I+GdV75LaeHM/J4Ny+LvB2GNzmxlPLYvEqcgxhaBvzz1NS6jBUJJfD5to0EfhcSM2tXSExP
2yYe68yQ54v5aHxwD6Mq0Do43zeX4lvegGHTgNiRg0JaTASJaBE8rF9ogEHMYELODVoqDA+bMMCm
8Ibbq0nXl21Ii/kDwFJnmxL3wvIumGVC2daa49AZMQyth9VXAnow6IYm+48jilSH5L887uvDdUhf
HjlvgWJsxS3EF1QZtzeNnDeRyPYL1epjb4OsOMLzP96a++EjYfDIJss2yKHzMI+ko6Kh3VOz3vCa
Mh+DkXkwwakfU5tTohVTP92dsxA7SH2JD/ztA/X7JWR1DhcZDY8AFmd5ekD8LVkH2ZD6mq093ICK
5lw1omdMEWux+IBkAC1vImHFrEsm5VoQgpukg3s0956JkSCXjrdCx2bD0Omk1vUgjcTDlaxECp1b
czwmPS9KvqfJpxAe+59QafMCAwEAAaOB5jCB4zAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE
AwIBBjAdBgNVHQ4EFgQU0QnQ6dfOeXRU+Tows/RtLAMDG2gwgaAGA1UdIASBmDCBlTCBkgYEVR0g
ADCBiTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5jZXJ0aWNhbWFyYS5jb20vZHBjLzBaBggrBgEF
BQcCAjBOGkxMaW1pdGFjaW9uZXMgZGUgZ2FyYW507WFzIGRlIGVzdGUgY2VydGlmaWNhZG8gc2Ug
cHVlZGVuIGVuY29udHJhciBlbiBsYSBEUEMuMA0GCSqGSIb3DQEBBQUAA4ICAQBclLW4RZFNjmEf
AygPU3zmpFmps4p6xbD/CHwso3EcIRNnoZUSQDWDg4902zNc8El2CoFS3UnUmjIz75uny3XlesuX
EpBcunvFm9+7OSPI/5jOCk0iAUgHforA1SBClETvv3eiiWdIG0ADBaGJ7M9i4z0ldma/Jre7Ir5v
/zlXdLp6yQGVwZVR6Kss+LGGIOk/yzVb0hfpKv6DExdA7ohiZVvVO2Dpezy4ydV/NgIlqmjCMRW3
MGXrfx1IebHPOeJCgBbT9ZMj/EyXyVo3bHwi2ErN0o42gzmRkBDI8ck1fj+404HGIGQatlDCIaR4
3NAvO2STdPCWkPHv+wlaNECW8DYSwaN0jJN+Qd53i+yG2dIPPy3RzECiiWZIHiCznCNZc6lEc7wk
eZBWN7PGKX6jD/EpOe9+XCgycDWs2rjIdWb8m0w5R44bb5tNAlQiM+9hup4phO9OSzNHdpdqy35f
/RWmnkJDW2ZaiogN9xa5P1FlK2Zqi9E4UqLWRhH6/JocdJ6PlwsCT2TG9WjTSy3/pDceiz+/RL5h
RqGEPQgnTIEgd4kI6mdAXmwIUV80WoyWaM3X94nCHNMyAK9Sy9NgWyo6R35rMDOhYil/SrnhLecU
Iw4OGEfhefwVVdCx/CVxY3UzHCMrr1zZ7Ud3YA47Dx7SwNxkBYn8eNZcLCZDqQ==
-----END CERTIFICATE-----

TC TrustCenter Class 2 CA II
============================
-----BEGIN CERTIFICATE-----
MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC
REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy
IENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYw
MTEyMTQzODQzWhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1
c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UE
AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jftMjWQ+nEdVl//OEd+DFw
IxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKguNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2
xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2JXjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQ
Xa7pIXSSTYtZgo+U4+lK8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7u
SNQZu+995OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1UdEwEB
/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3kUrL84J6E1wIqzCB
7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90
Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU
cnVzdENlbnRlciUyMENsYXNzJTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i
SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iSGNn3Bzn1LL4G
dXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprtZjluS5TmVfwLG4t3wVMTZonZ
KNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8au0WOB9/WIFaGusyiC2y8zl3gK9etmF1Kdsj
TYjKUCjLhdLTEKJZbtOTVAB6okaVhgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kP
JOzHdiEoZa5X6AeIdUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfk
vQ==
-----END CERTIFICATE-----

TC TrustCenter Class 3 CA II
============================
-----BEGIN CERTIFICATE-----
MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC
REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy
IENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYw
MTEyMTQ0MTU3WhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1
c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UE
AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJWHt4bNwcwIi9v8Qbxq63W
yKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+QVl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo
6SI7dYnWRBpl8huXJh0obazovVkdKyT21oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZ
uV3bOx4a+9P/FRQI2AlqukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk
2ZyqBwi1Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1UdEwEB
/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NXXAek0CSnwPIA1DCB
7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90
Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU
cnVzdENlbnRlciUyMENsYXNzJTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i
SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlNirTzwppVMXzE
O2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8TtXqluJucsG7Kv5sbviRmEb8
yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9
IJqDnxrcOfHFcqMRA/07QlIp2+gB95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal
092Y+tTmBvTwtiBjS+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc
5A==
-----END CERTIFICATE-----

TC TrustCenter Universal CA I
=============================
-----BEGIN CERTIFICATE-----
MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTELMAkGA1UEBhMC
REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNVBAsTG1RDIFRydXN0Q2VudGVy
IFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcN
MDYwMzIyMTU1NDI4WhcNMjUxMjMxMjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMg
VHJ1c3RDZW50ZXIgR21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYw
JAYDVQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSRJJZ4Hgmgm5qVSkr1YnwC
qMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3TfCZdzHd55yx4Oagmcw6iXSVphU9VDprv
xrlE4Vc93x9UIuVvZaozhDrzznq+VZeujRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtw
ag+1m7Z3W0hZneTvWq3zwZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9O
gdwZu5GQfezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYDVR0j
BBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
AYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0GCSqGSIb3DQEBBQUAA4IBAQAo0uCG
1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X17caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/Cy
vwbZ71q+s2IhtNerNXxTPqYn8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3
ghUJGooWMNjsydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT
ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/2TYcuiUaUj0a
7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY
-----END CERTIFICATE-----

Deutsche Telekom Root CA 2
==========================
-----BEGIN CERTIFICATE-----
MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMT
RGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEG
A1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENBIDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5
MjM1OTAwWjBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0G
A1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBS
b290IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEUha88EOQ5
bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhCQN/Po7qCWWqSG6wcmtoI
KyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1MjwrrFDa1sPeg5TKqAyZMg4ISFZbavva4VhY
AUlfckE8FQYBjl2tqriTtM2e66foai1SNNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aK
Se5TBY8ZTNXeWHmb0mocQqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTV
jlsB9WoHtxa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAPBgNV
HRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAlGRZrTlk5ynr
E/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756AbrsptJh6sTtU6zkXR34ajgv8HzFZMQSy
zhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpaIzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8
rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G
dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU
Cm26OWMohpLzGITY+9HPBVZkVw==
-----END CERTIFICATE-----

ComSign Secured CA
==================
-----BEGIN CERTIFICATE-----
MIIDqzCCApOgAwIBAgIRAMcoRwmzuGxFjB36JPU2TukwDQYJKoZIhvcNAQEFBQAwPDEbMBkGA1UE
AxMSQ29tU2lnbiBTZWN1cmVkIENBMRAwDgYDVQQKEwdDb21TaWduMQswCQYDVQQGEwJJTDAeFw0w
NDAzMjQxMTM3MjBaFw0yOTAzMTYxNTA0NTZaMDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBD
QTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUwwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQDGtWhfHZQVw6QIVS3joFd67+l0Kru5fFdJGhFeTymHDEjWaueP1H5XJLkGieQcPOqs
49ohgHMhCu95mGwfCP+hUH3ymBvJVG8+pSjsIQQPRbsHPaHA+iqYHU4Gk/v1iDurX8sWv+bznkqH
7Rnqwp9D5PGBpX8QTz7RSmKtUxvLg/8HZaWSLWapW7ha9B20IZFKF3ueMv5WJDmyVIRD9YTC2LxB
kMyd1mja6YJQqTtoz7VdApRgFrFD2UNd3V2Hbuq7s8lr9gOUCXDeFhF6K+h2j0kQmHe5Y1yLM5d1
9guMsqtb3nQgJT/j8xH5h2iGNXHDHYwt6+UarA9z1YJZQIDTAgMBAAGjgacwgaQwDAYDVR0TBAUw
AwEB/zBEBgNVHR8EPTA7MDmgN6A1hjNodHRwOi8vZmVkaXIuY29tc2lnbi5jby5pbC9jcmwvQ29t
U2lnblNlY3VyZWRDQS5jcmwwDgYDVR0PAQH/BAQDAgGGMB8GA1UdIwQYMBaAFMFL7XC29z58ADsA
j8c+DkWfHl3sMB0GA1UdDgQWBBTBS+1wtvc+fAA7AI/HPg5Fnx5d7DANBgkqhkiG9w0BAQUFAAOC
AQEAFs/ukhNQq3sUnjO2QiBq1BW9Cav8cujvR3qQrFHBZE7piL1DRYHjZiM/EoZNGeQFsOY3wo3a
BijJD4mkU6l1P7CW+6tMM1X5eCZGbxs2mPtCdsGCuY7e+0X5YxtiOzkGynd6qDwJz2w2PQ8KRUtp
FhpFfTMDZflScZAmlaxMDPWLkz/MdXSFmLr/YnpNH4n+rr2UAJm/EaXc4HnFFgt9AmEd6oX5AhVP
51qJThRv4zdLhfXBPGHg/QVBspJ/wx2g0K5SZGBrGMYmnNj1ZOQ2GmKfig8+/21OGVZOIJFsnzQz
OjRXUDpvgV4GxvU+fE6OK85lBi5d0ipTdF7Tbieejw==
-----END CERTIFICATE-----

Cybertrust Global Root
======================
-----BEGIN CERTIFICATE-----
MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li
ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4
MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD
ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW
0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL
AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin
89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT
8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP
BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2
MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G
A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO
lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi
5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2
hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T
X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW
WL1WMRJOEcgh4LMRkWXbtKaIOM5V
-----END CERTIFICATE-----

ePKI Root Certification Authority
=================================
-----BEGIN CERTIFICATE-----
MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG
EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg
Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx
MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq
MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs
IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi
lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYfl61dd4s5oz9wCGzh1NlDiv
qOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX
12ruOzjjK9SXDrkb5wdJfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0O
WQqraffAsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uUWH1+
ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLSnT0IFaUQAS2zMnao
lQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pHdmX2Os+PYhcZewoozRrSgx4hxyy/
vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJipNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXi
Zo1jDiVN1Rmy5nk3pyKdVDECAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/Qkqi
MAwGA1UdEwQFMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH
ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGBuvl2ICO1J2B0
1GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6YlPwZpVnPDimZI+ymBV3QGypzq
KOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkPJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdV
xrsStZf0X4OFunHB2WyBEXYKCrC/gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEP
NXubrjlpC2JgQCA2j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+r
GNm65ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUBo2M3IUxE
xJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS/jQ6fbjpKdx2qcgw+BRx
gMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2zGp1iro2C6pSe3VkQw63d4k3jMdXH7Ojy
sP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTEW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmOD
BCEIZ43ygknQW/2xzQ+DhNQ+IIX3Sj0rnP0qCglN6oH4EZw=
-----END CERTIFICATE-----

T\xc3\x9c\x42\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 - S\xC3\xBCr\xC3\xBCm 3
=============================================================================================================================
-----BEGIN CERTIFICATE-----
MIIFFzCCA/+gAwIBAgIBETANBgkqhkiG9w0BAQUFADCCASsxCzAJBgNVBAYTAlRSMRgwFgYDVQQH
DA9HZWJ6ZSAtIEtvY2FlbGkxRzBFBgNVBAoMPlTDvHJraXllIEJpbGltc2VsIHZlIFRla25vbG9q
aWsgQXJhxZ90xLFybWEgS3VydW11IC0gVMOcQsSwVEFLMUgwRgYDVQQLDD9VbHVzYWwgRWxla3Ry
b25payB2ZSBLcmlwdG9sb2ppIEFyYcWfdMSxcm1hIEVuc3RpdMO8c8O8IC0gVUVLQUUxIzAhBgNV
BAsMGkthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppMUowSAYDVQQDDEFUw5xCxLBUQUsgVUVLQUUg
S8O2ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSAtIFPDvHLDvG0gMzAeFw0wNzA4
MjQxMTM3MDdaFw0xNzA4MjExMTM3MDdaMIIBKzELMAkGA1UEBhMCVFIxGDAWBgNVBAcMD0dlYnpl
IC0gS29jYWVsaTFHMEUGA1UECgw+VMO8cmtpeWUgQmlsaW1zZWwgdmUgVGVrbm9sb2ppayBBcmHF
n3TEsXJtYSBLdXJ1bXUgLSBUw5xCxLBUQUsxSDBGBgNVBAsMP1VsdXNhbCBFbGVrdHJvbmlrIHZl
IEtyaXB0b2xvamkgQXJhxZ90xLFybWEgRW5zdGl0w7xzw7wgLSBVRUtBRTEjMCEGA1UECwwaS2Ft
dSBTZXJ0aWZpa2FzeW9uIE1lcmtlemkxSjBIBgNVBAMMQVTDnELEsFRBSyBVRUtBRSBLw7ZrIFNl
cnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIC0gU8O8csO8bSAzMIIBIjANBgkqhkiG9w0B
AQEFAAOCAQ8AMIIBCgKCAQEAim1L/xCIOsP2fpTo6iBkcK4hgb46ezzb8R1Sf1n68yJMlaCQvEhO
Eav7t7WNeoMojCZG2E6VQIdhn8WebYGHV2yKO7Rm6sxA/OOqbLLLAdsyv9Lrhc+hDVXDWzhXcLh1
xnnRFDDtG1hba+818qEhTsXOfJlfbLm4IpNQp81McGq+agV/E5wrHur+R84EpW+sky58K5+eeROR
6Oqeyjh1jmKwlZMq5d/pXpduIF9fhHpEORlAHLpVK/swsoHvhOPc7Jg4OQOFCKlUAwUp8MmPi+oL
hmUZEdPpCSPeaJMDyTYcIW7OjGbxmTDY17PDHfiBLqi9ggtm/oLL4eAagsNAgQIDAQABo0IwQDAd
BgNVHQ4EFgQUvYiHyY/2pAoLquvF/pEjnatKijIwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF
MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAB18+kmPNOm3JpIWmgV050vQbTlswyb2zrgxvMTfvCr4
N5EY3ATIZJkrGG2AA1nJrvhY0D7twyOfaTyGOBye79oneNGEN3GKPEs5z35FBtYt2IpNeBLWrcLT
y9LQQfMmNkqblWwM7uXRQydmwYj3erMgbOqwaSvHIOgMA8RBBZniP+Rr+KCGgceExh/VS4ESshYh
LBOhgLJeDEoTniDYYkCrkOpkSi+sDQESeUWoL4cZaMjihccwsnX5OD+ywJO0a+IDRM5noN+J1q2M
dqMTw5RhK2vZbMEHCiIHhWyFJEapvj+LeISCfiQMnf2BN+MlqO02TpUsyZyQ2uypQjyttgI=
-----END CERTIFICATE-----

Buypass Class 2 CA 1
====================
-----BEGIN CERTIFICATE-----
MIIDUzCCAjugAwIBAgIBATANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMiBDQSAxMB4XDTA2
MTAxMzEwMjUwOVoXDTE2MTAxMzEwMjUwOVowSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh
c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDIgQ0EgMTCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAIs8B0XY9t/mx8q6jUPFR42wWsE425KEHK8T1A9vNkYgxC7M
cXA0ojTTNy7Y3Tp3L8DrKehc0rWpkTSHIln+zNvnma+WwajHQN2lFYxuyHyXA8vmIPLXl18xoS83
0r7uvqmtqEyeIWZDO6i88wmjONVZJMHCR3axiFyCO7srpgTXjAePzdVBHfCuuCkslFJgNJQ72uA4
0Z0zPhX0kzLFANq1KWYOOngPIVJfAuWSeyXTkh4vFZ2B5J2O6O+JzhRMVB0cgRJNcKi+EAUXfh/R
uFdV7c27UsKwHnjCTTZoy1YmwVLBvXb3WNVyfh9EdrsAiR0WnVE1703CVu9r4Iw7DekCAwEAAaNC
MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUP42aWYv8e3uco684sDntkHGA1sgwDgYDVR0P
AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQAVGn4TirnoB6NLJzKyQJHyIdFkhb5jatLPgcIV
1Xp+DCmsNx4cfHZSldq1fyOhKXdlyTKdqC5Wq2B2zha0jX94wNWZUYN/Xtm+DKhQ7SLHrQVMdvvt
7h5HZPb3J31cKA9FxVxiXqaakZG3Uxcu3K1gnZZkOb1naLKuBctN518fV4bVIJwo+28TOPX2EZL2
fZleHwzoq0QkKXJAPTZSr4xYkHPB7GEseaHsh7U/2k3ZIQAw3pDaDtMaSKk+hQsUi4y8QZ5q9w5w
wDX3OaJdZtB7WZ+oRxKaJyOkLY4ng5IgodcVf/EuGO70SH8vf/GhGLWhC5SgYiAynB321O+/TIho
-----END CERTIFICATE-----

Buypass Class 3 CA 1
====================
-----BEGIN CERTIFICATE-----
MIIDUzCCAjugAwIBAgIBAjANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMyBDQSAxMB4XDTA1
MDUwOTE0MTMwM1oXDTE1MDUwOTE0MTMwM1owSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh
c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDMgQ0EgMTCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAKSO13TZKWTeXx+HgJHqTjnmGcZEC4DVC69TB4sSveZn8AKx
ifZgisRbsELRwCGoy+Gb72RRtqfPFfV0gGgEkKBYouZ0plNTVUhjP5JW3SROjvi6K//zNIqeKNc0
n6wv1g/xpC+9UrJJhW05NfBEMJNGJPO251P7vGGvqaMU+8IXF4Rs4HyI+MkcVyzwPX6UvCWThOia
AJpFBUJXgPROztmuOfbIUxAMZTpHe2DC1vqRycZxbL2RhzyRhkmr8w+gbCZ2Xhysm3HljbybIR6c
1jh+JIAVMYKWsUnTYjdbiAwKYjT+p0h+mbEwi5A3lRyoH6UsjfRVyNvdWQrCrXig9IsCAwEAAaNC
MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUOBTmyPCppAP0Tj4io1vy1uCtQHQwDgYDVR0P
AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQABZ6OMySU9E2NdFm/soT4JXJEVKirZgCFPBdy7
pYmrEzMqnji3jG8CcmPHc3ceCQa6Oyh7pEfJYWsICCD8igWKH7y6xsL+z27sEzNxZy5p+qksP2bA
EllNC1QCkoS72xLvg3BweMhT+t/Gxv/ciC8HwEmdMldg0/L2mSlf56oBzKwzqBwKu5HEA6BvtjT5
htOzdlSY9EqBs1OdTUDs5XcTRa9bqh/YL0yCe/4qxFi7T/ye/QNlGioOw6UgFpRreaaiErS7GqQj
el/wroQk5PMr+4okoyeYZdowdXb8GZHo2+ubPzK/QJcHJrrM85SFSnonk8+QQtS4Wxam58tAA915
-----END CERTIFICATE-----

EBG Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1
==========================================================================
-----BEGIN CERTIFICATE-----
MIIF5zCCA8+gAwIBAgIITK9zQhyOdAIwDQYJKoZIhvcNAQEFBQAwgYAxODA2BgNVBAMML0VCRyBF
bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMTcwNQYDVQQKDC5FQkcg
QmlsacWfaW0gVGVrbm9sb2ppbGVyaSB2ZSBIaXptZXRsZXJpIEEuxZ4uMQswCQYDVQQGEwJUUjAe
Fw0wNjA4MTcwMDIxMDlaFw0xNjA4MTQwMDMxMDlaMIGAMTgwNgYDVQQDDC9FQkcgRWxla3Ryb25p
ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTE3MDUGA1UECgwuRUJHIEJpbGnFn2lt
IFRla25vbG9qaWxlcmkgdmUgSGl6bWV0bGVyaSBBLsWeLjELMAkGA1UEBhMCVFIwggIiMA0GCSqG
SIb3DQEBAQUAA4ICDwAwggIKAoICAQDuoIRh0DpqZhAy2DE4f6en5f2h4fuXd7hxlugTlkaDT7by
X3JWbhNgpQGR4lvFzVcfd2NR/y8927k/qqk153nQ9dAktiHq6yOU/im/+4mRDGSaBUorzAzu8T2b
gmmkTPiab+ci2hC6X5L8GCcKqKpE+i4stPtGmggDg3KriORqcsnlZR9uKg+ds+g75AxuetpX/dfr
eYteIAbTdgtsApWjluTLdlHRKJ2hGvxEok3MenaoDT2/F08iiFD9rrbskFBKW5+VQarKD7JK/oCZ
TqNGFav4c0JqwmZ2sQomFd2TkuzbqV9UIlKRcF0T6kjsbgNs2d1s/OsNA/+mgxKb8amTD8UmTDGy
Y5lhcucqZJnSuOl14nypqZoaqsNW2xCaPINStnuWt6yHd6i58mcLlEOzrz5z+kI2sSXFCjEmN1Zn
uqMLfdb3ic1nobc6HmZP9qBVFCVMLDMNpkGMvQQxahByCp0OLna9XvNRiYuoP1Vzv9s6xiQFlpJI
qkuNKgPlV5EQ9GooFW5Hd4RcUXSfGenmHmMWOeMRFeNYGkS9y8RsZteEBt8w9DeiQyJ50hBs37vm
ExH8nYQKE3vwO9D8owrXieqWfo1IhR5kX9tUoqzVegJ5a9KK8GfaZXINFHDk6Y54jzJ0fFfy1tb0
Nokb+Clsi7n2l9GkLqq+CxnCRelwXQIDAJ3Zo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB
/wQEAwIBBjAdBgNVHQ4EFgQU587GT/wWZ5b6SqMHwQSny2re2kcwHwYDVR0jBBgwFoAU587GT/wW
Z5b6SqMHwQSny2re2kcwDQYJKoZIhvcNAQEFBQADggIBAJuYml2+8ygjdsZs93/mQJ7ANtyVDR2t
FcU22NU57/IeIl6zgrRdu0waypIN30ckHrMk2pGI6YNw3ZPX6bqz3xZaPt7gyPvT/Wwp+BVGoGgm
zJNSroIBk5DKd8pNSe/iWtkqvTDOTLKBtjDOWU/aWR1qeqRFsIImgYZ29fUQALjuswnoT4cCB64k
XPBfrAowzIpAoHMEwfuJJPaaHFy3PApnNgUIMbOv2AFoKuB4j3TeuFGkjGwgPaL7s9QJ/XvCgKqT
bCmYIai7FvOpEl90tYeY8pUm3zTvilORiF0alKM/fCL414i6poyWqD1SNGKfAB5UVUJnxk1Gj7sU
RT0KlhaOEKGXmdXTMIXM3rRyt7yKPBgpaP3ccQfuJDlq+u2lrDgv+R4QDgZxGhBM/nV+/x5XOULK
1+EVoVZVWRvRo68R2E7DpSvvkL/A7IITW43WciyTTo9qKd+FPNMN4KIYEsxVL0e3p5sC/kH2iExt
2qkBR4NkJ2IQgtYSe14DHzSpyZH+r11thie3I6p1GMog57AP14kOpmciY/SDQSsGS7tY1dHXt7kQ
Y9iJSrSq3RZj9W6+YKH47ejWkE8axsWgKdOnIaj1Wjz3x0miIZpKlVIglnKaZsv30oZDfCK+lvm9
AahH3eU7QPl1K5srRmSGjR70j/sHd9DqSaIcjVIUpgqT
-----END CERTIFICATE-----

certSIGN ROOT CA
================
-----BEGIN CERTIFICATE-----
MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYTAlJPMREwDwYD
VQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTAeFw0wNjA3MDQxNzIwMDRa
Fw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UE
CxMQY2VydFNJR04gUk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7I
JUqOtdu0KBuqV5Do0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHH
rfAQUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5dRdY4zTW2
ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQOA7+j0xbm0bqQfWwCHTD
0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwvJoIQ4uNllAoEwF73XVv4EOLQunpL+943
AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B
Af8EBAMCAcYwHQYDVR0OBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB
AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8
SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0
x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt
vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz
TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD
-----END CERTIFICATE-----

CNNIC ROOT
==========
-----BEGIN CERTIFICATE-----
MIIDVTCCAj2gAwIBAgIESTMAATANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJDTjEOMAwGA1UE
ChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwHhcNMDcwNDE2MDcwOTE0WhcNMjcwNDE2MDcw
OTE0WjAyMQswCQYDVQQGEwJDTjEOMAwGA1UEChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1Qw
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTNfc/c3et6FtzF8LRb+1VvG7q6KR5smzD
o+/hn7E7SIX1mlwhIhAsxYLO2uOabjfhhyzcuQxauohV3/2q2x8x6gHx3zkBwRP9SFIhxFXf2tiz
VHa6dLG3fdfA6PZZxU3Iva0fFNrfWEQlMhkqx35+jq44sDB7R3IJMfAw28Mbdim7aXZOV/kbZKKT
VrdvmW7bCgScEeOAH8tjlBAKqeFkgjH5jCftppkA9nCTGPihNIaj3XrCGHn2emU1z5DrvTOTn1Or
czvmmzQgLx3vqR1jGqCA2wMv+SYahtKNu6m+UjqHZ0gNv7Sg2Ca+I19zN38m5pIEo3/PIKe38zrK
y5nLAgMBAAGjczBxMBEGCWCGSAGG+EIBAQQEAwIABzAfBgNVHSMEGDAWgBRl8jGtKvf33VKWCscC
wQ7vptU7ETAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIB/jAdBgNVHQ4EFgQUZfIxrSr3991S
lgrHAsEO76bVOxEwDQYJKoZIhvcNAQEFBQADggEBAEs17szkrr/Dbq2flTtLP1se31cpolnKOOK5
Gv+e5m4y3R6u6jW39ZORTtpC4cMXYFDy0VwmuYK36m3knITnA3kXr5g9lNvHugDnuL8BV8F3RTIM
O/G0HAiw/VGgod2aHRM2mm23xzy54cXZF/qD1T0VoDy7HgviyJA/qIYM/PmLXoXLT1tLYhFHxUV8
BS9BsZ4QaRuZluBVeftOhpm4lNqGOGqTo+fLbuXf6iFViZx9fX+Y9QCJ7uOEwFyWtcVG6kbghVW2
G8kS1sHNzYDzAgE8yGnLRUhj2JTQ7IUOO04RZfSCjKY9ri4ilAnIXOo8gV0WKgOXFlUJ24pBgp5m
mxE=
-----END CERTIFICATE-----

ApplicationCA - Japanese Government
===================================
-----BEGIN CERTIFICATE-----
MIIDoDCCAoigAwIBAgIBMTANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJKUDEcMBoGA1UEChMT
SmFwYW5lc2UgR292ZXJubWVudDEWMBQGA1UECxMNQXBwbGljYXRpb25DQTAeFw0wNzEyMTIxNTAw
MDBaFw0xNzEyMTIxNTAwMDBaMEMxCzAJBgNVBAYTAkpQMRwwGgYDVQQKExNKYXBhbmVzZSBHb3Zl
cm5tZW50MRYwFAYDVQQLEw1BcHBsaWNhdGlvbkNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAp23gdE6Hj6UG3mii24aZS2QNcfAKBZuOquHMLtJqO8F6tJdhjYq+xpqcBrSGUeQ3DnR4
fl+Kf5Sk10cI/VBaVuRorChzoHvpfxiSQE8tnfWuREhzNgaeZCw7NCPbXCbkcXmP1G55IrmTwcrN
wVbtiGrXoDkhBFcsovW8R0FPXjQilbUfKW1eSvNNcr5BViCH/OlQR9cwFO5cjFW6WY2H/CPek9AE
jP3vbb3QesmlOmpyM8ZKDQUXKi17safY1vC+9D/qDihtQWEjdnjDuGWk81quzMKq2edY3rZ+nYVu
nyoKb58DKTCXKB28t89UKU5RMfkntigm/qJj5kEW8DOYRwIDAQABo4GeMIGbMB0GA1UdDgQWBBRU
WssmP3HMlEYNllPqa0jQk/5CdTAOBgNVHQ8BAf8EBAMCAQYwWQYDVR0RBFIwUKROMEwxCzAJBgNV
BAYTAkpQMRgwFgYDVQQKDA/ml6XmnKzlm73mlL/lupwxIzAhBgNVBAsMGuOCouODl+ODquOCseOD
vOOCt+ODp+ODs0NBMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADlqRHZ3ODrs
o2dGD/mLBqj7apAxzn7s2tGJfHrrLgy9mTLnsCTWw//1sogJhyzjVOGjprIIC8CFqMjSnHH2HZ9g
/DgzE+Ge3Atf2hZQKXsvcJEPmbo0NI2VdMV+eKlmXb3KIXdCEKxmJj3ekav9FfBv7WxfEPjzFvYD
io+nEhEMy/0/ecGc/WLuo89UDNErXxc+4z6/wCs+CZv+iKZ+tJIX/COUgb1up8WMwusRRdv4QcmW
dupwX3kSa+SjB1oF7ydJzyGfikwJcGapJsErEU4z0g781mzSDjJkaP+tBXhfAx2o45CsJOAPQKdL
rosot4LKGAfmt1t06SAZf7IbiVQ=
-----END CERTIFICATE-----

GeoTrust Primary Certification Authority - G3
=============================================
-----BEGIN CERTIFICATE-----
MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE
BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0
IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy
eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz
NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo
YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT
LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j
K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE
c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C
IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu
dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC
MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr
2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9
cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE
Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD
AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s
t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt
-----END CERTIFICATE-----

thawte Primary Root CA - G2
===========================
-----BEGIN CERTIFICATE-----
MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC
VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu
IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg
Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV
MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG
b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt
IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS
LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5
8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU
mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN
G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K
rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg==
-----END CERTIFICATE-----

thawte Primary Root CA - G3
===========================
-----BEGIN CERTIFICATE-----
MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE
BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2
aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv
cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w
ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh
d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD
VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG
A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At
P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC
+BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY
7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW
vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E
BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ
KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK
A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu
t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC
8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm
er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A=
-----END CERTIFICATE-----

GeoTrust Primary Certification Authority - G2
=============================================
-----BEGIN CERTIFICATE-----
MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC
VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu
Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD
ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1
OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg
MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl
b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG
BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc
KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD
VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+
EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m
ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2
npaqBA+K
-----END CERTIFICATE-----

VeriSign Universal Root Certification Authority
===============================================
-----BEGIN CERTIFICATE-----
MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE
BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u
IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV
UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj
1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP
MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72
9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I
AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR
tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G
CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O
a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud
DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3
Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx
Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx
P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P
wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4
mJO37M2CYfE45k+XmCpajQ==
-----END CERTIFICATE-----

VeriSign Class 3 Public Primary Certification Authority - G4
============================================================
-----BEGIN CERTIFICATE-----
MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC
VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3
b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz
ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj
YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU
cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo
b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8
Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz
rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB
/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw
HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u
Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD
A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx
AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA==
-----END CERTIFICATE-----

NetLock Arany (Class Gold) Főtanúsítvány
============================================
-----BEGIN CERTIFICATE-----
MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G
A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610
dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB
cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgx
MjA2MTUwODIxWjCBpzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxO
ZXRMb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlmaWNhdGlv
biBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNzIEdvbGQpIEbFkXRhbsO6
c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu
0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrTlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw
/HpYzY6b7cNGbIRwXdrzAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAk
H3B5r9s5VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRGILdw
fzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2BJtr+UBdADTHLpl1
neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAGAQH/AgEEMA4GA1UdDwEB/wQEAwIB
BjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2MU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwW
qZw8UQCgwBEIBaeZ5m8BiFRhbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTta
YtOUZcTh5m2C+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC
bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2FuLjbvrW5Kfna
NwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2XjG4Kvte9nHfRCaexOYNkbQu
dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E=
-----END CERTIFICATE-----

Staat der Nederlanden Root CA - G2
==================================
-----BEGIN CERTIFICATE-----
MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE
CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g
Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC
TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l
ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ
5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn
vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj
CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil
e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR
OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI
CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65
48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi
trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737
qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB
AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC
ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV
HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA
A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz
+51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj
f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN
kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk
CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF
URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb
CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h
oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV
IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm
66+KAQ==
-----END CERTIFICATE-----

CA Disig
========
-----BEGIN CERTIFICATE-----
MIIEDzCCAvegAwIBAgIBATANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMK
QnJhdGlzbGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwHhcNMDYw
MzIyMDEzOTM0WhcNMTYwMzIyMDEzOTM0WjBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMKQnJhdGlz
bGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQCS9jHBfYj9mQGp2HvycXXxMcbzdWb6UShGhJd4NLxs/LxFWYgm
GErENx+hSkS943EE9UQX4j/8SFhvXJ56CbpRNyIjZkMhsDxkovhqFQ4/61HhVKndBpnXmjxUizkD
Pw/Fzsbrg3ICqB9x8y34dQjbYkzo+s7552oftms1grrijxaSfQUMbEYDXcDtab86wYqg6I7ZuUUo
hwjstMoVvoLdtUSLLa2GDGhibYVW8qwUYzrG0ZmsNHhWS8+2rT+MitcE5eN4TPWGqvWP+j1scaMt
ymfraHtuM6kMgiioTGohQBUgDCZbg8KpFhXAJIJdKxatymP2dACw30PEEGBWZ2NFAgMBAAGjgf8w
gfwwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUjbJJaJ1yCCW5wCf1UJNWSEZx+Y8wDgYDVR0P
AQH/BAQDAgEGMDYGA1UdEQQvMC2BE2Nhb3BlcmF0b3JAZGlzaWcuc2uGFmh0dHA6Ly93d3cuZGlz
aWcuc2svY2EwZgYDVR0fBF8wXTAtoCugKYYnaHR0cDovL3d3dy5kaXNpZy5zay9jYS9jcmwvY2Ff
ZGlzaWcuY3JsMCygKqAohiZodHRwOi8vY2EuZGlzaWcuc2svY2EvY3JsL2NhX2Rpc2lnLmNybDAa
BgNVHSAEEzARMA8GDSuBHpGT5goAAAABAQEwDQYJKoZIhvcNAQEFBQADggEBAF00dGFMrzvY/59t
WDYcPQuBDRIrRhCA/ec8J9B6yKm2fnQwM6M6int0wHl5QpNt/7EpFIKrIYwvF/k/Ji/1WcbvgAa3
mkkp7M5+cTxqEEHA9tOasnxakZzArFvITV734VP/Q3f8nktnbNfzg9Gg4H8l37iYC5oyOGwwoPP/
CBUz91BKez6jPiCp3C9WgArtQVCwyfTssuMmRAAOb54GvCKWU3BlxFAKRmukLyeBEicTXxChds6K
ezfqwzlhA5WYOudsiCUI/HloDYd9Yvi0X/vF2Ey9WLw/Q1vUHgFNPGO+I++MzVpQuGhU+QqZMxEA
4Z7CRneC9VkGjCFMhwnN5ag=
-----END CERTIFICATE-----

Juur-SK
=======
-----BEGIN CERTIFICATE-----
MIIE5jCCA86gAwIBAgIEO45L/DANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA
c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw
DgYDVQQDEwdKdXVyLVNLMB4XDTAxMDgzMDE0MjMwMVoXDTE2MDgyNjE0MjMwMVowXTEYMBYGCSqG
SIb3DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVy
aW1pc2tlc2t1czEQMA4GA1UEAxMHSnV1ci1TSzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAIFxNj4zB9bjMI0TfncyRsvPGbJgMUaXhvSYRqTCZUXP00B841oiqBB4M8yIsdOBSvZiF3tf
TQou0M+LI+5PAk676w7KvRhj6IAcjeEcjT3g/1tf6mTll+g/mX8MCgkzABpTpyHhOEvWgxutr2TC
+Rx6jGZITWYfGAriPrsfB2WThbkasLnE+w0R9vXW+RvHLCu3GFH+4Hv2qEivbDtPL+/40UceJlfw
UR0zlv/vWT3aTdEVNMfqPxZIe5EcgEMPPbgFPtGzlc3Yyg/CQ2fbt5PgIoIuvvVoKIO5wTtpeyDa
Tpxt4brNj3pssAki14sL2xzVWiZbDcDq5WDQn/413z8CAwEAAaOCAawwggGoMA8GA1UdEwEB/wQF
MAMBAf8wggEWBgNVHSAEggENMIIBCTCCAQUGCisGAQQBzh8BAQEwgfYwgdAGCCsGAQUFBwICMIHD
HoHAAFMAZQBlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0ACAAbwBuACAAdgDkAGwAagBhAHMAdABh
AHQAdQBkACAAQQBTAC0AaQBzACAAUwBlAHIAdABpAGYAaQB0AHMAZQBlAHIAaQBtAGkAcwBrAGUA
cwBrAHUAcwAgAGEAbABhAG0ALQBTAEsAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQAaQBkAGUAIABr
AGkAbgBuAGkAdABhAG0AaQBzAGUAawBzMCEGCCsGAQUFBwIBFhVodHRwOi8vd3d3LnNrLmVlL2Nw
cy8wKwYDVR0fBCQwIjAgoB6gHIYaaHR0cDovL3d3dy5zay5lZS9qdXVyL2NybC8wHQYDVR0OBBYE
FASqekej5ImvGs8KQKcYP2/v6X2+MB8GA1UdIwQYMBaAFASqekej5ImvGs8KQKcYP2/v6X2+MA4G
A1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQUFAAOCAQEAe8EYlFOiCfP+JmeaUOTDBS8rNXiRTHyo
ERF5TElZrMj3hWVcRrs7EKACr81Ptcw2Kuxd/u+gkcm2k298gFTsxwhwDY77guwqYHhpNjbRxZyL
abVAyJRld/JXIWY7zoVAtjNjGr95HvxcHdMdkxuLDF2FvZkwMhgJkVLpfKG6/2SSmuz+Ne6ML678
IIbsSt4beDI3poHSna9aEhbKmVv8b20OxaAehsmR0FyYgl9jDIpaq9iVpszLita/ZEuOyoqysOkh
Mp6qqIWYNIE5ITuoOlIyPfZrN4YGWhWY3PARZv40ILcD9EEQfTmEeZZyY7aWAuVrua0ZTbvGRNs2
yyqcjg==
-----END CERTIFICATE-----

Hongkong Post Root CA 1
=======================
-----BEGIN CERTIFICATE-----
MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoT
DUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMB4XDTAzMDUx
NTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25n
IFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1
ApzQjVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEnPzlTCeqr
auh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjhZY4bXSNmO7ilMlHIhqqh
qZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9nnV0ttgCXjqQesBCNnLsak3c78QA3xMY
V18meMjWCnl3v/evt3a5pQuEF10Q6m/hq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNV
HRMBAf8ECDAGAQH/AgEDMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7i
h9legYsCmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI37pio
l7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clBoiMBdDhViw+5Lmei
IAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJsEhTkYY2sEJCehFC78JZvRZ+K88ps
T/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpOfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilT
c4afU9hDDl3WY4JxHYB0yvbiAmvZWg==
-----END CERTIFICATE-----

SecureSign RootCA11
===================
-----BEGIN CERTIFICATE-----
MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi
SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS
b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw
KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1
cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL
TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO
wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq
g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP
O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA
bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX
t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh
OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r
bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ
Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01
y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061
lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I=
-----END CERTIFICATE-----

ACEDICOM Root
=============
-----BEGIN CERTIFICATE-----
MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UEAwwNQUNFRElD
T00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMB4XDTA4
MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEWMBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoG
A1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEF
AAOCAg8AMIICCgKCAgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHk
WLn709gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7XBZXehuD
YAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5PGrjm6gSSrj0RuVFCPYew
MYWveVqc/udOXpJPQ/yrOq2lEiZmueIM15jO1FillUAKt0SdE3QrwqXrIhWYENiLxQSfHY9g5QYb
m8+5eaA9oiM/Qj9r+hwDezCNzmzAv+YbX79nuIQZ1RXve8uQNjFiybwCq0Zfm/4aaJQ0PZCOrfbk
HQl/Sog4P75n/TSW9R28MHTLOO7VbKvU/PQAtwBbhTIWdjPp2KOZnQUAqhbm84F9b32qhm2tFXTT
xKJxqvQUfecyuB+81fFOvW8XAjnXDpVCOscAPukmYxHqC9FK/xidstd7LzrZlvvoHpKuE1XI2Sf2
3EgbsCTBheN3nZqk8wwRHQ3ItBTutYJXCb8gWH8vIiPYcMt5bMlL8qkqyPyHK9caUPgn6C9D4zq9
2Fdx/c6mUlv53U3t5fZvie27k5x2IXXwkkwp9y+cAS7+UEaeZAwUswdbxcJzbPEHXEUkFDWug/Fq
TYl6+rPYLWbwNof1K1MCAwEAAaOBqjCBpzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKaz
4SsrSbbXc6GqlPUB53NlTKxQMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUprPhKytJttdzoaqU
9QHnc2VMrFAwRAYDVR0gBD0wOzA5BgRVHSAAMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly9hY2VkaWNv
bS5lZGljb21ncm91cC5jb20vZG9jMA0GCSqGSIb3DQEBBQUAA4ICAQDOLAtSUWImfQwng4/F9tqg
aHtPkl7qpHMyEVNEskTLnewPeUKzEKbHDZ3Ltvo/Onzqv4hTGzz3gvoFNTPhNahXwOf9jU8/kzJP
eGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKeI6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1Pwk
zQSulgUV1qzOMPPKC8W64iLgpq0i5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1
ThCojz2GuHURwCRiipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oI
KiMnMCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZo5NjEFIq
nxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6zqylfDJKZ0DcMDQj3dcE
I2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacNGHk0vFQYXlPKNFHtRQrmjseCNj6nOGOp
MCwXEGCSn1WHElkQwg9naRHMTh5+Spqtr0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3o
tkYNbn5XOmeUwssfnHdKZ05phkOTOPu220+DkdRgfks+KzgHVZhepA==
-----END CERTIFICATE-----

Verisign Class 3 Public Primary Certification Authority
=======================================================
-----BEGIN CERTIFICATE-----
MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCVVMx
FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVow
XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABByUqkFFBky
CEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWX
bj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/
D/xwzoiQ
-----END CERTIFICATE-----

Microsec e-Szigno Root CA 2009
==============================
-----BEGIN CERTIFICATE-----
MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER
MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv
c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o
dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE
BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt
U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA
fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG
0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA
pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm
1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC
AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf
QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE
FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o
lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX
I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775
tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02
yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi
LXpUq3DDfSJlgnCW
-----END CERTIFICATE-----

E-Guven Kok Elektronik Sertifika Hizmet Saglayicisi
===================================================
-----BEGIN CERTIFICATE-----
MIIDtjCCAp6gAwIBAgIQRJmNPMADJ72cdpW56tustTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG
EwJUUjEoMCYGA1UEChMfRWxla3Ryb25payBCaWxnaSBHdXZlbmxpZ2kgQS5TLjE8MDoGA1UEAxMz
ZS1HdXZlbiBLb2sgRWxla3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhZ2xheWljaXNpMB4XDTA3
MDEwNDExMzI0OFoXDTE3MDEwNDExMzI0OFowdTELMAkGA1UEBhMCVFIxKDAmBgNVBAoTH0VsZWt0
cm9uaWsgQmlsZ2kgR3V2ZW5saWdpIEEuUy4xPDA6BgNVBAMTM2UtR3V2ZW4gS29rIEVsZWt0cm9u
aWsgU2VydGlmaWthIEhpem1ldCBTYWdsYXlpY2lzaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAMMSIJ6wXgBljU5Gu4Bc6SwGl9XzcslwuedLZYDBS75+PNdUMZTe1RK6UxYC6lhj71vY
8+0qGqpxSKPcEC1fX+tcS5yWCEIlKBHMilpiAVDV6wlTL/jDj/6z/P2douNffb7tC+Bg62nsM+3Y
jfsSSYMAyYuXjDtzKjKzEve5TfL0TW3H5tYmNwjy2f1rXKPlSFxYvEK+A1qBuhw1DADT9SN+cTAI
JjjcJRFHLfO6IxClv7wC90Nex/6wN1CZew+TzuZDLMN+DfIcQ2Zgy2ExR4ejT669VmxMvLz4Bcpk
9Ok0oSy1c+HCPujIyTQlCFzz7abHlJ+tiEMl1+E5YP6sOVkCAwEAAaNCMEAwDgYDVR0PAQH/BAQD
AgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJ/uRLOU1fqRTy7ZVZoEVtstxNulMA0GCSqG
SIb3DQEBBQUAA4IBAQB/X7lTW2M9dTLn+sR0GstG30ZpHFLPqk/CaOv/gKlR6D1id4k9CnU58W5d
F4dvaAXBlGzZXd/aslnLpRCKysw5zZ/rTt5S/wzw9JKp8mxTq5vSR6AfdPebmvEvFZ96ZDAYBzwq
D2fK/A+JYZ1lpTzlvBNbCNvj/+27BrtqBrF6T2XGgv0enIu1De5Iu7i9qgi0+6N8y5/NkHZchpZ4
Vwpm+Vganf2XKWDeEaaQHBkc7gGWIjQ0LpH5t8Qn0Xvmv/uARFoW5evg1Ao4vOSR49XrXMGs3xtq
fJ7lddK2l4fbzIcrQzqECK+rPNv3PGYxhrCdU3nt+CPeQuMtgvEP5fqX
-----END CERTIFICATE-----

GlobalSign Root CA - R3
=======================
-----BEGIN CERTIFICATE-----
MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv
YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh
bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT
aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt
iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ
0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3
rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl
OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2
xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE
FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7
lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8
EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E
bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18
YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r
kpeDMdmztcpHWD9f
-----END CERTIFICATE-----

Autoridad de Certificacion Firmaprofesional CIF A62634068
=========================================================
-----BEGIN CERTIFICATE-----
MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA
BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2
MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw
QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBB
NjI2MzQwNjgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDD
Utd9thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQMcas9UX4P
B99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefGL9ItWY16Ck6WaVICqjaY
7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15iNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqH
ECNZXyAFGUftaI6SEspd/NYrspI8IM/hX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyI
plD9amML9ZMWGxmPsu2bm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctX
MbScyJCyZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirjaEbsX
LZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/TKI8xWVvTyQKmtFLK
bpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF6NkBiDkal4ZkQdU7hwxu+g/GvUgU
vzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVhOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1Ud
EwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNH
DhpkLzCBpgYDVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp
cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBvACAAZABlACAA
bABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBlAGwAbwBuAGEAIAAwADgAMAAx
ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx
51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk
R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP
T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f
Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl
osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR
crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR
saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD
KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi
6Et8Vcad+qMUu2WFbm5PEn4KPJ2V
-----END CERTIFICATE-----

Izenpe.com
==========
-----BEGIN CERTIFICATE-----
MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG
EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz
MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu
QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ
03rKDx6sp4boFmVqscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAK
ClaOxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6HLmYRY2xU
+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFXuaOKmMPsOzTFlUFpfnXC
PCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQDyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxT
OTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbK
F7jJeodWLBoBHmy+E60QrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK
0GqfvEyNBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8Lhij+
0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIBQFqNeb+Lz0vPqhbB
leStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+HMh3/1uaD7euBUbl8agW7EekFwID
AQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2luZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+
SVpFTlBFIFMuQS4gLSBDSUYgQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBG
NjIgUzgxQzBBBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx
MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O
BBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUAA4ICAQB4pgwWSp9MiDrAyw6l
Fn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga
kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q
hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs
g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5
aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5
nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC
ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo
Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z
WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==
-----END CERTIFICATE-----

Chambers of Commerce Root - 2008
================================
-----BEGIN CERTIFICATE-----
MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD
MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv
bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu
QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy
Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNl
ZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQF
EwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJl
cnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
AQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW928sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKA
XuFixrYp4YFs8r/lfTJqVKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorj
h40G072QDuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR5gN/
ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfLZEFHcpOrUMPrCXZk
NNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05aSd+pZgvMPMZ4fKecHePOjlO+Bd5g
D2vlGts/4+EhySnB8esHnFIbAURRPHsl18TlUlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331
lubKgdaX8ZSD6e2wsWsSaR6s+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ
0wlf2eOKNcx5Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj
ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAxhduub+84Mxh2
EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNVHQ4EFgQU+SSsD7K1+HnA+mCI
G8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJ
BgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNh
bWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENh
bWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiC
CQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUH
AgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAJASryI1
wqM58C7e6bXpeHxIvj99RZJe6dqxGfwWPJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH
3qLPaYRgM+gQDROpI9CF5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbU
RWpGqOt1glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaHFoI6
M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2pSB7+R5KBWIBpih1
YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MDxvbxrN8y8NmBGuScvfaAFPDRLLmF
9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QGtjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcK
zBIKinmwPQN/aUv0NCB9szTqjktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvG
nrDQWzilm1DefhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg
OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZd0jQ
-----END CERTIFICATE-----

Global Chambersign Root - 2008
==============================
-----BEGIN CERTIFICATE-----
MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD
MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv
bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu
QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx
NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg
Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ
QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD
aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf
VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf
XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0
ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB
/gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA
TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M
H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3VyJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfe
Ox2YItaswTXbo6Al/3K1dh3ebeksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSF
HTynyQbehP9r6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh
wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsogzCtLkykPAgMB
AAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQWBBS5CcqcHtvTbDprru1U8VuT
BjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDprru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UE
BhMCRVUxQzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJm
aXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJm
aXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiCCQDJzdPp
1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0
dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAICIf3DekijZBZRG
/5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZUohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6
ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/s
dZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg
9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH
foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du
qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr
P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq
c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z
09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B
-----END CERTIFICATE-----

Go Daddy Root Certificate Authority - G2
========================================
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu
MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5
MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6
b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G
A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq
9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD
+qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd
fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl
NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC
MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9
BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac
vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r
5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV
N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO
LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1
-----END CERTIFICATE-----

Starfield Root Certificate Authority - G2
=========================================
-----BEGIN CERTIFICATE-----
MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s
b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0
eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw
DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg
VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB
dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv
W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs
bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk
N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf
ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU
JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol
TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx
4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw
F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K
pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ
c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0
-----END CERTIFICATE-----

Starfield Services Root Certificate Authority - G2
==================================================
-----BEGIN CERTIFICATE-----
MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s
b2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRl
IEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNV
BAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxT
dGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2VydmljZXMg
Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20pOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2
h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4Pa
hHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLP
LJGmpufehRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk6mFB
rMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAwDwYDVR0TAQH/BAUw
AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+qAdcwKziIorhtSpzyEZGDMA0GCSqG
SIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMIbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPP
E95Dz+I0swSdHynVv/heyNXBve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTy
xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd
iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza
YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6
-----END CERTIFICATE-----

AffirmTrust Commercial
======================
-----BEGIN CERTIFICATE-----
MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS
BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw
MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly
bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb
DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV
C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6
BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww
MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV
HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG
hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi
qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv
0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh
sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8=
-----END CERTIFICATE-----

AffirmTrust Networking
======================
-----BEGIN CERTIFICATE-----
MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS
BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw
MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly
bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE
Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI
dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24
/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb
h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV
HQ4EFgQUBx/S55zawm6iQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
AQYwDQYJKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfOtDIu
UFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzuQY0x2+c06lkh1QF6
12S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZLgo/bNjR9eUJtGxUAArgFU2HdW23
WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4uolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9
/ZFvgrG+CJPbFEfxojfHRZ48x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s=
-----END CERTIFICATE-----

AffirmTrust Premium
===================
-----BEGIN CERTIFICATE-----
MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UEBhMCVVMxFDAS
BgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMB4XDTEwMDEy
OTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRy
dXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
MIICCgKCAgEAxBLfqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtn
BKAQJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ+jjeRFcV
5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrSs8PhaJyJ+HoAVt70VZVs
+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmd
GPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d770O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5R
p9EixAqnOEhss/n/fauGV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NI
S+LI+H+SqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S5u04
6uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4IaC1nEWTJ3s7xgaVY5
/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TXOwF0lkLgAOIua+rF7nKsu7/+6qqo
+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYEFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB
/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByv
MiPIs0laUZx2KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg
Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B8OWycvpEgjNC
6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQMKSOyARiqcTtNd56l+0OOF6S
L5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK
+4w1IX2COPKpVJEZNZOUbWo6xbLQu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmV
BtWVyuEklut89pMFu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFg
IxpHYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60
g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb
zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw==
-----END CERTIFICATE-----

AffirmTrust Premium ECC
=======================
-----BEGIN CERTIFICATE-----
MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV
BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx
MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U
cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA
IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ
N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW
BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK
BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X
57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM
eQ==
-----END CERTIFICATE-----

Certum Trusted Network CA
=========================
-----BEGIN CERTIFICATE-----
MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK
ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlv
biBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIy
MTIwNzM3WhcNMjkxMjMxMTIwNzM3WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBU
ZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
MSIwIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rHUV+rpDKmYYe2bg+G0jAC
l/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LMTXPb865Px1bVWqeWifrzq2jUI4ZZJ88J
J7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVUBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4
fOQtf/WsX+sWn7Et0brMkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0
cvW0QM8xAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNVHRMB
Af8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNVHQ8BAf8EBAMCAQYw
DQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15ysHhE49wcrwn9I0j6vSrEuVUEtRCj
jSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfLI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1
mS1FhIrlQgnXdAIv94nYmem8J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5aj
Zt3hrvJBW8qYVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI
03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw=
-----END CERTIFICATE-----

Certinomis - Autorité Racine
=============================
-----BEGIN CERTIFICATE-----
MIIFnDCCA4SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJGUjETMBEGA1UEChMK
Q2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxJjAkBgNVBAMMHUNlcnRpbm9taXMg
LSBBdXRvcml0w6kgUmFjaW5lMB4XDTA4MDkxNzA4Mjg1OVoXDTI4MDkxNzA4Mjg1OVowYzELMAkG
A1UEBhMCRlIxEzARBgNVBAoTCkNlcnRpbm9taXMxFzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMSYw
JAYDVQQDDB1DZXJ0aW5vbWlzIC0gQXV0b3JpdMOpIFJhY2luZTCCAiIwDQYJKoZIhvcNAQEBBQAD
ggIPADCCAgoCggIBAJ2Fn4bT46/HsmtuM+Cet0I0VZ35gb5j2CN2DpdUzZlMGvE5x4jYF1AMnmHa
wE5V3udauHpOd4cN5bjr+p5eex7Ezyh0x5P1FMYiKAT5kcOrJ3NqDi5N8y4oH3DfVS9O7cdxbwly
Lu3VMpfQ8Vh30WC8Tl7bmoT2R2FFK/ZQpn9qcSdIhDWerP5pqZ56XjUl+rSnSTV3lqc2W+HN3yNw
2F1MpQiD8aYkOBOo7C+ooWfHpi2GR+6K/OybDnT0K0kCe5B1jPyZOQE51kqJ5Z52qz6WKDgmi92N
jMD2AR5vpTESOH2VwnHu7XSu5DaiQ3XV8QCb4uTXzEIDS3h65X27uK4uIJPT5GHfceF2Z5c/tt9q
c1pkIuVC28+BA5PY9OMQ4HL2AHCs8MF6DwV/zzRpRbWT5BnbUhYjBYkOjUjkJW+zeL9i9Qf6lSTC
lrLooyPCXQP8w9PlfMl1I9f09bze5N/NgL+RiH2nE7Q5uiy6vdFrzPOlKO1Enn1So2+WLhl+HPNb
xxaOu2B9d2ZHVIIAEWBsMsGoOBvrbpgT1u449fCfDu/+MYHB0iSVL1N6aaLwD4ZFjliCK0wi1F6g
530mJ0jfJUaNSih8hp75mxpZuWW/Bd22Ql095gBIgl4g9xGC3srYn+Y3RyYe63j3YcNBZFgCQfna
4NH4+ej9Uji29YnfAgMBAAGjWzBZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G
A1UdDgQWBBQNjLZh2kS40RR9w759XkjwzspqsDAXBgNVHSAEEDAOMAwGCiqBegFWAgIAAQEwDQYJ
KoZIhvcNAQEFBQADggIBACQ+YAZ+He86PtvqrxyaLAEL9MW12Ukx9F1BjYkMTv9sov3/4gbIOZ/x
WqndIlgVqIrTseYyCYIDbNc/CMf4uboAbbnW/FIyXaR/pDGUu7ZMOH8oMDX/nyNTt7buFHAAQCva
R6s0fl6nVjBhK4tDrP22iCj1a7Y+YEq6QpA0Z43q619FVDsXrIvkxmUP7tCMXWY5zjKn2BCXwH40
nJ+U8/aGH88bc62UeYdocMMzpXDn2NU4lG9jeeu/Cg4I58UvD0KgKxRA/yHgBcUn4YQRE7rWhh1B
CxMjidPJC+iKunqjo3M3NYB9Ergzd0A4wPpeMNLytqOx1qKVl4GbUu1pTP+A5FPbVFsDbVRfsbjv
JL1vnxHDx2TCDyhihWZeGnuyt++uNckZM6i4J9szVb9o4XVIRFb7zdNIu0eJOqxp9YDG5ERQL1TE
qkPFMTFYvZbF6nVsmnWxTfj3l/+WFvKXTej28xH5On2KOG4Ey+HTRRWqpdEdnV1j6CTmNhTih60b
WfVEm/vXd3wfAXBioSAaosUaKPQhA+4u2cGA6rnZgtZbdsLLO7XSAPCjDuGtbkD326C00EauFddE
wk01+dIL8hf2rGbVJLJP0RyZwG71fet0BLj5TXcJ17TPBzAJ8bgAVtkXFhYKK4bfjwEZGuW7gmP/
vgt2Fl43N+bYdJeimUV5
-----END CERTIFICATE-----

Root CA Generalitat Valenciana
==============================
-----BEGIN CERTIFICATE-----
MIIGizCCBXOgAwIBAgIEO0XlaDANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJFUzEfMB0GA1UE
ChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290
IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwHhcNMDEwNzA2MTYyMjQ3WhcNMjEwNzAxMTUyMjQ3
WjBoMQswCQYDVQQGEwJFUzEfMB0GA1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UE
CxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGKqtXETcvIorKA3Qdyu0togu8M1JAJke+WmmmO3I2
F0zo37i7L3bhQEZ0ZQKQUgi0/6iMweDHiVYQOTPvaLRfX9ptI6GJXiKjSgbwJ/BXufjpTjJ3Cj9B
ZPPrZe52/lSqfR0grvPXdMIKX/UIKFIIzFVd0g/bmoGlu6GzwZTNVOAydTGRGmKy3nXiz0+J2ZGQ
D0EbtFpKd71ng+CT516nDOeB0/RSrFOyA8dEJvt55cs0YFAQexvba9dHq198aMpunUEDEO5rmXte
JajCq+TA81yc477OMUxkHl6AovWDfgzWyoxVjr7gvkkHD6MkQXpYHYTqWBLI4bft75PelAgxAgMB
AAGjggM7MIIDNzAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnBraS5n
dmEuZXMwEgYDVR0TAQH/BAgwBgEB/wIBAjCCAjQGA1UdIASCAiswggInMIICIwYKKwYBBAG/VQIB
ADCCAhMwggHoBggrBgEFBQcCAjCCAdoeggHWAEEAdQB0AG8AcgBpAGQAYQBkACAAZABlACAAQwBl
AHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAFIAYQDtAHoAIABkAGUAIABsAGEAIABHAGUAbgBlAHIA
YQBsAGkAdABhAHQAIABWAGEAbABlAG4AYwBpAGEAbgBhAC4ADQAKAEwAYQAgAEQAZQBjAGwAYQBy
AGEAYwBpAPMAbgAgAGQAZQAgAFAAcgDhAGMAdABpAGMAYQBzACAAZABlACAAQwBlAHIAdABpAGYA
aQBjAGEAYwBpAPMAbgAgAHEAdQBlACAAcgBpAGcAZQAgAGUAbAAgAGYAdQBuAGMAaQBvAG4AYQBt
AGkAZQBuAHQAbwAgAGQAZQAgAGwAYQAgAHAAcgBlAHMAZQBuAHQAZQAgAEEAdQB0AG8AcgBpAGQA
YQBkACAAZABlACAAQwBlAHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAHMAZQAgAGUAbgBjAHUAZQBu
AHQAcgBhACAAZQBuACAAbABhACAAZABpAHIAZQBjAGMAaQDzAG4AIAB3AGUAYgAgAGgAdAB0AHAA
OgAvAC8AdwB3AHcALgBwAGsAaQAuAGcAdgBhAC4AZQBzAC8AYwBwAHMwJQYIKwYBBQUHAgEWGWh0
dHA6Ly93d3cucGtpLmd2YS5lcy9jcHMwHQYDVR0OBBYEFHs100DSHHgZZu90ECjcPk+yeAT8MIGV
BgNVHSMEgY0wgYqAFHs100DSHHgZZu90ECjcPk+yeAT8oWykajBoMQswCQYDVQQGEwJFUzEfMB0G
A1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5S
b290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmGCBDtF5WgwDQYJKoZIhvcNAQEFBQADggEBACRh
TvW1yEICKrNcda3FbcrnlD+laJWIwVTAEGmiEi8YPyVQqHxK6sYJ2fR1xkDar1CdPaUWu20xxsdz
Ckj+IHLtb8zog2EWRpABlUt9jppSCS/2bxzkoXHPjCpaF3ODR00PNvsETUlR4hTJZGH71BTg9J63
NI8KJr2XXPR5OkowGcytT6CYirQxlyric21+eLj4iIlPsSKRZEv1UN4D2+XFducTZnV+ZfsBn5OH
iJ35Rld8TWCvmHMTI6QgkYH60GFmuH3Rr9ZvHmw96RH9qfmCIoaZM3Fa6hlXPZHNqcCjbgcTpsnt
+GijnsNacgmHKNHEc8RzGF9QdRYxn7fofMM=
-----END CERTIFICATE-----

A-Trust-nQual-03
================
-----BEGIN CERTIFICATE-----
MIIDzzCCAregAwIBAgIDAWweMA0GCSqGSIb3DQEBBQUAMIGNMQswCQYDVQQGEwJBVDFIMEYGA1UE
Cgw/QS1UcnVzdCBHZXMuIGYuIFNpY2hlcmhlaXRzc3lzdGVtZSBpbSBlbGVrdHIuIERhdGVudmVy
a2VociBHbWJIMRkwFwYDVQQLDBBBLVRydXN0LW5RdWFsLTAzMRkwFwYDVQQDDBBBLVRydXN0LW5R
dWFsLTAzMB4XDTA1MDgxNzIyMDAwMFoXDTE1MDgxNzIyMDAwMFowgY0xCzAJBgNVBAYTAkFUMUgw
RgYDVQQKDD9BLVRydXN0IEdlcy4gZi4gU2ljaGVyaGVpdHNzeXN0ZW1lIGltIGVsZWt0ci4gRGF0
ZW52ZXJrZWhyIEdtYkgxGTAXBgNVBAsMEEEtVHJ1c3QtblF1YWwtMDMxGTAXBgNVBAMMEEEtVHJ1
c3QtblF1YWwtMDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtPWFuA/OQO8BBC4SA
zewqo51ru27CQoT3URThoKgtUaNR8t4j8DRE/5TrzAUjlUC5B3ilJfYKvUWG6Nm9wASOhURh73+n
yfrBJcyFLGM/BWBzSQXgYHiVEEvc+RFZznF/QJuKqiTfC0Li21a8StKlDJu3Qz7dg9MmEALP6iPE
SU7l0+m0iKsMrmKS1GWH2WrX9IWf5DMiJaXlyDO6w8dB3F/GaswADm0yqLaHNgBid5seHzTLkDx4
iHQF63n1k3Flyp3HaxgtPVxO59X4PzF9j4fsCiIvI+n+u33J4PTs63zEsMMtYrWacdaxaujs2e3V
cuy+VwHOBVWf3tFgiBCzAgMBAAGjNjA0MA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0OBAoECERqlWdV
eRFPMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAVdRU0VlIXLOThaq/Yy/kgM40
ozRiPvbY7meIMQQDbwvUB/tOdQ/TLtPAF8fGKOwGDREkDg6lXb+MshOWcdzUzg4NCmgybLlBMRmr
sQd7TZjTXLDR8KdCoLXEjq/+8T/0709GAHbrAvv5ndJAlseIOrifEXnzgGWovR/TeIGgUUw3tKZd
JXDRZslo+S4RFGjxVJgIrCaSD96JntT6s3kr0qN51OyLrIdTaEJMUVF0HhsnLuP1Hyl0Te2v9+GS
mYHovjrHF1D2t8b8m7CKa9aIA5GPBnc6hQLdmNVDeD/GMBWsm2vLV7eJUYs66MmEDNuxUCAKGkq6
ahq97BvIxYSazQ==
-----END CERTIFICATE-----

TWCA Root Certification Authority
=================================
-----BEGIN CERTIFICATE-----
MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ
VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh
dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG
EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB
IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx
QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC
oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP
4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r
y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB
BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG
9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC
mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW
QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY
T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny
Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==
-----END CERTIFICATE-----

Security Communication RootCA2
==============================
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc
U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh
dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC
SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy
aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++
+T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R
3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV
spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K
EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8
QIH4D5csOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB
CwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpFcoJxDjrSzG+ntKEj
u/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXcokgfGT+Ok+vx+hfuzU7jBBJV1uXk
3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6q
tnRGEmyR7jTV7JqR50S+kDFy1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29
mvVXIwAHIRc/SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
-----END CERTIFICATE-----

EC-ACC
======
-----BEGIN CERTIFICATE-----
MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB8zELMAkGA1UE
BhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2VydGlmaWNhY2lvIChOSUYgUS0w
ODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYD
VQQLEyxWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UE
CxMsSmVyYXJxdWlhIEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMT
BkVDLUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQGEwJFUzE7
MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8gKE5JRiBRLTA4MDExNzYt
SSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBDZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZl
Z2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQubmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJh
cnF1aWEgRW50aXRhdHMgZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUND
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R85iK
w5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm4CgPukLjbo73FCeT
ae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaVHMf5NLWUhdWZXqBIoH7nF2W4onW4
HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNdQlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0a
E9jD2z3Il3rucO2n5nzbcc8tlGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw
0JDnJwIDAQABo4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E
BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4opvpXY0wfwYD
VR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBodHRwczovL3d3dy5jYXRjZXJ0
Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5l
dC92ZXJhcnJlbCAwDQYJKoZIhvcNAQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJ
lF7W2u++AVtd0x7Y/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNa
Al6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe
l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2
E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D
5EI=
-----END CERTIFICATE-----

Hellenic Academic and Research Institutions RootCA 2011
=======================================================
-----BEGIN CERTIFICATE-----
MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNVBAoT
O0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9y
aXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z
IFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYT
AkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z
IENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNo
IEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPzdYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI
1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa
71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u
8yBRQlqD75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSPFEDH
3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNVHRMBAf8EBTADAQH/
MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp5dgTBCPuQSUwRwYDVR0eBEAwPqA8
MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQub3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQu
b3JnMA0GCSqGSIb3DQEBBQUAA4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVt
XdMiKahsog2p6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8
TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7dIsXRSZMFpGD
/md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8AcysNnq/onN694/BtZqhFLKPM58N
7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXIl7WdmplNsDz4SgCbZN2fOUvRJ9e4
-----END CERTIFICATE-----

Actalis Authentication Root CA
==============================
-----BEGIN CERTIFICATE-----
MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQxDjAM
BgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UE
AwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDky
MjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlz
IFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290
IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNvUTufClrJ
wkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX4ay8IMKx4INRimlNAJZa
by/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9KK3giq0itFZljoZUj5NDKd45RnijMCO6
zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1f
YVEiVRvjRuPjPdA1YprbrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2
oxgkg4YQ51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2Fbe8l
EfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxeKF+w6D9Fz8+vm2/7
hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4Fv6MGn8i1zeQf1xcGDXqVdFUNaBr8
EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbnfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5
jF66CyCU3nuDuP/jVo23Eek7jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLY
iDrIn3hm7YnzezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt
ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQALe3KHwGCmSUyI
WOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70jsNjLiNmsGe+b7bAEzlgqqI0
JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDzWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKx
K3JCaKygvU5a2hi/a5iB0P2avl4VSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+
Xlff1ANATIGk0k9jpwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC
4yyXX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+OkfcvHlXHo
2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7RK4X9p2jIugErsWx0Hbhz
lefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btUZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXem
OR/qnuOf0GZvBeyqdn6/axag67XH/JJULysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9
vwGYT7JZVEc+NHt4bVaTLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg==
-----END CERTIFICATE-----

Trustis FPS Root CA
===================
-----BEGIN CERTIFICATE-----
MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQG
EwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQLExNUcnVzdGlzIEZQUyBSb290
IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTExMzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNV
BAoTD1RydXN0aXMgTGltaXRlZDEcMBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJ
KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQ
RUN+AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihHiTHcDnlk
H5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjjvSkCqPoc4Vu5g6hBSLwa
cY3nYuUtsuvffM/bq1rKMfFMIvMFE/eC+XN5DL7XSxzA0RU8k0Fk0ea+IxciAIleH2ulrG6nS4zt
o3Lmr2NNL4XSFDWaLk6M6jKYKIahkQlBOrTh4/L68MkKokHdqeMDx4gVOxzUGpTXn2RZEm0CAwEA
AaNTMFEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS6+nEleYtXQSUhhgtx67JkDoshZzAd
BgNVHQ4EFgQUuvpxJXmLV0ElIYYLceuyZA6LIWcwDQYJKoZIhvcNAQEFBQADggEBAH5Y//01GX2c
GE+esCu8jowU/yyg2kdbw++BLa8F6nRIW/M+TgfHbcWzk88iNVy2P3UnXwmWzaD+vkAMXBJV+JOC
yinpXj9WV4s4NvdFGkwozZ5BuO1WTISkQMi4sKUraXAEasP41BIy+Q7DsdwyhEQsb8tGD+pmQQ9P
8Vilpg0ND2HepZ5dfWWhPBfnqFVO76DH7cZEf1T1o+CP8HxVIo8ptoGj4W1OLBuAZ+ytIJ8MYmHV
l/9D7S3B2l0pKoU/rGXuhg8FjZBf3+6f9L/uHfuY5H+QK4R4EA5sSVPvFVtlRkpdr7r7OnIdzfYl
iB6XzCGcKQENZetX2fNXlrtIzYE=
-----END CERTIFICATE-----

StartCom Certification Authority
================================
-----BEGIN CERTIFICATE-----
MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN
U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu
ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0
NjM3WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk
LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg
U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y
o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/
Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d
eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt
2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z
6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ
osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/
untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc
UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT
37uMdBNSSwIDAQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD
VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFulF2mHMMo0aEPQ
Qa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCCATgwLgYIKwYBBQUHAgEWImh0
dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cu
c3RhcnRzc2wuY29tL2ludGVybWVkaWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENv
bW1lcmNpYWwgKFN0YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0
aGUgc2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0aWZpY2F0
aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93d3cuc3RhcnRzc2wuY29t
L3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBG
cmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5
fPGFf59Jb2vKXfuM/gTFwWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWm
N3PH/UvSTa0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst0OcN
Org+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNcpRJvkrKTlMeIFw6T
tn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKlCcWw0bdT82AUuoVpaiF8H3VhFyAX
e2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVFP0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA
2MFrLH9ZXF2RsXAiV+uKa0hK1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBs
HvUwyKMQ5bLmKhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE
JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ8dCAWZvLMdib
D4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnmfyWl8kgAwKQB2j8=
-----END CERTIFICATE-----

StartCom Certification Authority G2
===================================
-----BEGIN CERTIFICATE-----
MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMN
U3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg
RzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UE
ChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3Jp
dHkgRzIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8O
o1XJJZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsDvfOpL9HG
4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnooD/Uefyf3lLE3PbfHkffi
Aez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/Q0kGi4xDuFby2X8hQxfqp0iVAXV16iul
Q5XqFYSdCI0mblWbq9zSOdIxHWDirMxWRST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbs
O+wmETRIjfaAKxojAuuKHDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8H
vKTlXcxNnw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM0D4L
nMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/iUUjXuG+v+E5+M5iS
FGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9Ha90OrInwMEePnWjFqmveiJdnxMa
z6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHgTuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8E
BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJ
KoZIhvcNAQELBQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K
2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfXUfEpY9Z1zRbk
J4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl6/2o1PXWT6RbdejF0mCy2wl+
JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG
/+gyRr61M3Z3qAFdlsHB1b6uJcDJHgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTc
nIhT76IxW1hPkWLIwpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/Xld
blhYXzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5lIxKVCCIc
l85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoohdVddLHRDiBYmxOlsGOm
7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulrso8uBtjRkcfGEvRM/TAXw8HaOFvjqerm
obp573PYtlNXLfbQ4ddI
-----END CERTIFICATE-----

Buypass Class 2 Root CA
=======================
-----BEGIN CERTIFICATE-----
MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMiBSb290IENBMB4X
DTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1owTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1
eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIw
DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1
g1Lr6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPVL4O2fuPn
9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC911K2GScuVr1QGbNgGE41b
/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHxMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqU
CqTqc/sLUegTBxj6DvEr0VQVfTzh97QZQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeff
awrbD02TTqigzXsu8lkBarcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgI
zRFo1clrUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLiFRhn
Bkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRSP/TizPJhk9H9Z2vX
Uq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN9SG9dKpN6nIDSdvHXx1iY8f93ZHs
M+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxPAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD
VR0OBBYEFMmAd+BikoL1RpzzuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF
AAOCAgEAU18h9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s
A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3tOluwlN5E40EI
osHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo+fsicdl9sz1Gv7SEr5AcD48S
aq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYd
DnkM/crqJIByw5c/8nerQyIKx+u2DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWD
LfJ6v9r9jv6ly0UsH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0
oyLQI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK75t98biGC
wWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h3PFaTWwyI0PurKju7koS
CTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPzY11aWOIv4x3kqdbQCtCev9eBCfHJxyYN
rJgWVqA=
-----END CERTIFICATE-----

Buypass Class 3 Root CA
=======================
-----BEGIN CERTIFICATE-----
MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMyBSb290IENBMB4X
DTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFowTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1
eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIw
DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRH
sJ8YZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3EN3coTRiR
5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9tznDDgFHmV0ST9tD+leh
7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX0DJq1l1sDPGzbjniazEuOQAnFN44wOwZ
ZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH
2xc519woe2v1n/MuwU8XKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV
/afmiSTYzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvSO1UQ
RwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D34xFMFbG02SrZvPA
Xpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgPK9Dx2hzLabjKSWJtyNBjYt1gD1iq
j6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD
VR0OBBYEFEe4zf/lb+74suwvTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF
AAOCAgEAACAjQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV
cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXSIGrs/CIBKM+G
uIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2HJLw5QY33KbmkJs4j1xrG0aG
Q0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsaO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8
ZORK15FTAaggiG6cX0S5y2CBNOxv033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2
KSb12tjE8nVhz36udmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz
6MkEkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg413OEMXbug
UZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvDu79leNKGef9JOxqDDPDe
eOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq4/g7u9xN12TyUb7mqqta6THuBrxzvxNi
Cp/HuZc=
-----END CERTIFICATE-----

T-TeleSec GlobalRoot Class 3
============================
-----BEGIN CERTIFICATE-----
MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM
IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU
cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgx
MDAxMTAyOTU2WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz
dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD
ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN8ELg63iIVl6bmlQdTQyK
9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/RLyTPWGrTs0NvvAgJ1gORH8EGoel15YU
NpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZF
iP0Zf3WHHx+xGwpzJFu5ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W
0eDrXltMEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGjQjBA
MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1A/d2O2GCahKqGFPr
AyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOyWL6ukK2YJ5f+AbGwUgC4TeQbIXQb
fsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzT
ucpH9sry9uetuUg/vBa3wW306gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7h
P0HHRwA11fXT91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml
e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4pTpPDpFQUWw==
-----END CERTIFICATE-----

EE Certification Centre Root CA
===============================
-----BEGIN CERTIFICATE-----
MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG
EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEoMCYGA1UEAwwfRUUgQ2Vy
dGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIw
MTAxMDMwMTAxMDMwWhgPMjAzMDEyMTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlB
UyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRy
ZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUyeuuOF0+W2Ap7kaJjbMeM
TC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvObntl8jixwKIy72KyaOBhU8E2lf/slLo2
rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw
93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtN
P2MbRMNE1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0T
AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZ
MEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEF
BQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+Rj
xY6hUFaTlrg4wCQiZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqM
lIpPnTX/dqQGE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u
uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU
3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM
dcGWxZ0=
-----END CERTIFICATE-----

TURKTRUST Certificate Services Provider Root 2007
=================================================
-----BEGIN CERTIFICATE-----
MIIEPTCCAyWgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvzE/MD0GA1UEAww2VMOcUktUUlVTVCBF
bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP
MA0GA1UEBwwGQW5rYXJhMV4wXAYDVQQKDFVUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg
QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgQXJhbMSxayAyMDA3MB4X
DTA3MTIyNTE4MzcxOVoXDTE3MTIyMjE4MzcxOVowgb8xPzA9BgNVBAMMNlTDnFJLVFJVU1QgRWxl
a3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTELMAkGA1UEBhMCVFIxDzAN
BgNVBAcMBkFua2FyYTFeMFwGA1UECgxVVMOcUktUUlVTVCBCaWxnaSDEsGxldGnFn2ltIHZlIEJp
bGnFn2ltIEfDvHZlbmxpxJ9pIEhpem1ldGxlcmkgQS7Fni4gKGMpIEFyYWzEsWsgMjAwNzCCASIw
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKu3PgqMyKVYFeaK7yc9SrToJdPNM8Ig3BnuiD9N
YvDdE3ePYakqtdTyuTFYKTsvP2qcb3N2Je40IIDu6rfwxArNK4aUyeNgsURSsloptJGXg9i3phQv
KUmi8wUG+7RP2qFsmmaf8EMJyupyj+sA1zU511YXRxcw9L6/P8JorzZAwan0qafoEGsIiveGHtya
KhUG9qPw9ODHFNRRf8+0222vR5YXm3dx2KdxnSQM9pQ/hTEST7ruToK4uT6PIzdezKKqdfcYbwnT
rqdUKDT74eA7YH2gvnmJhsifLfkKS8RQouf9eRbHegsYz85M733WB2+Y8a+xwXrXgTW4qhe04MsC
AwEAAaNCMEAwHQYDVR0OBBYEFCnFkKslrxHkYb+j/4hhkeYO/pyBMA4GA1UdDwEB/wQEAwIBBjAP
BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAQDdr4Ouwo0RSVgrESLFF6QSU2TJ/s
Px+EnWVUXKgWAkD6bho3hO9ynYYKVZ1WKKxmLNA6VpM0ByWtCLCPyA8JWcqdmBzlVPi5RX9ql2+I
aE1KBiY3iAIOtsbWcpnOa3faYjGkVh+uX4132l32iPwa2Z61gfAyuOOI0JzzaqC5mxRZNTZPz/OO
Xl0XrRWV2N2y1RVuAE6zS89mlOTgzbUF2mNXi+WzqtvALhyQRNsaXRik7r4EW5nVcV9VZWRi1aKb
BFmGyGJ353yCRWo9F7/snXUMrqNvWtMvmDb08PUZqxFdyKbjKlhqQgnDvZImZjINXQhVdP+MmNAK
poRq0Tl9
-----END CERTIFICATE-----

D-TRUST Root Class 3 CA 2 2009
==============================
-----BEGIN CERTIFICATE-----
MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQK
DAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTAe
Fw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NThaME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxE
LVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIw
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOAD
ER03UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42tSHKXzlA
BF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9RySPocq60vFYJfxLLHLGv
KZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsMlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7z
p+hnUquVH+BGPtikw8paxTGA6Eian5Rp/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUC
AwEAAaOCARowggEWMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ
4PGEMA4GA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVjdG9y
eS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUyMENBJTIwMiUyMDIw
MDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRlcmV2b2NhdGlvbmxpc3QwQ6BBoD+G
PWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAw
OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm
2H6NMLVwMeniacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0
o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4KzCUqNQT4YJEV
dT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8PIWmawomDeCTmGCufsYkl4ph
X5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3YJohw1+qRzT65ysCQblrGXnRl11z+o+I=
-----END CERTIFICATE-----

D-TRUST Root Class 3 CA 2 EV 2009
=================================
-----BEGIN CERTIFICATE-----
MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK
DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw
OTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUwNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK
DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw
OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfS
egpnljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM03TP1YtHh
zRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6ZqQTMFexgaDbtCHu39b+T
7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lRp75mpoo6Kr3HGrHhFPC+Oh25z1uxav60
sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure35
11H3a6UCAwEAAaOCASQwggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyv
cop9NteaHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFwOi8v
ZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xhc3MlMjAzJTIwQ0El
MjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1ERT9jZXJ0aWZpY2F0ZXJldm9jYXRp
b25saXN0MEagRKBChkBodHRwOi8vd3d3LmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xh
c3NfM19jYV8yX2V2XzIwMDkuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+
PPoeUSbrh/Yp3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05
nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNFCSuGdXzfX2lX
ANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7naxpeG0ILD5EJt/rDiZE4OJudA
NCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqXKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVv
w9y4AyHqnxbxLFS1
-----END CERTIFICATE-----

PSCProcert
==========
-----BEGIN CERTIFICATE-----
MIIJhjCCB26gAwIBAgIBCzANBgkqhkiG9w0BAQsFADCCAR4xPjA8BgNVBAMTNUF1dG9yaWRhZCBk
ZSBDZXJ0aWZpY2FjaW9uIFJhaXogZGVsIEVzdGFkbyBWZW5lem9sYW5vMQswCQYDVQQGEwJWRTEQ
MA4GA1UEBxMHQ2FyYWNhczEZMBcGA1UECBMQRGlzdHJpdG8gQ2FwaXRhbDE2MDQGA1UEChMtU2lz
dGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMUMwQQYDVQQLEzpTdXBl
cmludGVuZGVuY2lhIGRlIFNlcnZpY2lvcyBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMSUw
IwYJKoZIhvcNAQkBFhZhY3JhaXpAc3VzY2VydGUuZ29iLnZlMB4XDTEwMTIyODE2NTEwMFoXDTIw
MTIyNTIzNTk1OVowgdExJjAkBgkqhkiG9w0BCQEWF2NvbnRhY3RvQHByb2NlcnQubmV0LnZlMQ8w
DQYDVQQHEwZDaGFjYW8xEDAOBgNVBAgTB01pcmFuZGExKjAoBgNVBAsTIVByb3ZlZWRvciBkZSBD
ZXJ0aWZpY2Fkb3MgUFJPQ0VSVDE2MDQGA1UEChMtU2lzdGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZp
Y2FjaW9uIEVsZWN0cm9uaWNhMQswCQYDVQQGEwJWRTETMBEGA1UEAxMKUFNDUHJvY2VydDCCAiIw
DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANW39KOUM6FGqVVhSQ2oh3NekS1wwQYalNo97BVC
wfWMrmoX8Yqt/ICV6oNEolt6Vc5Pp6XVurgfoCfAUFM+jbnADrgV3NZs+J74BCXfgI8Qhd19L3uA
3VcAZCP4bsm+lU/hdezgfl6VzbHvvnpC2Mks0+saGiKLt38GieU89RLAu9MLmV+QfI4tL3czkkoh
RqipCKzx9hEC2ZUWno0vluYC3XXCFCpa1sl9JcLB/KpnheLsvtF8PPqv1W7/U0HU9TI4seJfxPmO
EO8GqQKJ/+MMbpfg353bIdD0PghpbNjU5Db4g7ayNo+c7zo3Fn2/omnXO1ty0K+qP1xmk6wKImG2
0qCZyFSTXai20b1dCl53lKItwIKOvMoDKjSuc/HUtQy9vmebVOvh+qBa7Dh+PsHMosdEMXXqP+UH
0quhJZb25uSgXTcYOWEAM11G1ADEtMo88aKjPvM6/2kwLkDd9p+cJsmWN63nOaK/6mnbVSKVUyqU
td+tFjiBdWbjxywbk5yqjKPK2Ww8F22c3HxT4CAnQzb5EuE8XL1mv6JpIzi4mWCZDlZTOpx+FIyw
Bm/xhnaQr/2v/pDGj59/i5IjnOcVdo/Vi5QTcmn7K2FjiO/mpF7moxdqWEfLcU8UC17IAggmosvp
r2uKGcfLFFb14dq12fy/czja+eevbqQ34gcnAgMBAAGjggMXMIIDEzASBgNVHRMBAf8ECDAGAQH/
AgEBMDcGA1UdEgQwMC6CD3N1c2NlcnRlLmdvYi52ZaAbBgVghl4CAqASDBBSSUYtRy0yMDAwNDAz
Ni0wMB0GA1UdDgQWBBRBDxk4qpl/Qguk1yeYVKIXTC1RVDCCAVAGA1UdIwSCAUcwggFDgBStuyId
xuDSAaj9dlBSk+2YwU2u06GCASakggEiMIIBHjE+MDwGA1UEAxM1QXV0b3JpZGFkIGRlIENlcnRp
ZmljYWNpb24gUmFpeiBkZWwgRXN0YWRvIFZlbmV6b2xhbm8xCzAJBgNVBAYTAlZFMRAwDgYDVQQH
EwdDYXJhY2FzMRkwFwYDVQQIExBEaXN0cml0byBDYXBpdGFsMTYwNAYDVQQKEy1TaXN0ZW1hIE5h
Y2lvbmFsIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExQzBBBgNVBAsTOlN1cGVyaW50ZW5k
ZW5jaWEgZGUgU2VydmljaW9zIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExJTAjBgkqhkiG
9w0BCQEWFmFjcmFpekBzdXNjZXJ0ZS5nb2IudmWCAQowDgYDVR0PAQH/BAQDAgEGME0GA1UdEQRG
MESCDnByb2NlcnQubmV0LnZloBUGBWCGXgIBoAwMClBTQy0wMDAwMDKgGwYFYIZeAgKgEgwQUklG
LUotMzE2MzUzNzMtNzB2BgNVHR8EbzBtMEagRKBChkBodHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52
ZS9sY3IvQ0VSVElGSUNBRE8tUkFJWi1TSEEzODRDUkxERVIuY3JsMCOgIaAfhh1sZGFwOi8vYWNy
YWl6LnN1c2NlcnRlLmdvYi52ZTA3BggrBgEFBQcBAQQrMCkwJwYIKwYBBQUHMAGGG2h0dHA6Ly9v
Y3NwLnN1c2NlcnRlLmdvYi52ZTBBBgNVHSAEOjA4MDYGBmCGXgMBAjAsMCoGCCsGAQUFBwIBFh5o
dHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52ZS9kcGMwDQYJKoZIhvcNAQELBQADggIBACtZ6yKZu4Sq
T96QxtGGcSOeSwORR3C7wJJg7ODU523G0+1ng3dS1fLld6c2suNUvtm7CpsR72H0xpkzmfWvADmN
g7+mvTV+LFwxNG9s2/NkAZiqlCxB3RWGymspThbASfzXg0gTB1GEMVKIu4YXx2sviiCtxQuPcD4q
uxtxj7mkoP3YldmvWb8lK5jpY5MvYB7Eqvh39YtsL+1+LrVPQA3uvFd359m21D+VJzog1eWuq2w1
n8GhHVnchIHuTQfiSLaeS5UtQbHh6N5+LwUeaO6/u5BlOsju6rEYNxxik6SgMexxbJHmpHmJWhSn
FFAFTKQAVzAswbVhltw+HoSvOULP5dAssSS830DD7X9jSr3hTxJkhpXzsOfIt+FTvZLm8wyWuevo
5pLtp4EJFAv8lXrPj9Y0TzYS3F7RNHXGRoAvlQSMx4bEqCaJqD8Zm4G7UaRKhqsLEQ+xrmNTbSjq
3TNWOByyrYDT13K9mmyZY+gAu0F2BbdbmRiKw7gSXFbPVgx96OLP7bx0R/vu0xdOIk9W/1DzLuY5
poLWccret9W6aAjtmcz9opLLabid+Qqkpj5PkygqYWwHJgD/ll9ohri4zspV4KuxPX+Y1zMOWj3Y
eMLEYC/HYvBhkdI4sPaeVdtAgAUSM84dkpvRabP/v/GSCmE1P93+hvS84Bpxs2Km
-----END CERTIFICATE-----

China Internet Network Information Center EV Certificates Root
==============================================================
-----BEGIN CERTIFICATE-----
MIID9zCCAt+gAwIBAgIESJ8AATANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCQ04xMjAwBgNV
BAoMKUNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyMUcwRQYDVQQDDD5D
aGluYSBJbnRlcm5ldCBOZXR3b3JrIEluZm9ybWF0aW9uIENlbnRlciBFViBDZXJ0aWZpY2F0ZXMg
Um9vdDAeFw0xMDA4MzEwNzExMjVaFw0zMDA4MzEwNzExMjVaMIGKMQswCQYDVQQGEwJDTjEyMDAG
A1UECgwpQ2hpbmEgSW50ZXJuZXQgTmV0d29yayBJbmZvcm1hdGlvbiBDZW50ZXIxRzBFBgNVBAMM
PkNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyIEVWIENlcnRpZmljYXRl
cyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm35z7r07eKpkQ0H1UN+U8i6y
jUqORlTSIRLIOTJCBumD1Z9S7eVnAztUwYyZmczpwA//DdmEEbK40ctb3B75aDFk4Zv6dOtouSCV
98YPjUesWgbdYavi7NifFy2cyjw1l1VxzUOFsUcW9SxTgHbP0wBkvUCZ3czY28Sf1hNfQYOL+Q2H
klY0bBoQCxfVWhyXWIQ8hBouXJE0bhlffxdpxWXvayHG1VA6v2G5BY3vbzQ6sm8UY78WO5upKv23
KzhmBsUs4qpnHkWnjQRmQvaPK++IIGmPMowUc9orhpFjIpryp9vOiYurXccUwVswah+xt54ugQEC
7c+WXmPbqOY4twIDAQABo2MwYTAfBgNVHSMEGDAWgBR8cks5x8DbYqVPm6oYNJKiyoOCWTAPBgNV
HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUfHJLOcfA22KlT5uqGDSSosqD
glkwDQYJKoZIhvcNAQEFBQADggEBACrDx0M3j92tpLIM7twUbY8opJhJywyA6vPtI2Z1fcXTIWd5
0XPFtQO3WKwMVC/GVhMPMdoG52U7HW8228gd+f2ABsqjPWYWqJ1MFn3AlUa1UeTiH9fqBk1jjZaM
7+czV0I664zBechNdn3e9rG3geCg+aF4RhcaVpjwTj2rHO3sOdwHSPdj/gauwqRcalsyiMXHM4Ws
ZkJHwlgkmeHlPuV1LI5D1l08eB6olYIpUNHRFrrvwb562bTYzB5MRuF3sTGrvSrIzo9uoV1/A3U0
5K2JRVRevq4opbs/eHnrc7MKDf2+yfdWrPa37S+bISnHOLaVxATywy39FCqQmbkHzJ8=
-----END CERTIFICATE-----

Swisscom Root CA 2
==================
-----BEGIN CERTIFICATE-----
MIIF2TCCA8GgAwIBAgIQHp4o6Ejy5e/DfEoeWhhntjANBgkqhkiG9w0BAQsFADBkMQswCQYDVQQG
EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy
dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMjAeFw0xMTA2MjQwODM4MTRaFw0zMTA2
MjUwNzM4MTRaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln
aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAyMIIC
IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlUJOhJ1R5tMJ6HJaI2nbeHCOFvErjw0DzpPM
LgAIe6szjPTpQOYXTKueuEcUMncy3SgM3hhLX3af+Dk7/E6J2HzFZ++r0rk0X2s682Q2zsKwzxNo
ysjL67XiPS4h3+os1OD5cJZM/2pYmLcX5BtS5X4HAB1f2uY+lQS3aYg5oUFgJWFLlTloYhyxCwWJ
wDaCFCE/rtuh/bxvHGCGtlOUSbkrRsVPACu/obvLP+DHVxxX6NZp+MEkUp2IVd3Chy50I9AU/SpH
Wrumnf2U5NGKpV+GY3aFy6//SSj8gO1MedK75MDvAe5QQQg1I3ArqRa0jG6F6bYRzzHdUyYb3y1a
SgJA/MTAtukxGggo5WDDH8SQjhBiYEQN7Aq+VRhxLKX0srwVYv8c474d2h5Xszx+zYIdkeNL6yxS
NLCK/RJOlrDrcH+eOfdmQrGrrFLadkBXeyq96G4DsguAhYidDMfCd7Camlf0uPoTXGiTOmekl9Ab
mbeGMktg2M7v0Ax/lZ9vh0+Hio5fCHyqW/xavqGRn1V9TrALacywlKinh/LTSlDcX3KwFnUey7QY
Ypqwpzmqm59m2I2mbJYV4+by+PGDYmy7Velhk6M99bFXi08jsJvllGov34zflVEpYKELKeRcVVi3
qPyZ7iVNTA6z00yPhOgpD/0QVAKFyPnlw4vP5w8CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw
HQYDVR0hBBYwFDASBgdghXQBUwIBBgdghXQBUwIBMBIGA1UdEwEB/wQIMAYBAf8CAQcwHQYDVR0O
BBYEFE0mICKJS9PVpAqhb97iEoHF8TwuMB8GA1UdIwQYMBaAFE0mICKJS9PVpAqhb97iEoHF8Twu
MA0GCSqGSIb3DQEBCwUAA4ICAQAyCrKkG8t9voJXiblqf/P0wS4RfbgZPnm3qKhyN2abGu2sEzsO
v2LwnN+ee6FTSA5BesogpxcbtnjsQJHzQq0Qw1zv/2BZf82Fo4s9SBwlAjxnffUy6S8w5X2lejjQ
82YqZh6NM4OKb3xuqFp1mrjX2lhIREeoTPpMSQpKwhI3qEAMw8jh0FcNlzKVxzqfl9NX+Ave5XLz
o9v/tdhZsnPdTSpxsrpJ9csc1fV5yJmz/MFMdOO0vSk3FQQoHt5FRnDsr7p4DooqzgB53MBfGWcs
a0vvaGgLQ+OswWIJ76bdZWGgr4RVSJFSHMYlkSrQwSIjYVmvRRGFHQEkNI/Ps/8XciATwoCqISxx
OQ7Qj1zB09GOInJGTB2Wrk9xseEFKZZZ9LuedT3PDTcNYtsmjGOpI99nBjx8Oto0QuFmtEYE3saW
mA9LSHokMnWRn6z3aOkquVVlzl1h0ydw2Df+n7mvoC5Wt6NlUe07qxS/TFED6F+KBZvuim6c779o
+sjaC+NCydAXFJy3SuCvkychVSa1ZC+N8f+mQAWFBVzKBxlcCxMoTFh/wqXvRdpg065lYZ1Tg3TC
rvJcwhbtkj6EPnNgiLx29CzP0H1907he0ZESEOnN3col49XtmS++dYFLJPlFRpTJKSFTnCZFqhMX
5OfNeOI5wSsSnqaeG8XmDtkx2Q==
-----END CERTIFICATE-----

Swisscom Root EV CA 2
=====================
-----BEGIN CERTIFICATE-----
MIIF4DCCA8igAwIBAgIRAPL6ZOJ0Y9ON/RAdBB92ylgwDQYJKoZIhvcNAQELBQAwZzELMAkGA1UE
BhMCY2gxETAPBgNVBAoTCFN3aXNzY29tMSUwIwYDVQQLExxEaWdpdGFsIENlcnRpZmljYXRlIFNl
cnZpY2VzMR4wHAYDVQQDExVTd2lzc2NvbSBSb290IEVWIENBIDIwHhcNMTEwNjI0MDk0NTA4WhcN
MzEwNjI1MDg0NTA4WjBnMQswCQYDVQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsT
HERpZ2l0YWwgQ2VydGlmaWNhdGUgU2VydmljZXMxHjAcBgNVBAMTFVN3aXNzY29tIFJvb3QgRVYg
Q0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMT3HS9X6lds93BdY7BxUglgRCgz
o3pOCvrY6myLURYaVa5UJsTMRQdBTxB5f3HSek4/OE6zAMaVylvNwSqD1ycfMQ4jFrclyxy0uYAy
Xhqdk/HoPGAsp15XGVhRXrwsVgu42O+LgrQ8uMIkqBPHoCE2G3pXKSinLr9xJZDzRINpUKTk4Rti
GZQJo/PDvO/0vezbE53PnUgJUmfANykRHvvSEaeFGHR55E+FFOtSN+KxRdjMDUN/rhPSays/p8Li
qG12W0OfvrSdsyaGOx9/5fLoZigWJdBLlzin5M8J0TbDC77aO0RYjb7xnglrPvMyxyuHxuxenPaH
Za0zKcQvidm5y8kDnftslFGXEBuGCxobP/YCfnvUxVFkKJ3106yDgYjTdLRZncHrYTNaRdHLOdAG
alNgHa/2+2m8atwBz735j9m9W8E6X47aD0upm50qKGsaCnw8qyIL5XctcfaCNYGu+HuB5ur+rPQa
m3Rc6I8k9l2dRsQs0h4rIWqDJ2dVSqTjyDKXZpBy2uPUZC5f46Fq9mDU5zXNysRojddxyNMkM3Ox
bPlq4SjbX8Y96L5V5jcb7STZDxmPX2MYWFCBUWVv8p9+agTnNCRxunZLWB4ZvRVgRaoMEkABnRDi
xzgHcgplwLa7JSnaFp6LNYth7eVxV4O1PHGf40+/fh6Bn0GXAgMBAAGjgYYwgYMwDgYDVR0PAQH/
BAQDAgGGMB0GA1UdIQQWMBQwEgYHYIV0AVMCAgYHYIV0AVMCAjASBgNVHRMBAf8ECDAGAQH/AgED
MB0GA1UdDgQWBBRF2aWBbj2ITY1x0kbBbkUe88SAnTAfBgNVHSMEGDAWgBRF2aWBbj2ITY1x0kbB
bkUe88SAnTANBgkqhkiG9w0BAQsFAAOCAgEAlDpzBp9SSzBc1P6xXCX5145v9Ydkn+0UjrgEjihL
j6p7jjm02Vj2e6E1CqGdivdj5eu9OYLU43otb98TPLr+flaYC/NUn81ETm484T4VvwYmneTwkLbU
wp4wLh/vx3rEUMfqe9pQy3omywC0Wqu1kx+AiYQElY2NfwmTv9SoqORjbdlk5LgpWgi/UOGED1V7
XwgiG/W9mR4U9s70WBCCswo9GcG/W6uqmdjyMb3lOGbcWAXH7WMaLgqXfIeTK7KK4/HsGOV1timH
59yLGn602MnTihdsfSlEvoqq9X46Lmgxk7lq2prg2+kupYTNHAq4Sgj5nPFhJpiTt3tm7JFe3VE/
23MPrQRYCd0EApUKPtN236YQHoA96M2kZNEzx5LH4k5E4wnJTsJdhw4Snr8PyQUQ3nqjsTzyP6Wq
J3mtMX0f/fwZacXduT98zca0wjAefm6S139hdlqP65VNvBFuIXxZN5nQBrz5Bm0yFqXZaajh3DyA
HmBR3NdUIR7KYndP+tiPsys6DXhyyWhBWkdKwqPrGtcKqzwyVcgKEZzfdNbwQBUdyLmPtTbFr/gi
uMod89a2GQ+fYWVq6nTIfI/DT11lgh/ZDYnadXL77/FHZxOzyNEZiCcmmpl5fx7kLD977vHeTYuW
l8PVP3wbI+2ksx0WckNLIOFZfsLorSa/ovc=
-----END CERTIFICATE-----

CA Disig Root R1
================
-----BEGIN CERTIFICATE-----
MIIFaTCCA1GgAwIBAgIJAMMDmu5QkG4oMA0GCSqGSIb3DQEBBQUAMFIxCzAJBgNVBAYTAlNLMRMw
EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp
ZyBSb290IFIxMB4XDTEyMDcxOTA5MDY1NloXDTQyMDcxOTA5MDY1NlowUjELMAkGA1UEBhMCU0sx
EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp
c2lnIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCqw3j33Jijp1pedxiy
3QRkD2P9m5YJgNXoqqXinCaUOuiZc4yd39ffg/N4T0Dhf9Kn0uXKE5Pn7cZ3Xza1lK/oOI7bm+V8
u8yN63Vz4STN5qctGS7Y1oprFOsIYgrY3LMATcMjfF9DCCMyEtztDK3AfQ+lekLZWnDZv6fXARz2
m6uOt0qGeKAeVjGu74IKgEH3G8muqzIm1Cxr7X1r5OJeIgpFy4QxTaz+29FHuvlglzmxZcfe+5nk
CiKxLU3lSCZpq+Kq8/v8kiky6bM+TR8noc2OuRf7JT7JbvN32g0S9l3HuzYQ1VTW8+DiR0jm3hTa
YVKvJrT1cU/J19IG32PK/yHoWQbgCNWEFVP3Q+V8xaCJmGtzxmjOZd69fwX3se72V6FglcXM6pM6
vpmumwKjrckWtc7dXpl4fho5frLABaTAgqWjR56M6ly2vGfb5ipN0gTco65F97yLnByn1tUD3AjL
LhbKXEAz6GfDLuemROoRRRw1ZS0eRWEkG4IupZ0zXWX4Qfkuy5Q/H6MMMSRE7cderVC6xkGbrPAX
ZcD4XW9boAo0PO7X6oifmPmvTiT6l7Jkdtqr9O3jw2Dv1fkCyC2fg69naQanMVXVz0tv/wQFx1is
XxYb5dKj6zHbHzMVTdDypVP1y+E9Tmgt2BLdqvLmTZtJ5cUoobqwWsagtQIDAQABo0IwQDAPBgNV
HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUiQq0OJMa5qvum5EY+fU8PjXQ
04IwDQYJKoZIhvcNAQEFBQADggIBADKL9p1Kyb4U5YysOMo6CdQbzoaz3evUuii+Eq5FLAR0rBNR
xVgYZk2C2tXck8An4b58n1KeElb21Zyp9HWc+jcSjxyT7Ff+Bw+r1RL3D65hXlaASfX8MPWbTx9B
LxyE04nH4toCdu0Jz2zBuByDHBb6lM19oMgY0sidbvW9adRtPTXoHqJPYNcHKfyyo6SdbhWSVhlM
CrDpfNIZTUJG7L399ldb3Zh+pE3McgODWF3vkzpBemOqfDqo9ayk0d2iLbYq/J8BjuIQscTK5Gfb
VSUZP/3oNn6z4eGBrxEWi1CXYBmCAMBrTXO40RMHPuq2MU/wQppt4hF05ZSsjYSVPCGvxdpHyN85
YmLLW1AL14FABZyb7bq2ix4Eb5YgOe2kfSnbSM6C3NQCjR0EMVrHS/BsYVLXtFHCgWzN4funodKS
ds+xDzdYpPJScWc/DIh4gInByLUfkmO+p3qKViwaqKactV2zY9ATIKHrkWzQjX2v3wvkF7mGnjix
lAxYjOBVqjtjbZqJYLhkKpLGN/R+Q0O3c+gB53+XD9fyexn9GtePyfqFa3qdnom2piiZk4hA9z7N
UaPK6u95RyG1/jLix8NRb76AdPCkwzryT+lf3xkK8jsTQ6wxpLPn6/wY1gGp8yqPNg7rtLG8t0zJ
a7+h89n07eLw4+1knj0vllJPgFOL
-----END CERTIFICATE-----

CA Disig Root R2
================
-----BEGIN CERTIFICATE-----
MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNVBAYTAlNLMRMw
EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp
ZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQyMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sx
EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp
c2lnIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbC
w3OeNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNHPWSb6Wia
xswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3Ix2ymrdMxp7zo5eFm1tL7
A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbeQTg06ov80egEFGEtQX6sx3dOy1FU+16S
GBsEWmjGycT6txOgmLcRK7fWV8x8nhfRyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqV
g8NTEQxzHQuyRpDRQjrOQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa
5Beny912H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJQfYE
koopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUDi/ZnWejBBhG93c+A
Ak9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORsnLMOPReisjQS1n6yqEm70XooQL6i
Fh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNV
HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5u
Qu0wDQYJKoZIhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM
tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqfGopTpti72TVV
sRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkblvdhuDvEK7Z4bLQjb/D907Je
dR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W8
1k/BfDxujRNt+3vrMNDcTa/F1balTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjx
mHHEt38OFdAlab0inSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01
utI3gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18DrG5gPcFw0
sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3OszMOl6W8KjptlwlCFtaOg
UxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8xL4ysEr3vQCj8KWefshNPZiTEUxnpHikV
7+ZtsH8tZ/3zbBt1RqPlShfppNcL
-----END CERTIFICATE-----

ACCVRAIZ1
=========
-----BEGIN CERTIFICATE-----
MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJB
SVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1
MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwH
UEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4IC
DwAwggIKAoICAQCbqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gM
jmoYHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWoG2ioPej0
RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpAlHPrzg5XPAOBOp0KoVdD
aaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhrIA8wKFSVf+DuzgpmndFALW4ir50awQUZ
0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDG
WuzndN9wrqODJerWx5eHk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs7
8yM2x/474KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMOm3WR
5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpacXpkatcnYGMN285J
9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPluUsXQA+xtrn13k/c4LOsOxFwYIRK
Q26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYIKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRw
Oi8vd3d3LmFjY3YuZXMvZmlsZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEu
Y3J0MB8GCCsGAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2
VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeTVfZW6oHlNsyM
Hj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIGCCsGAQUFBwICMIIBFB6CARAA
QQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUAcgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBh
AO0AegAgAGQAZQAgAGwAYQAgAEEAQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUA
YwBuAG8AbABvAGcA7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBj
AHQAcgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAAQwBQAFMA
IABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUAczAwBggrBgEFBQcCARYk
aHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2MuaHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0
dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRtaW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2
MV9kZXIuY3JsMA4GA1UdDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZI
hvcNAQEFBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdpD70E
R9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gUJyCpZET/LtZ1qmxN
YEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+mAM/EKXMRNt6GGT6d7hmKG9Ww7Y49
nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepDvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJ
TS+xJlsndQAJxGJ3KQhfnlmstn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3
sCPdK6jT2iWH7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h
I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szAh1xA2syVP1Xg
Nce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xFd3+YJ5oyXSrjhO7FmGYvliAd
3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2HpPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3p
EfbRD0tVNEYqi4Y7
-----END CERTIFICATE-----

TWCA Global Root CA
===================
-----BEGIN CERTIFICATE-----
MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcxEjAQBgNVBAoT
CVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMTVFdDQSBHbG9iYWwgUm9vdCBD
QTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQK
EwlUQUlXQU4tQ0ExEDAOBgNVBAsTB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3Qg
Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2C
nJfF10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz0ALfUPZV
r2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfChMBwqoJimFb3u/Rk28OKR
Q4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbHzIh1HrtsBv+baz4X7GGqcXzGHaL3SekV
tTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1W
KKD+u4ZqyPpcC1jcxkt2yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99
sy2sbZCilaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYPoA/p
yJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQABDzfuBSO6N+pjWxn
kjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcEqYSjMq+u7msXi7Kx/mzhkIyIqJdI
zshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMC
AQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6g
cFGn90xHNcgL1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn
LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WFH6vPNOw/KP4M
8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNoRI2T9GRwoD2dKAXDOXC4Ynsg
/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlg
lPx4mI88k1HtQJAH32RjJMtOcQWh15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryP
A9gK8kxkRr05YuWW6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3m
i4TWnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5jwa19hAM8
EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWzaGHQRiapIVJpLesux+t3
zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmyKwbQBM0=
-----END CERTIFICATE-----

TeliaSonera Root CA v1
======================
-----BEGIN CERTIFICATE-----
MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAwNzEUMBIGA1UE
CgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJvb3QgQ0EgdjEwHhcNMDcxMDE4
MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYDVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwW
VGVsaWFTb25lcmEgUm9vdCBDQSB2MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+
6yfwIaPzaSZVfp3FVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA
3GV17CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+XZ75Ljo1k
B1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+/jXh7VB7qTCNGdMJjmhn
Xb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxH
oLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkmdtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3
F0fUTPHSiXk+TT2YqGHeOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJ
oWjiUIMusDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4pgd7
gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fsslESl1MpWtTwEhDc
TwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQarMCpgKIv7NHfirZ1fpoeDVNAgMB
AAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qW
DNXr+nuqF+gTEjANBgkqhkiG9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNm
zqjMDfz1mgbldxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx
0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1TjTQpgcmLNkQfW
pb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBedY2gea+zDTYa4EzAvXUYNR0PV
G6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpc
c41teyWRyu5FrgZLAMzTsVlQ2jqIOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOT
JsjrDNYmiLbAJM+7vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2
qReWt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcnHL/EVlP6
Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVxSK236thZiNSQvxaz2ems
WWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY=
-----END CERTIFICATE-----

E-Tugra Certification Authority
===============================
-----BEGIN CERTIFICATE-----
MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNVBAYTAlRSMQ8w
DQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamls
ZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN
ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMw
NTEyMDk0OFoXDTIzMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmEx
QDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxl
cmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQD
DB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
MIICCgKCAgEA4vU/kwVRHoViVF56C/UYB4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vd
hQd2h8y/L5VMzH2nPbxHD5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5K
CKpbknSFQ9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEoq1+g
ElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3Dk14opz8n8Y4e0ypQ
BaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcHfC425lAcP9tDJMW/hkd5s3kc91r0
E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsutdEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gz
rt48Ue7LE3wBf4QOXVGUnhMMti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAq
jqFGOjGY5RH8zLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn
rFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUXU8u3Zg5mTPj5
dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6Jyr+zE7S6E5UMA8GA1UdEwEB
/wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5XPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEG
MA0GCSqGSIb3DQEBCwUAA4ICAQAFNzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAK
kEh47U6YA5n+KGCRHTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jO
XKqYGwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c77NCR807
VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3+GbHeJAAFS6LrVE1Uweo
a2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WKvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCc
dlqMQ1DujjByTd//SffGqWfZbawCEeI6FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEV
KV0jq9BgoRJP3vQXzTLlyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gT
Dx4JnW2PAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpDy4Q0
8ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8dNL/+I5c30jn6PQ0G
C7TbO6Orb1wdtn7os4I07QZcJA==
-----END CERTIFICATE-----

T-TeleSec GlobalRoot Class 2
============================
-----BEGIN CERTIFICATE-----
MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM
IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU
cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgx
MDAxMTA0MDE0WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz
dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD
ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUdAqSzm1nzHoqvNK38DcLZ
SBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiCFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/F
vudocP05l03Sx5iRUKrERLMjfTlH6VJi1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx970
2cu+fjOlbpSD8DT6IavqjnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGV
WOHAD3bZwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGjQjBA
MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/WSA2AHmgoCJrjNXy
YdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhyNsZt+U2e+iKo4YFWz827n+qrkRk4
r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPACuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNf
vNoBYimipidx5joifsFvHZVwIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR
3p1m0IvVVGb6g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN
9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlPBSeOE6Fuwg==
-----END CERTIFICATE-----

Atos TrustedRoot 2011
=====================
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UEAwwVQXRvcyBU
cnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0xMTA3MDcxNDU4
MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsG
A1UECgwEQXRvczELMAkGA1UEBhMCREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCV
hTuXbyo7LjvPpvMpNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr
54rMVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+SZFhyBH+
DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ4J7sVaE3IqKHBAUsR320
HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0Lcp2AMBYHlT8oDv3FdU9T1nSatCQujgKR
z3bFmx5VdJx4IbHwLfELn8LVlhgf8FQieowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7R
l+lwrrw7GWzbITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZ
bNshMBgGA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB
CwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8jvZfza1zv7v1Apt+h
k6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kPDpFrdRbhIfzYJsdHt6bPWHJxfrrh
TZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pcmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a9
61qn8FYiqTxlVMYVqL2Gns2Dlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G
3mB/ufNPRJLvKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed
-----END CERTIFICATE-----

<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Version;
use Guzzle\Common\ToArrayInterface;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Parser\ParserRegistry;

/**
 * Guzzle HTTP response object
 */
class Response extends AbstractMessage implements \Serializable
{
    /**
     * @var array Array of reason phrases and their corresponding status codes
     */
    private static $statusTexts = array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',
        208 => 'Already Reported',
        226 => 'IM Used',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        422 => 'Unprocessable Entity',
        423 => 'Locked',
        424 => 'Failed Dependency',
        425 => 'Reserved for WebDAV advanced collections expired proposal',
        426 => 'Upgrade required',
        428 => 'Precondition Required',
        429 => 'Too Many Requests',
        431 => 'Request Header Fields Too Large',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates (Experimental)',
        507 => 'Insufficient Storage',
        508 => 'Loop Detected',
        510 => 'Not Extended',
        511 => 'Network Authentication Required',
    );

    /** @var EntityBodyInterface The response body */
    protected $body;

    /** @var string The reason phrase of the response (human readable code) */
    protected $reasonPhrase;

    /** @var string The status code of the response */
    protected $statusCode;

    /** @var array Information about the request */
    protected $info = array();

    /** @var string The effective URL that returned this response */
    protected $effectiveUrl;

    /** @var array Cacheable response codes (see RFC 2616:13.4) */
    protected static $cacheResponseCodes = array(200, 203, 206, 300, 301, 410);

    /**
     * Create a new Response based on a raw response message
     *
     * @param string $message Response message
     *
     * @return self|bool Returns false on error
     */
    public static function fromMessage($message)
    {
        $data = ParserRegistry::getInstance()->getParser('message')->parseResponse($message);
        if (!$data) {
            return false;
        }

        $response = new static($data['code'], $data['headers'], $data['body']);
        $response->setProtocol($data['protocol'], $data['version'])
                 ->setStatus($data['code'], $data['reason_phrase']);

        // Set the appropriate Content-Length if the one set is inaccurate (e.g. setting to X)
        $contentLength = (string) $response->getHeader('Content-Length');
        $actualLength = strlen($data['body']);
        if (strlen($data['body']) > 0 && $contentLength != $actualLength) {
            $response->setHeader('Content-Length', $actualLength);
        }

        return $response;
    }

    /**
     * Construct the response
     *
     * @param string                              $statusCode The response status code (e.g. 200, 404, etc)
     * @param ToArrayInterface|array              $headers    The response headers
     * @param string|resource|EntityBodyInterface $body       The body of the response
     *
     * @throws BadResponseException if an invalid response code is given
     */
    public function __construct($statusCode, $headers = null, $body = null)
    {
        parent::__construct();
        $this->setStatus($statusCode);
        $this->body = EntityBody::factory($body !== null ? $body : '');

        if ($headers) {
            if (is_array($headers)) {
                $this->setHeaders($headers);
            } elseif ($headers instanceof ToArrayInterface) {
                $this->setHeaders($headers->toArray());
            } else {
                throw new BadResponseException('Invalid headers argument received');
            }
        }
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getMessage();
    }

    public function serialize()
    {
        return json_encode(array(
            'status'  => $this->statusCode,
            'body'    => (string) $this->body,
            'headers' => $this->headers->toArray()
        ));
    }

    public function unserialize($serialize)
    {
        $data = json_decode($serialize, true);
        $this->__construct($data['status'], $data['headers'], $data['body']);
    }

    /**
     * Get the response entity body
     *
     * @param bool $asString Set to TRUE to return a string of the body rather than a full body object
     *
     * @return EntityBodyInterface|string
     */
    public function getBody($asString = false)
    {
        return $asString ? (string) $this->body : $this->body;
    }

    /**
     * Set the response entity body
     *
     * @param EntityBodyInterface|string $body Body to set
     *
     * @return self
     */
    public function setBody($body)
    {
        $this->body = EntityBody::factory($body);

        return $this;
    }

    /**
     * Set the protocol and protocol version of the response
     *
     * @param string $protocol Response protocol
     * @param string $version  Protocol version
     *
     * @return self
     */
    public function setProtocol($protocol, $version)
    {
        $this->protocol = $protocol;
        $this->protocolVersion = $version;

        return $this;
    }

    /**
     * Get the protocol used for the response (e.g. HTTP)
     *
     * @return string
     */
    public function getProtocol()
    {
        return $this->protocol;
    }

    /**
     * Get the HTTP protocol version
     *
     * @return string
     */
    public function getProtocolVersion()
    {
        return $this->protocolVersion;
    }

    /**
     * Get a cURL transfer information
     *
     * @param string $key A single statistic to check
     *
     * @return array|string|null Returns all stats if no key is set, a single stat if a key is set, or null if a key
     *                           is set and not found
     * @link http://www.php.net/manual/en/function.curl-getinfo.php
     */
    public function getInfo($key = null)
    {
        if ($key === null) {
            return $this->info;
        } elseif (array_key_exists($key, $this->info)) {
            return $this->info[$key];
        } else {
            return null;
        }
    }

    /**
     * Set the transfer information
     *
     * @param array $info Array of cURL transfer stats
     *
     * @return self
     */
    public function setInfo(array $info)
    {
        $this->info = $info;

        return $this;
    }

    /**
     * Set the response status
     *
     * @param int    $statusCode   Response status code to set
     * @param string $reasonPhrase Response reason phrase
     *
     * @return self
     * @throws BadResponseException when an invalid response code is received
     */
    public function setStatus($statusCode, $reasonPhrase = '')
    {
        $this->statusCode = (int) $statusCode;

        if (!$reasonPhrase && isset(self::$statusTexts[$this->statusCode])) {
            $this->reasonPhrase = self::$statusTexts[$this->statusCode];
        } else {
            $this->reasonPhrase = $reasonPhrase;
        }

        return $this;
    }

    /**
     * Get the response status code
     *
     * @return integer
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * Get the entire response as a string
     *
     * @return string
     */
    public function getMessage()
    {
        $message = $this->getRawHeaders();

        // Only include the body in the message if the size is < 2MB
        $size = $this->body->getSize();
        if ($size < 2097152) {
            $message .= (string) $this->body;
        }

        return $message;
    }

    /**
     * Get the the raw message headers as a string
     *
     * @return string
     */
    public function getRawHeaders()
    {
        $headers = 'HTTP/1.1 ' . $this->statusCode . ' ' . $this->reasonPhrase . "\r\n";
        $lines = $this->getHeaderLines();
        if (!empty($lines)) {
            $headers .= implode("\r\n", $lines) . "\r\n";
        }

        return $headers . "\r\n";
    }

    /**
     * Get the response reason phrase- a human readable version of the numeric
     * status code
     *
     * @return string
     */
    public function getReasonPhrase()
    {
        return $this->reasonPhrase;
    }

    /**
     * Get the Accept-Ranges HTTP header
     *
     * @return string Returns what partial content range types this server supports.
     */
    public function getAcceptRanges()
    {
        return (string) $this->getHeader('Accept-Ranges');
    }

    /**
     * Calculate the age of the response
     *
     * @return integer
     */
    public function calculateAge()
    {
        $age = $this->getHeader('Age');

        if ($age === null && $this->getDate()) {
            $age = time() - strtotime($this->getDate());
        }

        return $age === null ? null : (int) (string) $age;
    }

    /**
     * Get the Age HTTP header
     *
     * @return integer|null Returns the age the object has been in a proxy cache in seconds.
     */
    public function getAge()
    {
        return (string) $this->getHeader('Age');
    }

    /**
     * Get the Allow HTTP header
     *
     * @return string|null Returns valid actions for a specified resource. To be used for a 405 Method not allowed.
     */
    public function getAllow()
    {
        return (string) $this->getHeader('Allow');
    }

    /**
     * Check if an HTTP method is allowed by checking the Allow response header
     *
     * @param string $method Method to check
     *
     * @return bool
     */
    public function isMethodAllowed($method)
    {
        $allow = $this->getHeader('Allow');
        if ($allow) {
            foreach (explode(',', $allow) as $allowable) {
                if (!strcasecmp(trim($allowable), $method)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get the Cache-Control HTTP header
     *
     * @return string
     */
    public function getCacheControl()
    {
        return (string) $this->getHeader('Cache-Control');
    }

    /**
     * Get the Connection HTTP header
     *
     * @return string
     */
    public function getConnection()
    {
        return (string) $this->getHeader('Connection');
    }

    /**
     * Get the Content-Encoding HTTP header
     *
     * @return string|null
     */
    public function getContentEncoding()
    {
        return (string) $this->getHeader('Content-Encoding');
    }

    /**
     * Get the Content-Language HTTP header
     *
     * @return string|null Returns the language the content is in.
     */
    public function getContentLanguage()
    {
        return (string) $this->getHeader('Content-Language');
    }

    /**
     * Get the Content-Length HTTP header
     *
     * @return integer Returns the length of the response body in bytes
     */
    public function getContentLength()
    {
        return (int) (string) $this->getHeader('Content-Length');
    }

    /**
     * Get the Content-Location HTTP header
     *
     * @return string|null Returns an alternate location for the returned data (e.g /index.htm)
     */
    public function getContentLocation()
    {
        return (string) $this->getHeader('Content-Location');
    }

    /**
     * Get the Content-Disposition HTTP header
     *
     * @return string|null Returns the Content-Disposition header
     */
    public function getContentDisposition()
    {
        return (string) $this->getHeader('Content-Disposition');
    }

    /**
     * Get the Content-MD5 HTTP header
     *
     * @return string|null Returns a Base64-encoded binary MD5 sum of the content of the response.
     */
    public function getContentMd5()
    {
        return (string) $this->getHeader('Content-MD5');
    }

    /**
     * Get the Content-Range HTTP header
     *
     * @return string Returns where in a full body message this partial message belongs (e.g. bytes 21010-47021/47022).
     */
    public function getContentRange()
    {
        return (string) $this->getHeader('Content-Range');
    }

    /**
     * Get the Content-Type HTTP header
     *
     * @return string Returns the mime type of this content.
     */
    public function getContentType()
    {
        return (string) $this->getHeader('Content-Type');
    }

    /**
     * Checks if the Content-Type is of a certain type.  This is useful if the
     * Content-Type header contains charset information and you need to know if
     * the Content-Type matches a particular type.
     *
     * @param string $type Content type to check against
     *
     * @return bool
     */
    public function isContentType($type)
    {
        return stripos($this->getHeader('Content-Type'), $type) !== false;
    }

    /**
     * Get the Date HTTP header
     *
     * @return string|null Returns the date and time that the message was sent.
     */
    public function getDate()
    {
        return (string) $this->getHeader('Date');
    }

    /**
     * Get the ETag HTTP header
     *
     * @return string|null Returns an identifier for a specific version of a resource, often a Message digest.
     */
    public function getEtag()
    {
        return (string) $this->getHeader('ETag');
    }

    /**
     * Get the Expires HTTP header
     *
     * @return string|null Returns the date/time after which the response is considered stale.
     */
    public function getExpires()
    {
        return (string) $this->getHeader('Expires');
    }

    /**
     * Get the Last-Modified HTTP header
     *
     * @return string|null Returns the last modified date for the requested object, in RFC 2822 format
     *                     (e.g. Tue, 15 Nov 1994 12:45:26 GMT)
     */
    public function getLastModified()
    {
        return (string) $this->getHeader('Last-Modified');
    }

    /**
     * Get the Location HTTP header
     *
     * @return string|null Used in redirection, or when a new resource has been created.
     */
    public function getLocation()
    {
        return (string) $this->getHeader('Location');
    }

    /**
     * Get the Pragma HTTP header
     *
     * @return Header|null Returns the implementation-specific headers that may have various effects anywhere along
     *                     the request-response chain.
     */
    public function getPragma()
    {
        return (string) $this->getHeader('Pragma');
    }

    /**
     * Get the Proxy-Authenticate HTTP header
     *
     * @return string|null Authentication to access the proxy (e.g. Basic)
     */
    public function getProxyAuthenticate()
    {
        return (string) $this->getHeader('Proxy-Authenticate');
    }

    /**
     * Get the Retry-After HTTP header
     *
     * @return int|null If an entity is temporarily unavailable, this instructs the client to try again after a
     *                  specified period of time.
     */
    public function getRetryAfter()
    {
        return (string) $this->getHeader('Retry-After');
    }

    /**
     * Get the Server HTTP header
     *
     * @return string|null A name for the server
     */
    public function getServer()
    {
        return (string)  $this->getHeader('Server');
    }

    /**
     * Get the Set-Cookie HTTP header
     *
     * @return string|null An HTTP cookie.
     */
    public function getSetCookie()
    {
        return (string) $this->getHeader('Set-Cookie');
    }

    /**
     * Get the Trailer HTTP header
     *
     * @return string|null The Trailer general field value indicates that the given set of header fields is present in
     *                     the trailer of a message encoded with chunked transfer-coding.
     */
    public function getTrailer()
    {
        return (string) $this->getHeader('Trailer');
    }

    /**
     * Get the Transfer-Encoding HTTP header
     *
     * @return string|null The form of encoding used to safely transfer the entity to the user
     */
    public function getTransferEncoding()
    {
        return (string) $this->getHeader('Transfer-Encoding');
    }

    /**
     * Get the Vary HTTP header
     *
     * @return string|null Tells downstream proxies how to match future request headers to decide whether the cached
     *                     response can be used rather than requesting a fresh one from the origin server.
     */
    public function getVary()
    {
        return (string) $this->getHeader('Vary');
    }

    /**
     * Get the Via HTTP header
     *
     * @return string|null Informs the client of proxies through which the response was sent.
     */
    public function getVia()
    {
        return (string) $this->getHeader('Via');
    }

    /**
     * Get the Warning HTTP header
     *
     * @return string|null A general warning about possible problems with the entity body
     */
    public function getWarning()
    {
        return (string) $this->getHeader('Warning');
    }

    /**
     * Get the WWW-Authenticate HTTP header
     *
     * @return string|null Indicates the authentication scheme that should be used to access the requested entity
     */
    public function getWwwAuthenticate()
    {
        return (string) $this->getHeader('WWW-Authenticate');
    }

    /**
     * Checks if HTTP Status code is a Client Error (4xx)
     *
     * @return bool
     */
    public function isClientError()
    {
        return $this->statusCode >= 400 && $this->statusCode < 500;
    }

    /**
     * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx)
     *
     * @return boolean
     */
    public function isError()
    {
        return $this->isClientError() || $this->isServerError();
    }

    /**
     * Checks if HTTP Status code is Information (1xx)
     *
     * @return bool
     */
    public function isInformational()
    {
        return $this->statusCode < 200;
    }

    /**
     * Checks if HTTP Status code is a Redirect (3xx)
     *
     * @return bool
     */
    public function isRedirect()
    {
        return $this->statusCode >= 300 && $this->statusCode < 400;
    }

    /**
     * Checks if HTTP Status code is Server Error (5xx)
     *
     * @return bool
     */
    public function isServerError()
    {
        return $this->statusCode >= 500 && $this->statusCode < 600;
    }

    /**
     * Checks if HTTP Status code is Successful (2xx | 304)
     *
     * @return bool
     */
    public function isSuccessful()
    {
        return ($this->statusCode >= 200 && $this->statusCode < 300) || $this->statusCode == 304;
    }

    /**
     * Check if the response can be cached based on the response headers
     *
     * @return bool Returns TRUE if the response can be cached or false if not
     */
    public function canCache()
    {
        // Check if the response is cacheable based on the code
        if (!in_array((int) $this->getStatusCode(), self::$cacheResponseCodes)) {
            return false;
        }

        // Make sure a valid body was returned and can be cached
        if ((!$this->getBody()->isReadable() || !$this->getBody()->isSeekable())
            && ($this->getContentLength() > 0 || $this->getTransferEncoding() == 'chunked')) {
            return false;
        }

        // Never cache no-store resources (this is a private cache, so private
        // can be cached)
        if ($this->getHeader('Cache-Control') && $this->getHeader('Cache-Control')->hasDirective('no-store')) {
            return false;
        }

        return $this->isFresh() || $this->getFreshness() === null || $this->canValidate();
    }

    /**
     * Gets the number of seconds from the current time in which this response is still considered fresh
     *
     * @return int|null Returns the number of seconds
     */
    public function getMaxAge()
    {
        if ($header = $this->getHeader('Cache-Control')) {
            // s-max-age, then max-age, then Expires
            if ($age = $header->getDirective('s-maxage')) {
                return $age;
            }
            if ($age = $header->getDirective('max-age')) {
                return $age;
            }
        }

        if ($this->getHeader('Expires')) {
            return strtotime($this->getExpires()) - time();
        }

        return null;
    }

    /**
     * Check if the response is considered fresh.
     *
     * A response is considered fresh when its age is less than or equal to the freshness lifetime (maximum age) of the
     * response.
     *
     * @return bool|null
     */
    public function isFresh()
    {
        $fresh = $this->getFreshness();

        return $fresh === null ? null : $fresh >= 0;
    }

    /**
     * Check if the response can be validated against the origin server using a conditional GET request.
     *
     * @return bool
     */
    public function canValidate()
    {
        return $this->getEtag() || $this->getLastModified();
    }

    /**
     * Get the freshness of the response by returning the difference of the maximum lifetime of the response and the
     * age of the response (max-age - age).
     *
     * Freshness values less than 0 mean that the response is no longer fresh and is ABS(freshness) seconds expired.
     * Freshness values of greater than zero is the number of seconds until the response is no longer fresh. A NULL
     * result means that no freshness information is available.
     *
     * @return int
     */
    public function getFreshness()
    {
        $maxAge = $this->getMaxAge();
        $age = $this->calculateAge();

        return $maxAge && $age ? ($maxAge - $age) : null;
    }

    /**
     * Parse the JSON response body and return an array
     *
     * @return array|string|int|bool|float
     * @throws RuntimeException if the response body is not in JSON format
     */
    public function json()
    {
        $data = json_decode((string) $this->body, true);
        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error());
        }

        return $data === null ? array() : $data;
    }

    /**
     * Parse the XML response body and return a \SimpleXMLElement.
     *
     * In order to prevent XXE attacks, this method disables loading external
     * entities. If you rely on external entities, then you must parse the
     * XML response manually by accessing the response body directly.
     *
     * @return \SimpleXMLElement
     * @throws RuntimeException if the response body is not in XML format
     * @link http://websec.io/2012/08/27/Preventing-XXE-in-PHP.html
     */
    public function xml()
    {
        $errorMessage = null;
        $internalErrors = libxml_use_internal_errors(true);
        $disableEntities = libxml_disable_entity_loader(true);
        libxml_clear_errors();

        try {
            $xml = new \SimpleXMLElement((string) $this->body ?: '<root />', LIBXML_NONET);
            if ($error = libxml_get_last_error()) {
                $errorMessage = $error->message;
            }
        } catch (\Exception $e) {
            $errorMessage = $e->getMessage();
        }

        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
        libxml_disable_entity_loader($disableEntities);

        if ($errorMessage) {
            throw new RuntimeException('Unable to parse response body into XML: ' . $errorMessage);
        }

        return $xml;
    }

    /**
     * Get the redirect count of this response
     *
     * @return int
     */
    public function getRedirectCount()
    {
        return (int) $this->params->get(RedirectPlugin::REDIRECT_COUNT);
    }

    /**
     * Set the effective URL that resulted in this response (e.g. the last redirect URL)
     *
     * @param string $url The effective URL
     *
     * @return self
     */
    public function setEffectiveUrl($url)
    {
        $this->effectiveUrl = $url;

        return $this;
    }

    /**
     * Get the effective URL that resulted in this response (e.g. the last redirect URL)
     *
     * @return string
     */
    public function getEffectiveUrl()
    {
        return $this->effectiveUrl;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function getPreviousResponse()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin.');
        return null;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function setRequest($request)
    {
        Version::warn(__METHOD__ . ' is deprecated');
        return $this;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function getRequest()
    {
        Version::warn(__METHOD__ . ' is deprecated');
        return null;
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * POST file upload
 */
interface PostFileInterface
{
    /**
     * Set the name of the field
     *
     * @param string $name Field name
     *
     * @return self
     */
    public function setFieldName($name);

    /**
     * Get the name of the field
     *
     * @return string
     */
    public function getFieldName();

    /**
     * Set the path to the file
     *
     * @param string $path Full path to the file
     *
     * @return self
     * @throws InvalidArgumentException if the file cannot be read
     */
    public function setFilename($path);

    /**
     * Set the post name of the file
     *
     * @param string $name The new name of the file
     *
     * @return self
     */
    public function setPostname($name);

    /**
     * Get the full path to the file
     *
     * @return string
     */
    public function getFilename();

    /**
     * Get the post name of the file
     *
     * @return string
     */
    public function getPostname();

    /**
     * Set the Content-Type of the file
     *
     * @param string $type Content type
     *
     * @return self
     */
    public function setContentType($type);

    /**
     * Get the Content-Type of the file
     *
     * @return string
     */
    public function getContentType();

    /**
     * Get a cURL ready string or CurlFile object for the upload
     *
     * @return string
     */
    public function getCurlValue();
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Http\Exception\RequestException;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\Url;
use Guzzle\Http\QueryString;

/**
 * Generic HTTP request interface
 */
interface RequestInterface extends MessageInterface, HasDispatcherInterface
{
    const STATE_NEW = 'new';
    const STATE_COMPLETE = 'complete';
    const STATE_TRANSFER = 'transfer';
    const STATE_ERROR = 'error';

    const GET = 'GET';
    const PUT = 'PUT';
    const POST = 'POST';
    const DELETE = 'DELETE';
    const HEAD = 'HEAD';
    const CONNECT = 'CONNECT';
    const OPTIONS = 'OPTIONS';
    const TRACE = 'TRACE';
    const PATCH = 'PATCH';

    /**
     * @return string
     */
    public function __toString();

    /**
     * Send the request
     *
     * @return Response
     * @throws RequestException on a request error
     */
    public function send();

    /**
     * Set the client used to transport the request
     *
     * @param ClientInterface $client
     *
     * @return self
     */
    public function setClient(ClientInterface $client);

    /**
     * Get the client used to transport the request
     *
     * @return ClientInterface $client
     */
    public function getClient();

    /**
     * Set the URL of the request
     *
     * @param string $url|Url Full URL to set including query string
     *
     * @return self
     */
    public function setUrl($url);

    /**
     * Get the full URL of the request (e.g. 'http://www.guzzle-project.com/')
     *
     * @param bool $asObject Set to TRUE to retrieve the URL as a clone of the URL object owned by the request.
     *
     * @return string|Url
     */
    public function getUrl($asObject = false);

    /**
     * Get the resource part of the the request, including the path, query string, and fragment
     *
     * @return string
     */
    public function getResource();

    /**
     * Get the collection of key value pairs that will be used as the query string in the request
     *
     * @return QueryString
     */
    public function getQuery();

    /**
     * Get the HTTP method of the request
     *
     * @return string
     */
    public function getMethod();

    /**
     * Get the URI scheme of the request (http, https, ftp, etc)
     *
     * @return string
     */
    public function getScheme();

    /**
     * Set the URI scheme of the request (http, https, ftp, etc)
     *
     * @param string $scheme Scheme to set
     *
     * @return self
     */
    public function setScheme($scheme);

    /**
     * Get the host of the request
     *
     * @return string
     */
    public function getHost();

    /**
     * Set the host of the request. Including a port in the host will modify the port of the request.
     *
     * @param string $host Host to set (e.g. www.yahoo.com, www.yahoo.com:80)
     *
     * @return self
     */
    public function setHost($host);

    /**
     * Get the path of the request (e.g. '/', '/index.html')
     *
     * @return string
     */
    public function getPath();

    /**
     * Set the path of the request (e.g. '/', '/index.html')
     *
     * @param string|array $path Path to set or array of segments to implode
     *
     * @return self
     */
    public function setPath($path);

    /**
     * Get the port that the request will be sent on if it has been set
     *
     * @return int|null
     */
    public function getPort();

    /**
     * Set the port that the request will be sent on
     *
     * @param int $port Port number to set
     *
     * @return self
     */
    public function setPort($port);

    /**
     * Get the username to pass in the URL if set
     *
     * @return string|null
     */
    public function getUsername();

    /**
     * Get the password to pass in the URL if set
     *
     * @return string|null
     */
    public function getPassword();

    /**
     * Set HTTP authorization parameters
     *
     * @param string|bool $user     User name or false disable authentication
     * @param string      $password Password
     * @param string      $scheme   Authentication scheme ('Basic', 'Digest', or a CURLAUTH_* constant (deprecated))
     *
     * @return self
     * @link http://www.ietf.org/rfc/rfc2617.txt
     * @link http://php.net/manual/en/function.curl-setopt.php See the available options for CURLOPT_HTTPAUTH
     * @throws RequestException
     */
    public function setAuth($user, $password = '', $scheme = 'Basic');

    /**
     * Get the HTTP protocol version of the request
     *
     * @return string
     */
    public function getProtocolVersion();

    /**
     * Set the HTTP protocol version of the request (e.g. 1.1 or 1.0)
     *
     * @param string $protocol HTTP protocol version to use with the request
     *
     * @return self
     */
    public function setProtocolVersion($protocol);

    /**
     * Get the previously received {@see Response} or NULL if the request has not been sent
     *
     * @return Response|null
     */
    public function getResponse();

    /**
     * Manually set a response for the request.
     *
     * This method is useful for specifying a mock response for the request or setting the response using a cache.
     * Manually setting a response will bypass the actual sending of a request.
     *
     * @param Response $response Response object to set
     * @param bool     $queued   Set to TRUE to keep the request in a state of not having been sent, but queue the
     *                           response for send()
     *
     * @return self Returns a reference to the object.
     */
    public function setResponse(Response $response, $queued = false);

    /**
     * The start of a response has been received for a request and the request is still in progress
     *
     * @param Response $response Response that has been received so far
     *
     * @return self
     */
    public function startResponse(Response $response);

    /**
     * Set the EntityBody that will hold a successful response message's entity body.
     *
     * This method should be invoked when you need to send the response's entity body somewhere other than the normal
     * php://temp buffer. For example, you can send the entity body to a socket, file, or some other custom stream.
     *
     * @param EntityBodyInterface|string|resource $body Response body object. Pass a string to attempt to store the
     *                                                  response body in a local file.
     * @return Request
     */
    public function setResponseBody($body);

    /**
     * Get the EntityBody that will hold the resulting response message's entity body. This response body will only
     * be used for successful responses. Intermediate responses (e.g. redirects) will not use the targeted response
     * body.
     *
     * @return EntityBodyInterface
     */
    public function getResponseBody();

    /**
     * Get the state of the request. One of 'complete', 'transfer', 'new', 'error'
     *
     * @return string
     */
    public function getState();

    /**
     * Set the state of the request
     *
     * @param string $state   State of the request ('complete', 'transfer', 'new', 'error')
     * @param array  $context Contextual information about the state change
     *
     * @return string Returns the current state of the request (which may have changed due to events being fired)
     */
    public function setState($state, array $context = array());

    /**
     * Get the cURL options that will be applied when the cURL handle is created
     *
     * @return Collection
     */
    public function getCurlOptions();

    /**
     * Get an array of Cookies
     *
     * @return array
     */
    public function getCookies();

    /**
     * Get a cookie value by name
     *
     * @param string $name Cookie to retrieve
     *
     * @return null|string
     */
    public function getCookie($name);

    /**
     * Add a Cookie value by name to the Cookie header
     *
     * @param string $name  Name of the cookie to add
     * @param string $value Value to set
     *
     * @return self
     */
    public function addCookie($name, $value);

    /**
     * Remove a specific cookie value by name
     *
     * @param string $name Cookie to remove by name
     *
     * @return self
     */
    public function removeCookie($name);
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Version;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Mimetypes;

/**
 * POST file upload
 */
class PostFile implements PostFileInterface
{
    protected $fieldName;
    protected $contentType;
    protected $filename;
    protected $postname;

    /**
     * @param string $fieldName   Name of the field
     * @param string $filename    Local path to the file
     * @param string $postname    Remote post file name
     * @param string $contentType Content-Type of the upload
     */
    public function __construct($fieldName, $filename, $contentType = null, $postname = null)
    {
        $this->fieldName = $fieldName;
        $this->setFilename($filename);
        $this->postname = $postname ? $postname : basename($filename);
        $this->contentType = $contentType ?: $this->guessContentType();
    }

    public function setFieldName($name)
    {
        $this->fieldName = $name;

        return $this;
    }

    public function getFieldName()
    {
        return $this->fieldName;
    }

    public function setFilename($filename)
    {
        // Remove leading @ symbol
        if (strpos($filename, '@') === 0) {
            $filename = substr($filename, 1);
        }

        if (!is_readable($filename)) {
            throw new InvalidArgumentException("Unable to open {$filename} for reading");
        }

        $this->filename = $filename;

        return $this;
    }

    public function setPostname($postname)
    {
        $this->postname = $postname;

        return $this;
    }

    public function getFilename()
    {
        return $this->filename;
    }

    public function getPostname()
    {
        return $this->postname;
    }

    public function setContentType($type)
    {
        $this->contentType = $type;

        return $this;
    }

    public function getContentType()
    {
        return $this->contentType;
    }

    public function getCurlValue()
    {
        // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
        // See: https://wiki.php.net/rfc/curl-file-upload
        if (function_exists('curl_file_create')) {
            return curl_file_create($this->filename, $this->contentType, $this->postname);
        }

        // Use the old style if using an older version of PHP
        $value = "@{$this->filename};filename=" . $this->postname;
        if ($this->contentType) {
            $value .= ';type=' . $this->contentType;
        }

        return $value;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function getCurlString()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use getCurlValue()');
        return $this->getCurlValue();
    }

    /**
     * Determine the Content-Type of the file
     */
    protected function guessContentType()
    {
        return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream';
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Version;
use Guzzle\Common\Event;
use Guzzle\Common\Collection;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Exception\RequestException;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\EntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\Message\Header\HeaderInterface;
use Guzzle\Http\Url;
use Guzzle\Parser\ParserRegistry;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * HTTP request class to send requests
 */
class Request extends AbstractMessage implements RequestInterface
{
    /** @var EventDispatcherInterface */
    protected $eventDispatcher;

    /** @var Url HTTP Url */
    protected $url;

    /** @var string HTTP method (GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE) */
    protected $method;

    /** @var ClientInterface */
    protected $client;

    /** @var Response Response of the request */
    protected $response;

    /** @var EntityBodyInterface Response body */
    protected $responseBody;

    /** @var string State of the request object */
    protected $state;

    /** @var string Authentication username */
    protected $username;

    /** @var string Auth password */
    protected $password;

    /** @var Collection cURL specific transfer options */
    protected $curlOptions;

    /** @var bool */
    protected $isRedirect = false;

    public static function getAllEvents()
    {
        return array(
            // Called when receiving or uploading data through cURL
            'curl.callback.read', 'curl.callback.write', 'curl.callback.progress',
            // Cloning a request
            'request.clone',
            // About to send the request, sent request, completed transaction
            'request.before_send', 'request.sent', 'request.complete',
            // A request received a successful response
            'request.success',
            // A request received an unsuccessful response
            'request.error',
            // An exception is being thrown because of an unsuccessful response
            'request.exception',
            // Received response status line
            'request.receive.status_line'
        );
    }

    /**
     * @param string           $method  HTTP method
     * @param string|Url       $url     HTTP URL to connect to. The URI scheme, host header, and URI are parsed from the
     *                                  full URL. If query string parameters are present they will be parsed as well.
     * @param array|Collection $headers HTTP headers
     */
    public function __construct($method, $url, $headers = array())
    {
        parent::__construct();
        $this->method = strtoupper($method);
        $this->curlOptions = new Collection();
        $this->setUrl($url);

        if ($headers) {
            // Special handling for multi-value headers
            foreach ($headers as $key => $value) {
                // Deal with collisions with Host and Authorization
                if ($key == 'host' || $key == 'Host') {
                    $this->setHeader($key, $value);
                } elseif ($value instanceof HeaderInterface) {
                    $this->addHeader($key, $value);
                } else {
                    foreach ((array) $value as $v) {
                        $this->addHeader($key, $v);
                    }
                }
            }
        }

        $this->setState(self::STATE_NEW);
    }

    public function __clone()
    {
        if ($this->eventDispatcher) {
            $this->eventDispatcher = clone $this->eventDispatcher;
        }
        $this->curlOptions = clone $this->curlOptions;
        $this->params = clone $this->params;
        $this->url = clone $this->url;
        $this->response = $this->responseBody = null;
        $this->headers = clone $this->headers;

        $this->setState(RequestInterface::STATE_NEW);
        $this->dispatch('request.clone', array('request' => $this));
    }

    /**
     * Get the HTTP request as a string
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getRawHeaders() . "\r\n\r\n";
    }

    /**
     * Default method that will throw exceptions if an unsuccessful response is received.
     *
     * @param Event $event Received
     * @throws BadResponseException if the response is not successful
     */
    public static function onRequestError(Event $event)
    {
        $e = BadResponseException::factory($event['request'], $event['response']);
        $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray());
        throw $e;
    }

    public function setClient(ClientInterface $client)
    {
        $this->client = $client;

        return $this;
    }

    public function getClient()
    {
        return $this->client;
    }

    public function getRawHeaders()
    {
        $protocolVersion = $this->protocolVersion ?: '1.1';

        return trim($this->method . ' ' . $this->getResource()) . ' '
            . strtoupper(str_replace('https', 'http', $this->url->getScheme()))
            . '/' . $protocolVersion . "\r\n" . implode("\r\n", $this->getHeaderLines());
    }

    public function setUrl($url)
    {
        if ($url instanceof Url) {
            $this->url = $url;
        } else {
            $this->url = Url::factory($url);
        }

        // Update the port and host header
        $this->setPort($this->url->getPort());

        if ($this->url->getUsername() || $this->url->getPassword()) {
            $this->setAuth($this->url->getUsername(), $this->url->getPassword());
            // Remove the auth info from the URL
            $this->url->setUsername(null);
            $this->url->setPassword(null);
        }

        return $this;
    }

    public function send()
    {
        if (!$this->client) {
            throw new RuntimeException('A client must be set on the request');
        }

        return $this->client->send($this);
    }

    public function getResponse()
    {
        return $this->response;
    }

    public function getQuery($asString = false)
    {
        return $asString
            ? (string) $this->url->getQuery()
            : $this->url->getQuery();
    }

    public function getMethod()
    {
        return $this->method;
    }

    public function getScheme()
    {
        return $this->url->getScheme();
    }

    public function setScheme($scheme)
    {
        $this->url->setScheme($scheme);

        return $this;
    }

    public function getHost()
    {
        return $this->url->getHost();
    }

    public function setHost($host)
    {
        $this->url->setHost($host);
        $this->setPort($this->url->getPort());

        return $this;
    }

    public function getProtocolVersion()
    {
        return $this->protocolVersion;
    }

    public function setProtocolVersion($protocol)
    {
        $this->protocolVersion = $protocol;

        return $this;
    }

    public function getPath()
    {
        return '/' . ltrim($this->url->getPath(), '/');
    }

    public function setPath($path)
    {
        $this->url->setPath($path);

        return $this;
    }

    public function getPort()
    {
        return $this->url->getPort();
    }

    public function setPort($port)
    {
        $this->url->setPort($port);

        // Include the port in the Host header if it is not the default port for the scheme of the URL
        $scheme = $this->url->getScheme();
        if ($port && (($scheme == 'http' && $port != 80) || ($scheme == 'https' && $port != 443))) {
            $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost() . ':' . $port);
        } else {
            $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost());
        }

        return $this;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setAuth($user, $password = '', $scheme = CURLAUTH_BASIC)
    {
        static $authMap = array(
            'basic'  => CURLAUTH_BASIC,
            'digest' => CURLAUTH_DIGEST,
            'ntlm'   => CURLAUTH_NTLM,
            'any'    => CURLAUTH_ANY
        );

        // If we got false or null, disable authentication
        if (!$user) {
            $this->password = $this->username = null;
            $this->removeHeader('Authorization');
            $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH);
            return $this;
        }

        if (!is_numeric($scheme)) {
            $scheme = strtolower($scheme);
            if (!isset($authMap[$scheme])) {
                throw new InvalidArgumentException($scheme . ' is not a valid authentication type');
            }
            $scheme = $authMap[$scheme];
        }

        $this->username = $user;
        $this->password = $password;

        // Bypass CURL when using basic auth to promote connection reuse
        if ($scheme == CURLAUTH_BASIC) {
            $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH);
            $this->setHeader('Authorization', 'Basic ' . base64_encode($this->username . ':' . $this->password));
        } else {
            $this->getCurlOptions()
                ->set(CURLOPT_HTTPAUTH, $scheme)
                ->set(CURLOPT_USERPWD, $this->username . ':' . $this->password);
        }

        return $this;
    }

    public function getResource()
    {
        $resource = $this->getPath();
        if ($query = (string) $this->url->getQuery()) {
            $resource .= '?' . $query;
        }

        return $resource;
    }

    public function getUrl($asObject = false)
    {
        return $asObject ? clone $this->url : (string) $this->url;
    }

    public function getState()
    {
        return $this->state;
    }

    public function setState($state, array $context = array())
    {
        $oldState = $this->state;
        $this->state = $state;

        switch ($state) {
            case self::STATE_NEW:
                $this->response = null;
                break;
            case self::STATE_TRANSFER:
                if ($oldState !== $state) {
                    // Fix Content-Length and Transfer-Encoding collisions
                    if ($this->hasHeader('Transfer-Encoding') && $this->hasHeader('Content-Length')) {
                        $this->removeHeader('Transfer-Encoding');
                    }
                    $this->dispatch('request.before_send', array('request' => $this));
                }
                break;
            case self::STATE_COMPLETE:
                if ($oldState !== $state) {
                    $this->processResponse($context);
                    $this->responseBody = null;
                }
                break;
            case self::STATE_ERROR:
                if (isset($context['exception'])) {
                    $this->dispatch('request.exception', array(
                        'request'   => $this,
                        'response'  => isset($context['response']) ? $context['response'] : $this->response,
                        'exception' => isset($context['exception']) ? $context['exception'] : null
                    ));
                }
        }

        return $this->state;
    }

    public function getCurlOptions()
    {
        return $this->curlOptions;
    }

    public function startResponse(Response $response)
    {
        $this->state = self::STATE_TRANSFER;
        $response->setEffectiveUrl((string) $this->getUrl());
        $this->response = $response;

        return $this;
    }

    public function setResponse(Response $response, $queued = false)
    {
        $response->setEffectiveUrl((string) $this->url);

        if ($queued) {
            $ed = $this->getEventDispatcher();
            $ed->addListener('request.before_send', $f = function ($e) use ($response, &$f, $ed) {
                $e['request']->setResponse($response);
                $ed->removeListener('request.before_send', $f);
            }, -9999);
        } else {
            $this->response = $response;
            // If a specific response body is specified, then use it instead of the response's body
            if ($this->responseBody && !$this->responseBody->getCustomData('default') && !$response->isRedirect()) {
                $this->getResponseBody()->write((string) $this->response->getBody());
            } else {
                $this->responseBody = $this->response->getBody();
            }
            $this->setState(self::STATE_COMPLETE);
        }

        return $this;
    }

    public function setResponseBody($body)
    {
        // Attempt to open a file for writing if a string was passed
        if (is_string($body)) {
            // @codeCoverageIgnoreStart
            if (!($body = fopen($body, 'w+'))) {
                throw new InvalidArgumentException('Could not open ' . $body . ' for writing');
            }
            // @codeCoverageIgnoreEnd
        }

        $this->responseBody = EntityBody::factory($body);

        return $this;
    }

    public function getResponseBody()
    {
        if ($this->responseBody === null) {
            $this->responseBody = EntityBody::factory()->setCustomData('default', true);
        }

        return $this->responseBody;
    }

    /**
     * Determine if the response body is repeatable (readable + seekable)
     *
     * @return bool
     * @deprecated Use getResponseBody()->isSeekable()
     * @codeCoverageIgnore
     */
    public function isResponseBodyRepeatable()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $request->getResponseBody()->isRepeatable()');
        return !$this->responseBody ? true : $this->responseBody->isRepeatable();
    }

    public function getCookies()
    {
        if ($cookie = $this->getHeader('Cookie')) {
            $data = ParserRegistry::getInstance()->getParser('cookie')->parseCookie($cookie);
            return $data['cookies'];
        }

        return array();
    }

    public function getCookie($name)
    {
        $cookies = $this->getCookies();

        return isset($cookies[$name]) ? $cookies[$name] : null;
    }

    public function addCookie($name, $value)
    {
        if (!$this->hasHeader('Cookie')) {
            $this->setHeader('Cookie', "{$name}={$value}");
        } else {
            $this->getHeader('Cookie')->add("{$name}={$value}");
        }

        // Always use semicolons to separate multiple cookie headers
        $this->getHeader('Cookie')->setGlue(';');

        return $this;
    }

    public function removeCookie($name)
    {
        if ($cookie = $this->getHeader('Cookie')) {
            foreach ($cookie as $cookieValue) {
                if (strpos($cookieValue, $name . '=') === 0) {
                    $cookie->removeValue($cookieValue);
                }
            }
        }

        return $this;
    }

    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->eventDispatcher->addListener('request.error', array(__CLASS__, 'onRequestError'), -255);

        return $this;
    }

    public function getEventDispatcher()
    {
        if (!$this->eventDispatcher) {
            $this->setEventDispatcher(new EventDispatcher());
        }

        return $this->eventDispatcher;
    }

    public function dispatch($eventName, array $context = array())
    {
        $context['request'] = $this;

        return $this->getEventDispatcher()->dispatch($eventName, new Event($context));
    }

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->getEventDispatcher()->addSubscriber($subscriber);

        return $this;
    }

    /**
     * Get an array containing the request and response for event notifications
     *
     * @return array
     */
    protected function getEventArray()
    {
        return array(
            'request'  => $this,
            'response' => $this->response
        );
    }

    /**
     * Process a received response
     *
     * @param array $context Contextual information
     * @throws RequestException|BadResponseException on unsuccessful responses
     */
    protected function processResponse(array $context = array())
    {
        if (!$this->response) {
            // If no response, then processResponse shouldn't have been called
            $e = new RequestException('Error completing request');
            $e->setRequest($this);
            throw $e;
        }

        $this->state = self::STATE_COMPLETE;

        // A request was sent, but we don't know if we'll send more or if the final response will be successful
        $this->dispatch('request.sent', $this->getEventArray() + $context);

        // Some response processors will remove the response or reset the state (example: ExponentialBackoffPlugin)
        if ($this->state == RequestInterface::STATE_COMPLETE) {

            // The request completed, so the HTTP transaction is complete
            $this->dispatch('request.complete', $this->getEventArray());

            // If the response is bad, allow listeners to modify it or throw exceptions. You can change the response by
            // modifying the Event object in your listeners or calling setResponse() on the request
            if ($this->response->isError()) {
                $event = new Event($this->getEventArray());
                $this->getEventDispatcher()->dispatch('request.error', $event);
                // Allow events of request.error to quietly change the response
                if ($event['response'] !== $this->response) {
                    $this->response = $event['response'];
                }
            }

            // If a successful response was received, dispatch an event
            if ($this->response->isSuccessful()) {
                $this->dispatch('request.success', $this->getEventArray());
            }
        }
    }

    /**
     * @deprecated Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy
     * @codeCoverageIgnore
     */
    public function canCache()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy.');
        if (class_exists('Guzzle\Plugin\Cache\DefaultCanCacheStrategy')) {
            $canCache = new \Guzzle\Plugin\Cache\DefaultCanCacheStrategy();
            return $canCache->canCacheRequest($this);
        } else {
            return false;
        }
    }

    /**
     * @deprecated Use the history plugin (not emitting a warning as this is built-into the RedirectPlugin for now)
     * @codeCoverageIgnore
     */
    public function setIsRedirect($isRedirect)
    {
        $this->isRedirect = $isRedirect;

        return $this;
    }

    /**
     * @deprecated Use the history plugin
     * @codeCoverageIgnore
     */
    public function isRedirect()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin to track this.');
        return $this->isRedirect;
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Version;
use Guzzle\Http\Message\Header\HeaderInterface;

/**
 * Represents a header and all of the values stored by that header
 */
class Header implements HeaderInterface
{
    protected $values = array();
    protected $header;
    protected $glue;

    /**
     * @param string       $header Name of the header
     * @param array|string $values Values of the header as an array or a scalar
     * @param string       $glue   Glue used to combine multiple values into a string
     */
    public function __construct($header, $values = array(), $glue = ',')
    {
        $this->header = trim($header);
        $this->glue = $glue;

        foreach ((array) $values as $value) {
            foreach ((array) $value as $v) {
                $this->values[] = $v;
            }
        }
    }

    public function __toString()
    {
        return implode($this->glue . ' ', $this->toArray());
    }

    public function add($value)
    {
        $this->values[] = $value;

        return $this;
    }

    public function getName()
    {
        return $this->header;
    }

    public function setName($name)
    {
        $this->header = $name;

        return $this;
    }

    public function setGlue($glue)
    {
        $this->glue = $glue;

        return $this;
    }

    public function getGlue()
    {
        return $this->glue;
    }

    /**
     * Normalize the header to be a single header with an array of values.
     *
     * If any values of the header contains the glue string value (e.g. ","), then the value will be exploded into
     * multiple entries in the header.
     *
     * @return self
     */
    public function normalize()
    {
        $values = $this->toArray();

        for ($i = 0, $total = count($values); $i < $total; $i++) {
            if (strpos($values[$i], $this->glue) !== false) {
                // Explode on glue when the glue is not inside of a comma
                foreach (preg_split('/' . preg_quote($this->glue) . '(?=([^"]*"[^"]*")*[^"]*$)/', $values[$i]) as $v) {
                    $values[] = trim($v);
                }
                unset($values[$i]);
            }
        }

        $this->values = array_values($values);

        return $this;
    }

    public function hasValue($searchValue)
    {
        return in_array($searchValue, $this->toArray());
    }

    public function removeValue($searchValue)
    {
        $this->values = array_values(array_filter($this->values, function ($value) use ($searchValue) {
            return $value != $searchValue;
        }));

        return $this;
    }

    public function toArray()
    {
        return $this->values;
    }

    public function count()
    {
        return count($this->toArray());
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->toArray());
    }

    public function parseParams()
    {
        $params = $matches = array();
        $callback = array($this, 'trimHeader');

        // Normalize the header into a single array and iterate over all values
        foreach ($this->normalize()->toArray() as $val) {
            $part = array();
            foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
                if (!preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
                    continue;
                }
                $pieces = array_map($callback, $matches[0]);
                $part[$pieces[0]] = isset($pieces[1]) ? $pieces[1] : '';
            }
            if ($part) {
                $params[] = $part;
            }
        }

        return $params;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function hasExactHeader($header)
    {
        Version::warn(__METHOD__ . ' is deprecated');
        return $this->header == $header;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function raw()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use toArray()');
        return $this->toArray();
    }

    /**
     * Trim a header by removing excess spaces and wrapping quotes
     *
     * @param $str
     *
     * @return string
     */
    protected function trimHeader($str)
    {
        static $trimmed = "\"'  \n\t";

        return trim($str, $trimmed);
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Version;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\Header\HeaderCollection;
use Guzzle\Http\Message\Header\HeaderFactory;
use Guzzle\Http\Message\Header\HeaderFactoryInterface;
use Guzzle\Http\Message\Header\HeaderInterface;

/**
 * Abstract HTTP request/response message
 */
abstract class AbstractMessage implements MessageInterface
{
    /** @var array HTTP header collection */
    protected $headers;

    /** @var HeaderFactoryInterface $headerFactory */
    protected $headerFactory;

    /** @var Collection Custom message parameters that are extendable by plugins */
    protected $params;

    /** @var string Message protocol */
    protected $protocol = 'HTTP';

    /** @var string HTTP protocol version of the message */
    protected $protocolVersion = '1.1';

    public function __construct()
    {
        $this->params = new Collection();
        $this->headerFactory = new HeaderFactory();
        $this->headers = new HeaderCollection();
    }

    /**
     * Set the header factory to use to create headers
     *
     * @param HeaderFactoryInterface $factory
     *
     * @return self
     */
    public function setHeaderFactory(HeaderFactoryInterface $factory)
    {
        $this->headerFactory = $factory;

        return $this;
    }

    public function getParams()
    {
        return $this->params;
    }

    public function addHeader($header, $value)
    {
        if (isset($this->headers[$header])) {
            $this->headers[$header]->add($value);
        } elseif ($value instanceof HeaderInterface) {
            $this->headers[$header] = $value;
        } else {
            $this->headers[$header] = $this->headerFactory->createHeader($header, $value);
        }

        return $this;
    }

    public function addHeaders(array $headers)
    {
        foreach ($headers as $key => $value) {
            $this->addHeader($key, $value);
        }

        return $this;
    }

    public function getHeader($header)
    {
        return $this->headers[$header];
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function getHeaderLines()
    {
        $headers = array();
        foreach ($this->headers as $value) {
            $headers[] = $value->getName() . ': ' . $value;
        }

        return $headers;
    }

    public function setHeader($header, $value)
    {
        unset($this->headers[$header]);
        $this->addHeader($header, $value);

        return $this;
    }

    public function setHeaders(array $headers)
    {
        $this->headers->clear();
        foreach ($headers as $key => $value) {
            $this->addHeader($key, $value);
        }

        return $this;
    }

    public function hasHeader($header)
    {
        return isset($this->headers[$header]);
    }

    public function removeHeader($header)
    {
        unset($this->headers[$header]);

        return $this;
    }

    /**
     * @deprecated Use $message->getHeader()->parseParams()
     * @codeCoverageIgnore
     */
    public function getTokenizedHeader($header, $token = ';')
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader()->parseParams()');
        if ($this->hasHeader($header)) {
            $data = new Collection();
            foreach ($this->getHeader($header)->parseParams() as $values) {
                foreach ($values as $key => $value) {
                    if ($value === '') {
                        $data->set($data->count(), $key);
                    } else {
                        $data->add($key, $value);
                    }
                }
            }
            return $data;
        }
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function setTokenizedHeader($header, $data, $token = ';')
    {
        Version::warn(__METHOD__ . ' is deprecated.');
        return $this;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function getCacheControlDirective($directive)
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->getDirective()');
        if (!($header = $this->getHeader('Cache-Control'))) {
            return null;
        }

        return $header->getDirective($directive);
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function hasCacheControlDirective($directive)
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->hasDirective()');
        if ($header = $this->getHeader('Cache-Control')) {
            return $header->hasDirective($directive);
        } else {
            return false;
        }
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function addCacheControlDirective($directive, $value = true)
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->addDirective()');
        if (!($header = $this->getHeader('Cache-Control'))) {
            $this->addHeader('Cache-Control', '');
            $header = $this->getHeader('Cache-Control');
        }

        $header->addDirective($directive, $value);

        return $this;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function removeCacheControlDirective($directive)
    {
        Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->removeDirective()');
        if ($header = $this->getHeader('Cache-Control')) {
            $header->removeDirective($directive);
        }

        return $this;
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Url;
use Guzzle\Parser\ParserRegistry;

/**
 * Default HTTP request factory used to create the default {@see Request} and {@see EntityEnclosingRequest} objects.
 */
class RequestFactory implements RequestFactoryInterface
{
    /** @var RequestFactory Singleton instance of the default request factory */
    protected static $instance;

    /** @var array Hash of methods available to the class (provides fast isset() lookups) */
    protected $methods;

    /** @var string Class to instantiate for requests with no body */
    protected $requestClass = 'Guzzle\\Http\\Message\\Request';

    /** @var string Class to instantiate for requests with a body */
    protected $entityEnclosingRequestClass = 'Guzzle\\Http\\Message\\EntityEnclosingRequest';

    /**
     * Get a cached instance of the default request factory
     *
     * @return RequestFactory
     */
    public static function getInstance()
    {
        // @codeCoverageIgnoreStart
        if (!static::$instance) {
            static::$instance = new static();
        }
        // @codeCoverageIgnoreEnd

        return static::$instance;
    }

    public function __construct()
    {
        $this->methods = array_flip(get_class_methods(__CLASS__));
    }

    public function fromMessage($message)
    {
        $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($message);

        if (!$parsed) {
            return false;
        }

        $request = $this->fromParts($parsed['method'], $parsed['request_url'],
            $parsed['headers'], $parsed['body'], $parsed['protocol'],
            $parsed['version']);

        // EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST
        // requests. This factory method should accurately reflect the message, so here we are removing the Expect
        // header if one was not supplied in the message.
        if (!isset($parsed['headers']['Expect']) && !isset($parsed['headers']['expect'])) {
            $request->removeHeader('Expect');
        }

        return $request;
    }

    public function fromParts(
        $method,
        array $urlParts,
        $headers = null,
        $body = null,
        $protocol = 'HTTP',
        $protocolVersion = '1.1'
    ) {
        return $this->create($method, Url::buildUrl($urlParts), $headers, $body)
                    ->setProtocolVersion($protocolVersion);
    }

    public function create($method, $url, $headers = null, $body = null, array $options = array())
    {
        $method = strtoupper($method);

        if ($method == 'GET' || $method == 'HEAD' || $method == 'TRACE') {
            // Handle non-entity-enclosing request methods
            $request = new $this->requestClass($method, $url, $headers);
            if ($body) {
                // The body is where the response body will be stored
                $type = gettype($body);
                if ($type == 'string' || $type == 'resource' || $type == 'object') {
                    $request->setResponseBody($body);
                }
            }
        } else {
            // Create an entity enclosing request by default
            $request = new $this->entityEnclosingRequestClass($method, $url, $headers);
            if ($body || $body === '0') {
                // Add POST fields and files to an entity enclosing request if an array is used
                if (is_array($body) || $body instanceof Collection) {
                    // Normalize PHP style cURL uploads with a leading '@' symbol
                    foreach ($body as $key => $value) {
                        if (is_string($value) && substr($value, 0, 1) == '@') {
                            $request->addPostFile($key, $value);
                            unset($body[$key]);
                        }
                    }
                    // Add the fields if they are still present and not all files
                    $request->addPostFields($body);
                } else {
                    // Add a raw entity body body to the request
                    $request->setBody($body, (string) $request->getHeader('Content-Type'));
                    if ((string) $request->getHeader('Transfer-Encoding') == 'chunked') {
                        $request->removeHeader('Content-Length');
                    }
                }
            }
        }

        if ($options) {
            $this->applyOptions($request, $options);
        }

        return $request;
    }

    /**
     * Clone a request while changing the method. Emulates the behavior of
     * {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method.
     *
     * @param RequestInterface $request Request to clone
     * @param string           $method  Method to set
     *
     * @return RequestInterface
     */
    public function cloneRequestWithMethod(RequestInterface $request, $method)
    {
        // Create the request with the same client if possible
        if ($request->getClient()) {
            $cloned = $request->getClient()->createRequest($method, $request->getUrl(), $request->getHeaders());
        } else {
            $cloned = $this->create($method, $request->getUrl(), $request->getHeaders());
        }

        $cloned->getCurlOptions()->replace($request->getCurlOptions()->toArray());
        $cloned->setEventDispatcher(clone $request->getEventDispatcher());
        // Ensure that that the Content-Length header is not copied if changing to GET or HEAD
        if (!($cloned instanceof EntityEnclosingRequestInterface)) {
            $cloned->removeHeader('Content-Length');
        } elseif ($request instanceof EntityEnclosingRequestInterface) {
            $cloned->setBody($request->getBody());
        }
        $cloned->getParams()->replace($request->getParams()->toArray());
        $cloned->dispatch('request.clone', array('request' => $cloned));

        return $cloned;
    }

    public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE)
    {
        // Iterate over each key value pair and attempt to apply a config using function visitors
        foreach ($options as $key => $value) {
            $method = "visit_{$key}";
            if (isset($this->methods[$method])) {
                $this->{$method}($request, $value, $flags);
            }
        }
    }

    protected function visit_headers(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('headers value must be an array');
        }

        if ($flags & self::OPTIONS_AS_DEFAULTS) {
            // Merge headers in but do not overwrite existing values
            foreach ($value as $key => $header) {
                if (!$request->hasHeader($key)) {
                    $request->setHeader($key, $header);
                }
            }
        } else {
            $request->addHeaders($value);
        }
    }

    protected function visit_body(RequestInterface $request, $value, $flags)
    {
        if ($request instanceof EntityEnclosingRequestInterface) {
            $request->setBody($value);
        } else {
            throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request');
        }
    }

    protected function visit_allow_redirects(RequestInterface $request, $value, $flags)
    {
        if ($value === false) {
            $request->getParams()->set(RedirectPlugin::DISABLE, true);
        }
    }

    protected function visit_auth(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('auth value must be an array');
        }

        $request->setAuth($value[0], isset($value[1]) ? $value[1] : null, isset($value[2]) ? $value[2] : 'basic');
    }

    protected function visit_query(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('query value must be an array');
        }

        if ($flags & self::OPTIONS_AS_DEFAULTS) {
            // Merge query string values in but do not overwrite existing values
            $query = $request->getQuery();
            $query->overwriteWith(array_diff_key($value, $query->toArray()));
        } else {
            $request->getQuery()->overwriteWith($value);
        }
    }

    protected function visit_cookies(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('cookies value must be an array');
        }

        foreach ($value as $name => $v) {
            $request->addCookie($name, $v);
        }
    }

    protected function visit_events(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('events value must be an array');
        }

        foreach ($value as $name => $method) {
            if (is_array($method)) {
                $request->getEventDispatcher()->addListener($name, $method[0], $method[1]);
            } else {
                $request->getEventDispatcher()->addListener($name, $method);
            }
        }
    }

    protected function visit_plugins(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('plugins value must be an array');
        }

        foreach ($value as $plugin) {
            $request->addSubscriber($plugin);
        }
    }

    protected function visit_exceptions(RequestInterface $request, $value, $flags)
    {
        if ($value === false || $value === 0) {
            $dispatcher = $request->getEventDispatcher();
            foreach ($dispatcher->getListeners('request.error') as $listener) {
                if (is_array($listener) && $listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError') {
                    $dispatcher->removeListener('request.error', $listener);
                    break;
                }
            }
        }
    }

    protected function visit_save_to(RequestInterface $request, $value, $flags)
    {
        $request->setResponseBody($value);
    }

    protected function visit_params(RequestInterface $request, $value, $flags)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('params value must be an array');
        }

        $request->getParams()->overwriteWith($value);
    }

    protected function visit_timeout(RequestInterface $request, $value, $flags)
    {
        if (defined('CURLOPT_TIMEOUT_MS')) {
            $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000);
        } else {
            $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $value);
        }
    }

    protected function visit_connect_timeout(RequestInterface $request, $value, $flags)
    {
        if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
            $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, $value * 1000);
        } else {
            $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, $value);
        }
    }

    protected function visit_debug(RequestInterface $request, $value, $flags)
    {
        if ($value) {
            $request->getCurlOptions()->set(CURLOPT_VERBOSE, true);
        }
    }

    protected function visit_verify(RequestInterface $request, $value, $flags)
    {
        $curl = $request->getCurlOptions();
        if ($value === true || is_string($value)) {
            $curl[CURLOPT_SSL_VERIFYHOST] = 2;
            $curl[CURLOPT_SSL_VERIFYPEER] = true;
            if ($value !== true) {
                $curl[CURLOPT_CAINFO] = $value;
            }
        } elseif ($value === false) {
            unset($curl[CURLOPT_CAINFO]);
            $curl[CURLOPT_SSL_VERIFYHOST] = 0;
            $curl[CURLOPT_SSL_VERIFYPEER] = false;
        }
    }

    protected function visit_proxy(RequestInterface $request, $value, $flags)
    {
        $request->getCurlOptions()->set(CURLOPT_PROXY, $value, $flags);
    }

    protected function visit_cert(RequestInterface $request, $value, $flags)
    {
        if (is_array($value)) {
            $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value[0]);
            $request->getCurlOptions()->set(CURLOPT_SSLCERTPASSWD, $value[1]);
        } else {
            $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value);
        }
    }

    protected function visit_ssl_key(RequestInterface $request, $value, $flags)
    {
        if (is_array($value)) {
            $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value[0]);
            $request->getCurlOptions()->set(CURLOPT_SSLKEYPASSWD, $value[1]);
        } else {
            $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value);
        }
    }
}
<?php

namespace Guzzle\Http\Message;

/**
 * Request and response message interface
 */
interface MessageInterface
{
    /**
     * Get application and plugin specific parameters set on the message.
     *
     * @return \Guzzle\Common\Collection
     */
    public function getParams();

    /**
     * Add a header to an existing collection of headers.
     *
     * @param string $header Header name to add
     * @param string $value  Value of the header
     *
     * @return self
     */
    public function addHeader($header, $value);

    /**
     * Add and merge in an array of HTTP headers.
     *
     * @param array $headers Associative array of header data.
     *
     * @return self
     */
    public function addHeaders(array $headers);

    /**
     * Retrieve an HTTP header by name. Performs a case-insensitive search of all headers.
     *
     * @param string $header Header to retrieve.
     *
     * @return Header|null
     */
    public function getHeader($header);

    /**
     * Get all headers as a collection
     *
     * @return \Guzzle\Http\Message\Header\HeaderCollection
     */
    public function getHeaders();

    /**
     * Check if the specified header is present.
     *
     * @param string $header The header to check.
     *
     * @return bool
     */
    public function hasHeader($header);

    /**
     * Remove a specific HTTP header.
     *
     * @param string $header HTTP header to remove.
     *
     * @return self
     */
    public function removeHeader($header);

    /**
     * Set an HTTP header and overwrite any existing value for the header
     *
     * @param string $header Name of the header to set.
     * @param mixed  $value  Value to set.
     *
     * @return self
     */
    public function setHeader($header, $value);

    /**
     * Overwrite all HTTP headers with the supplied array of headers
     *
     * @param array $headers Associative array of header data.
     *
     * @return self
     */
    public function setHeaders(array $headers);

    /**
     * Get an array of message header lines (e.g. ["Host: example.com", ...])
     *
     * @return array
     */
    public function getHeaderLines();

    /**
     * Get the raw message headers as a string
     *
     * @return string
     */
    public function getRawHeaders();
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Http\EntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Http\Exception\RequestException;

/**
 * HTTP request that sends an entity-body in the request message (POST, PUT, PATCH, DELETE)
 */
class EntityEnclosingRequest extends Request implements EntityEnclosingRequestInterface
{
    /** @var int When the size of the body is greater than 1MB, then send Expect: 100-Continue */
    protected $expectCutoff = 1048576;

    /** @var EntityBodyInterface $body Body of the request */
    protected $body;

    /** @var QueryString POST fields to use in the EntityBody */
    protected $postFields;

    /** @var array POST files to send with the request */
    protected $postFiles = array();

    public function __construct($method, $url, $headers = array())
    {
        $this->postFields = new QueryString();
        parent::__construct($method, $url, $headers);
    }

    /**
     * @return string
     */
    public function __toString()
    {
        // Only attempt to include the POST data if it's only fields
        if (count($this->postFields) && empty($this->postFiles)) {
            return parent::__toString() . (string) $this->postFields;
        }

        return parent::__toString() . $this->body;
    }

    public function setState($state, array $context = array())
    {
        parent::setState($state, $context);
        if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) {
            $this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding');
        }

        return $this->state;
    }

    public function setBody($body, $contentType = null)
    {
        $this->body = EntityBody::factory($body);

        // Auto detect the Content-Type from the path of the request if possible
        if ($contentType === null && !$this->hasHeader('Content-Type')) {
            $contentType = $this->body->getContentType();
        }

        if ($contentType) {
            $this->setHeader('Content-Type', $contentType);
        }

        // Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects.
        if (!$this->body->isSeekable() && $this->expectCutoff !== false) {
            $this->setHeader('Expect', '100-Continue');
        }

        // Set the Content-Length header if it can be determined
        $size = $this->body->getContentLength();
        if ($size !== null && $size !== false) {
            $this->setHeader('Content-Length', $size);
            if ($size > $this->expectCutoff) {
                $this->setHeader('Expect', '100-Continue');
            }
        } elseif (!$this->hasHeader('Content-Length')) {
            if ('1.1' == $this->protocolVersion) {
                $this->setHeader('Transfer-Encoding', 'chunked');
            } else {
                throw new RequestException(
                    'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0'
                );
            }
        }

        return $this;
    }

    public function getBody()
    {
        return $this->body;
    }

    /**
     * Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header.
     *
     * @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data)
     *
     * @return self
     */
    public function setExpectHeaderCutoff($size)
    {
        $this->expectCutoff = $size;
        if ($size === false || !$this->body) {
            $this->removeHeader('Expect');
        } elseif ($this->body && $this->body->getSize() && $this->body->getSize() > $size) {
            $this->setHeader('Expect', '100-Continue');
        }

        return $this;
    }

    public function configureRedirects($strict = false, $maxRedirects = 5)
    {
        $this->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, $strict);
        if ($maxRedirects == 0) {
            $this->getParams()->set(RedirectPlugin::DISABLE, true);
        } else {
            $this->getParams()->set(RedirectPlugin::MAX_REDIRECTS, $maxRedirects);
        }

        return $this;
    }

    public function getPostField($field)
    {
        return $this->postFields->get($field);
    }

    public function getPostFields()
    {
        return $this->postFields;
    }

    public function setPostField($key, $value)
    {
        $this->postFields->set($key, $value);
        $this->processPostFields();

        return $this;
    }

    public function addPostFields($fields)
    {
        $this->postFields->merge($fields);
        $this->processPostFields();

        return $this;
    }

    public function removePostField($field)
    {
        $this->postFields->remove($field);
        $this->processPostFields();

        return $this;
    }

    public function getPostFiles()
    {
        return $this->postFiles;
    }

    public function getPostFile($fieldName)
    {
        return isset($this->postFiles[$fieldName]) ? $this->postFiles[$fieldName] : null;
    }

    public function removePostFile($fieldName)
    {
        unset($this->postFiles[$fieldName]);
        $this->processPostFields();

        return $this;
    }

    public function addPostFile($field, $filename = null, $contentType = null, $postname = null)
    {
        $data = null;

        if ($field instanceof PostFileInterface) {
            $data = $field;
        } elseif (is_array($filename)) {
            // Allow multiple values to be set in a single key
            foreach ($filename as $file) {
                $this->addPostFile($field, $file, $contentType);
            }
            return $this;
        } elseif (!is_string($filename)) {
            throw new RequestException('The path to a file must be a string');
        } elseif (!empty($filename)) {
            // Adding an empty file will cause cURL to error out
            $data = new PostFile($field, $filename, $contentType, $postname);
        }

        if ($data) {
            if (!isset($this->postFiles[$data->getFieldName()])) {
                $this->postFiles[$data->getFieldName()] = array($data);
            } else {
                $this->postFiles[$data->getFieldName()][] = $data;
            }
            $this->processPostFields();
        }

        return $this;
    }

    public function addPostFiles(array $files)
    {
        foreach ($files as $key => $file) {
            if ($file instanceof PostFileInterface) {
                $this->addPostFile($file, null, null, false);
            } elseif (is_string($file)) {
                // Convert non-associative array keys into 'file'
                if (is_numeric($key)) {
                    $key = 'file';
                }
                $this->addPostFile($key, $file, null, false);
            } else {
                throw new RequestException('File must be a string or instance of PostFileInterface');
            }
        }

        return $this;
    }

    /**
     * Determine what type of request should be sent based on post fields
     */
    protected function processPostFields()
    {
        if (!$this->postFiles) {
            $this->removeHeader('Expect')->setHeader('Content-Type', self::URL_ENCODED);
        } else {
            $this->setHeader('Content-Type', self::MULTIPART);
            if ($this->expectCutoff !== false) {
                $this->setHeader('Expect', '100-Continue');
            }
        }
    }
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Http\Exception\RequestException;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\QueryString;

/**
 * HTTP request that sends an entity-body in the request message (POST, PUT)
 */
interface EntityEnclosingRequestInterface extends RequestInterface
{
    const URL_ENCODED = 'application/x-www-form-urlencoded; charset=utf-8';
    const MULTIPART = 'multipart/form-data';

    /**
     * Set the body of the request
     *
     * @param string|resource|EntityBodyInterface $body        Body to use in the entity body of the request
     * @param string                              $contentType Content-Type to set. Leave null to use an existing
     *                                                         Content-Type or to guess the Content-Type
     * @return self
     * @throws RequestException if the protocol is < 1.1 and Content-Length can not be determined
     */
    public function setBody($body, $contentType = null);

    /**
     * Get the body of the request if set
     *
     * @return EntityBodyInterface|null
     */
    public function getBody();

    /**
     * Get a POST field from the request
     *
     * @param string $field Field to retrieve
     *
     * @return mixed|null
     */
    public function getPostField($field);

    /**
     * Get the post fields that will be used in the request
     *
     * @return QueryString
     */
    public function getPostFields();

    /**
     * Set a POST field value
     *
     * @param string $key   Key to set
     * @param string $value Value to set
     *
     * @return self
     */
    public function setPostField($key, $value);

    /**
     * Add POST fields to use in the request
     *
     * @param QueryString|array $fields POST fields
     *
     * @return self
     */
    public function addPostFields($fields);

    /**
     * Remove a POST field or file by name
     *
     * @param string $field Name of the POST field or file to remove
     *
     * @return self
     */
    public function removePostField($field);

    /**
     * Returns an associative array of POST field names to PostFileInterface objects
     *
     * @return array
     */
    public function getPostFiles();

    /**
     * Get a POST file from the request
     *
     * @param string $fieldName POST fields to retrieve
     *
     * @return array|null Returns an array wrapping an array of PostFileInterface objects
     */
    public function getPostFile($fieldName);

    /**
     * Remove a POST file from the request
     *
     * @param string $fieldName POST file field name to remove
     *
     * @return self
     */
    public function removePostFile($fieldName);

    /**
     * Add a POST file to the upload
     *
     * @param string $field       POST field to use (e.g. file). Used to reference content from the server.
     * @param string $filename    Full path to the file. Do not include the @ symbol.
     * @param string $contentType Optional Content-Type to add to the Content-Disposition.
     *                            Default behavior is to guess. Set to false to not specify.
     * @param string $postname    The name of the file, when posted. (e.g. rename the file)
     * @return self
     */
    public function addPostFile($field, $filename = null, $contentType = null, $postname = null);

    /**
     * Add POST files to use in the upload
     *
     * @param array $files An array of POST fields => filenames where filename can be a string or PostFileInterface
     *
     * @return self
     */
    public function addPostFiles(array $files);

    /**
     * Configure how redirects are handled for the request
     *
     * @param bool $strict       Set to true to follow strict RFC compliance when redirecting POST requests. Most
     *                           browsers with follow a 301-302 redirect for a POST request with a GET request. This is
     *                           the default behavior of Guzzle. Enable strict redirects to redirect these responses
     *                           with a POST rather than a GET request.
     * @param int  $maxRedirects Specify the maximum number of allowed redirects. Set to 0 to disable redirects.
     *
     * @return self
     */
    public function configureRedirects($strict = false, $maxRedirects = 5);
}
<?php

namespace Guzzle\Http\Message\Header;

use Guzzle\Common\ToArrayInterface;

interface HeaderInterface extends ToArrayInterface, \Countable, \IteratorAggregate
{
    /**
     * Convert the header to a string
     *
     * @return string
     */
    public function __toString();

    /**
     * Add a value to the list of header values
     *
     * @param string $value Value to add to the header
     *
     * @return self
     */
    public function add($value);

    /**
     * Get the name of the header
     *
     * @return string
     */
    public function getName();

    /**
     * Change the name of the header
     *
     * @param string $name Name to change to
     *
     * @return self
     */
    public function setName($name);

    /**
     * Change the glue used to implode the values
     *
     * @param string $glue Glue used to implode multiple values
     *
     * @return self
     */
    public function setGlue($glue);

    /**
     * Get the glue used to implode multiple values into a string
     *
     * @return string
     */
    public function getGlue();

    /**
     * Check if the collection of headers has a particular value
     *
     * @param string $searchValue Value to search for
     *
     * @return bool
     */
    public function hasValue($searchValue);

    /**
     * Remove a specific value from the header
     *
     * @param string $searchValue Value to remove
     *
     * @return self
     */
    public function removeValue($searchValue);

    /**
     * Parse a header containing ";" separated data into an array of associative arrays representing the header
     * key value pair data of the header. When a parameter does not contain a value, but just contains a key, this
     * function will inject a key with a '' string value.
     *
     * @return array
     */
    public function parseParams();
}
<?php

namespace Guzzle\Http\Message\Header;

use Guzzle\Common\ToArrayInterface;

/**
 * Provides a case-insensitive collection of headers
 */
class HeaderCollection implements \IteratorAggregate, \Countable, \ArrayAccess, ToArrayInterface
{
    /** @var array */
    protected $headers;

    public function __construct($headers = array())
    {
        $this->headers = $headers;
    }

    public function __clone()
    {
        foreach ($this->headers as &$header) {
            $header = clone $header;
        }
    }

    /**
     * Clears the header collection
     */
    public function clear()
    {
        $this->headers = array();
    }

    /**
     * Set a header on the collection
     *
     * @param HeaderInterface $header Header to add
     *
     * @return self
     */
    public function add(HeaderInterface $header)
    {
        $this->headers[strtolower($header->getName())] = $header;

        return $this;
    }

    /**
     * Get an array of header objects
     *
     * @return array
     */
    public function getAll()
    {
        return $this->headers;
    }

    /**
     * Alias of offsetGet
     */
    public function get($key)
    {
        return $this->offsetGet($key);
    }

    public function count()
    {
        return count($this->headers);
    }

    public function offsetExists($offset)
    {
        return isset($this->headers[strtolower($offset)]);
    }

    public function offsetGet($offset)
    {
        $l = strtolower($offset);

        return isset($this->headers[$l]) ? $this->headers[$l] : null;
    }

    public function offsetSet($offset, $value)
    {
        $this->add($value);
    }

    public function offsetUnset($offset)
    {
        unset($this->headers[strtolower($offset)]);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->headers);
    }

    public function toArray()
    {
        $result = array();
        foreach ($this->headers as $header) {
            $result[$header->getName()] = $header->toArray();
        }

        return $result;
    }
}
<?php

namespace Guzzle\Http\Message\Header;

use Guzzle\Http\Message\Header;

/**
 * Provides helpful functionality for link headers
 */
class Link extends Header
{
    /**
     * Add a link to the header
     *
     * @param string $url    Link URL
     * @param string $rel    Link rel
     * @param array  $params Other link parameters
     *
     * @return self
     */
    public function addLink($url, $rel, array $params = array())
    {
        $values = array("<{$url}>", "rel=\"{$rel}\"");

        foreach ($params as $k => $v) {
            $values[] = "{$k}=\"{$v}\"";
        }

        return $this->add(implode('; ', $values));
    }

    /**
     * Check if a specific link exists for a given rel attribute
     *
     * @param string $rel rel value
     *
     * @return bool
     */
    public function hasLink($rel)
    {
        return $this->getLink($rel) !== null;
    }

    /**
     * Get a specific link for a given rel attribute
     *
     * @param string $rel Rel value
     *
     * @return array|null
     */
    public function getLink($rel)
    {
        foreach ($this->getLinks() as $link) {
            if (isset($link['rel']) && $link['rel'] == $rel) {
                return $link;
            }
        }

        return null;
    }

    /**
     * Get an associative array of links
     *
     * For example:
     * Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg"
     *
     * <code>
     * var_export($response->getLinks());
     * array(
     *     array(
     *         'url' => 'http:/.../front.jpeg',
     *         'rel' => 'back',
     *         'type' => 'image/jpeg',
     *     )
     * )
     * </code>
     *
     * @return array
     */
    public function getLinks()
    {
        $links = $this->parseParams();

        foreach ($links as &$link) {
            $key = key($link);
            unset($link[$key]);
            $link['url'] = trim($key, '<> ');
        }

        return $links;
    }
}
<?php

namespace Guzzle\Http\Message\Header;

use Guzzle\Http\Message\Header;

/**
 * Provides helpful functionality for Cache-Control headers
 */
class CacheControl extends Header
{
    /** @var array */
    protected $directives;

    public function add($value)
    {
        parent::add($value);
        $this->directives = null;
    }

    public function removeValue($searchValue)
    {
        parent::removeValue($searchValue);
        $this->directives = null;
    }

    /**
     * Check if a specific cache control directive exists
     *
     * @param string $param Directive to retrieve
     *
     * @return bool
     */
    public function hasDirective($param)
    {
        $directives = $this->getDirectives();

        return isset($directives[$param]);
    }

    /**
     * Get a specific cache control directive
     *
     * @param string $param Directive to retrieve
     *
     * @return string|bool|null
     */
    public function getDirective($param)
    {
        $directives = $this->getDirectives();

        return isset($directives[$param]) ? $directives[$param] : null;
    }

    /**
     * Add a cache control directive
     *
     * @param string $param Directive to add
     * @param string $value Value to set
     *
     * @return self
     */
    public function addDirective($param, $value)
    {
        $directives = $this->getDirectives();
        $directives[$param] = $value;
        $this->updateFromDirectives($directives);

        return $this;
    }

    /**
     * Remove a cache control directive by name
     *
     * @param string $param Directive to remove
     *
     * @return self
     */
    public function removeDirective($param)
    {
        $directives = $this->getDirectives();
        unset($directives[$param]);
        $this->updateFromDirectives($directives);

        return $this;
    }

    /**
     * Get an associative array of cache control directives
     *
     * @return array
     */
    public function getDirectives()
    {
        if ($this->directives === null) {
            $this->directives = array();
            foreach ($this->parseParams() as $collection) {
                foreach ($collection as $key => $value) {
                    $this->directives[$key] = $value === '' ? true : $value;
                }
            }
        }

        return $this->directives;
    }

    /**
     * Updates the header value based on the parsed directives
     *
     * @param array $directives Array of cache control directives
     */
    protected function updateFromDirectives(array $directives)
    {
        $this->directives = $directives;
        $this->values = array();

        foreach ($directives as $key => $value) {
            $this->values[] = $value === true ? $key : "{$key}={$value}";
        }
    }
}
<?php

namespace Guzzle\Http\Message\Header;

use Guzzle\Http\Message\Header;

/**
 * Default header factory implementation
 */
class HeaderFactory implements HeaderFactoryInterface
{
    /** @var array */
    protected $mapping = array(
        'cache-control' => 'Guzzle\Http\Message\Header\CacheControl',
        'link'          => 'Guzzle\Http\Message\Header\Link',
    );

    public function createHeader($header, $value = null)
    {
        $lowercase = strtolower($header);

        return isset($this->mapping[$lowercase])
            ? new $this->mapping[$lowercase]($header, $value)
            : new Header($header, $value);
    }
}
<?php

namespace Guzzle\Http\Message\Header;

/**
 * Interface for creating headers
 */
interface HeaderFactoryInterface
{
    /**
     * Create a header from a header name and a single value
     *
     * @param string $header Name of the header to create
     * @param string $value  Value to set on the header
     *
     * @return HeaderInterface
     */
    public function createHeader($header, $value = null);
}
<?php

namespace Guzzle\Http\Message;

use Guzzle\Common\Collection;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Http\Url;

/**
 * Request factory used to create HTTP requests
 */
interface RequestFactoryInterface
{
    const OPTIONS_NONE = 0;
    const OPTIONS_AS_DEFAULTS = 1;

    /**
     * Create a new request based on an HTTP message
     *
     * @param string $message HTTP message as a string
     *
     * @return RequestInterface
     */
    public function fromMessage($message);

    /**
     * Create a request from URL parts as returned from parse_url()
     *
     * @param string $method HTTP method (GET, POST, PUT, HEAD, DELETE, etc)
     *
     * @param array $urlParts URL parts containing the same keys as parse_url()
     *     - scheme: e.g. http
     *     - host:   e.g. www.guzzle-project.com
     *     - port:   e.g. 80
     *     - user:   e.g. michael
     *     - pass:   e.g. rocks
     *     - path:   e.g. / OR /index.html
     *     - query:  after the question mark ?
     * @param array|Collection                          $headers         HTTP headers
     * @param string|resource|array|EntityBodyInterface $body            Body to send in the request
     * @param string                                    $protocol        Protocol (HTTP, SPYDY, etc)
     * @param string                                    $protocolVersion 1.0, 1.1, etc
     *
     * @return RequestInterface
     */
    public function fromParts(
        $method,
        array $urlParts,
        $headers = null,
        $body = null,
        $protocol = 'HTTP',
        $protocolVersion = '1.1'
    );

    /**
     * Create a new request based on the HTTP method
     *
     * @param string                                    $method  HTTP method (GET, POST, PUT, PATCH, HEAD, DELETE, ...)
     * @param string|Url                                $url     HTTP URL to connect to
     * @param array|Collection                          $headers HTTP headers
     * @param string|resource|array|EntityBodyInterface $body    Body to send in the request
     * @param array                                     $options Array of options to apply to the request
     *
     * @return RequestInterface
     */
    public function create($method, $url, $headers = null, $body = null, array $options = array());

    /**
     * Apply an associative array of options to the request
     *
     * @param RequestInterface $request Request to update
     * @param array            $options Options to use with the request. Available options are:
     *        "headers": Associative array of headers
     *        "query": Associative array of query string values to add to the request
     *        "body": Body of a request, including an EntityBody, string, or array when sending POST requests.
     *        "auth": Array of HTTP authentication parameters to use with the request. The array must contain the
     *            username in index [0], the password in index [2], and can optionally contain the authentication type
     *            in index [3]. The authentication types are: "Basic", "Digest", "NTLM", "Any" (defaults to "Basic").
     *        "cookies": Associative array of cookies
     *        "allow_redirects": Set to false to disable redirects
     *        "save_to": String, fopen resource, or EntityBody object used to store the body of the response
     *        "events": Associative array mapping event names to a closure or array of (priority, closure)
     *        "plugins": Array of plugins to add to the request
     *        "exceptions": Set to false to disable throwing exceptions on an HTTP level error (e.g. 404, 500, etc)
     *        "params": Set custom request data parameters on a request. (Note: these are not query string parameters)
     *        "timeout": Float describing the timeout of the request in seconds
     *        "connect_timeout": Float describing the number of seconds to wait while trying to connect. Use 0 to wait
     *            indefinitely.
     *        "verify": Set to true to enable SSL cert validation (the default), false to disable, or supply the path
     *            to a CA bundle to enable verification using a custom certificate.
     *        "cert": Set to a string to specify the path to a file containing a PEM formatted certificate. If a
     *            password is required, then set an array containing the path to the PEM file followed by the the
     *            password required for the certificate.
     *        "ssl_key": Specify the path to a file containing a private SSL key in PEM format. If a password is
     *            required, then set an array containing the path to the SSL key followed by the password required for
     *            the certificate.
     *        "proxy": Specify an HTTP proxy (e.g. "http://username:password@192.168.16.1:10")
     *        "debug": Set to true to display all data sent over the wire
     * @param int $flags Bitwise flags to apply when applying the options to the request. Defaults to no special
     *                   options. `1` (OPTIONS_AS_DEFAULTS): When specified, options will only update a request when
     *                   the value does not already exist on the request. This is only supported by "query" and
     *                   "headers". Other bitwise options may be added in the future.
     */
    public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE);
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Parses and generates URLs based on URL parts. In favor of performance, URL parts are not validated.
 */
class Url
{
    protected $scheme;
    protected $host;
    protected $port;
    protected $username;
    protected $password;
    protected $path = '';
    protected $fragment;

    /** @var QueryString Query part of the URL */
    protected $query;

    /**
     * Factory method to create a new URL from a URL string
     *
     * @param string $url Full URL used to create a Url object
     *
     * @return Url
     * @throws InvalidArgumentException
     */
    public static function factory($url)
    {
        static $defaults = array('scheme' => null, 'host' => null, 'path' => null, 'port' => null, 'query' => null,
            'user' => null, 'pass' => null, 'fragment' => null);

        if (false === ($parts = parse_url($url))) {
            throw new InvalidArgumentException('Was unable to parse malformed url: ' . $url);
        }

        $parts += $defaults;

        // Convert the query string into a QueryString object
        if ($parts['query'] || 0 !== strlen($parts['query'])) {
            $parts['query'] = QueryString::fromString($parts['query']);
        }

        return new static($parts['scheme'], $parts['host'], $parts['user'],
            $parts['pass'], $parts['port'], $parts['path'], $parts['query'],
            $parts['fragment']);
    }

    /**
     * Build a URL from parse_url parts. The generated URL will be a relative URL if a scheme or host are not provided.
     *
     * @param array $parts Array of parse_url parts
     *
     * @return string
     */
    public static function buildUrl(array $parts)
    {
        $url = $scheme = '';

        if (isset($parts['scheme'])) {
            $scheme = $parts['scheme'];
            $url .= $scheme . ':';
        }

        if (isset($parts['host'])) {
            $url .= '//';
            if (isset($parts['user'])) {
                $url .= $parts['user'];
                if (isset($parts['pass'])) {
                    $url .= ':' . $parts['pass'];
                }
                $url .=  '@';
            }

            $url .= $parts['host'];

            // Only include the port if it is not the default port of the scheme
            if (isset($parts['port'])
                && !(($scheme == 'http' && $parts['port'] == 80) || ($scheme == 'https' && $parts['port'] == 443))
            ) {
                $url .= ':' . $parts['port'];
            }
        }

        // Add the path component if present
        if (isset($parts['path']) && 0 !== strlen($parts['path'])) {
            // Always ensure that the path begins with '/' if set and something is before the path
            if ($url && $parts['path'][0] != '/' && substr($url, -1)  != '/') {
                $url .= '/';
            }
            $url .= $parts['path'];
        }

        // Add the query string if present
        if (isset($parts['query'])) {
            $url .= '?' . $parts['query'];
        }

        // Ensure that # is only added to the url if fragment contains anything.
        if (isset($parts['fragment'])) {
            $url .= '#' . $parts['fragment'];
        }

        return $url;
    }

    /**
     * Create a new URL from URL parts
     *
     * @param string                   $scheme   Scheme of the URL
     * @param string                   $host     Host of the URL
     * @param string                   $username Username of the URL
     * @param string                   $password Password of the URL
     * @param int                      $port     Port of the URL
     * @param string                   $path     Path of the URL
     * @param QueryString|array|string $query    Query string of the URL
     * @param string                   $fragment Fragment of the URL
     */
    public function __construct($scheme, $host, $username = null, $password = null, $port = null, $path = null, QueryString $query = null, $fragment = null)
    {
        $this->scheme = $scheme;
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
        $this->fragment = $fragment;
        if (!$query) {
            $this->query = new QueryString();
        } else {
            $this->setQuery($query);
        }
        $this->setPath($path);
    }

    /**
     * Clone the URL
     */
    public function __clone()
    {
        $this->query = clone $this->query;
    }

    /**
     * Returns the URL as a URL string
     *
     * @return string
     */
    public function __toString()
    {
        return self::buildUrl($this->getParts());
    }

    /**
     * Get the parts of the URL as an array
     *
     * @return array
     */
    public function getParts()
    {
        $query = (string) $this->query;

        return array(
            'scheme' => $this->scheme,
            'user' => $this->username,
            'pass' => $this->password,
            'host' => $this->host,
            'port' => $this->port,
            'path' => $this->getPath(),
            'query' => $query !== '' ? $query : null,
            'fragment' => $this->fragment,
        );
    }

    /**
     * Set the host of the request.
     *
     * @param string $host Host to set (e.g. www.yahoo.com, yahoo.com)
     *
     * @return Url
     */
    public function setHost($host)
    {
        if (strpos($host, ':') === false) {
            $this->host = $host;
        } else {
            list($host, $port) = explode(':', $host);
            $this->host = $host;
            $this->setPort($port);
        }

        return $this;
    }

    /**
     * Get the host part of the URL
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Set the scheme part of the URL (http, https, ftp, etc)
     *
     * @param string $scheme Scheme to set
     *
     * @return Url
     */
    public function setScheme($scheme)
    {
        if ($this->scheme == 'http' && $this->port == 80) {
            $this->port = null;
        } elseif ($this->scheme == 'https' && $this->port == 443) {
            $this->port = null;
        }

        $this->scheme = $scheme;

        return $this;
    }

    /**
     * Get the scheme part of the URL
     *
     * @return string
     */
    public function getScheme()
    {
        return $this->scheme;
    }

    /**
     * Set the port part of the URL
     *
     * @param int $port Port to set
     *
     * @return Url
     */
    public function setPort($port)
    {
        $this->port = $port;

        return $this;
    }

    /**
     * Get the port part of the URl. Will return the default port for a given scheme if no port has been set.
     *
     * @return int|null
     */
    public function getPort()
    {
        if ($this->port) {
            return $this->port;
        } elseif ($this->scheme == 'http') {
            return 80;
        } elseif ($this->scheme == 'https') {
            return 443;
        }

        return null;
    }

    /**
     * Set the path part of the URL
     *
     * @param array|string $path Path string or array of path segments
     *
     * @return Url
     */
    public function setPath($path)
    {
        static $pathReplace = array(' ' => '%20', '?' => '%3F');
        if (is_array($path)) {
            $path = '/' . implode('/', $path);
        }

        $this->path = strtr($path, $pathReplace);

        return $this;
    }

    /**
     * Normalize the URL so that double slashes and relative paths are removed
     *
     * @return Url
     */
    public function normalizePath()
    {
        if (!$this->path || $this->path == '/' || $this->path == '*') {
            return $this;
        }

        $results = array();
        $segments = $this->getPathSegments();
        foreach ($segments as $segment) {
            if ($segment == '..') {
                array_pop($results);
            } elseif ($segment != '.' && $segment != '') {
                $results[] = $segment;
            }
        }

        // Combine the normalized parts and add the leading slash if needed
        $this->path = ($this->path[0] == '/' ? '/' : '') . implode('/', $results);

        // Add the trailing slash if necessary
        if ($this->path != '/' && end($segments) == '') {
            $this->path .= '/';
        }

        return $this;
    }

    /**
     * Add a relative path to the currently set path.
     *
     * @param string $relativePath Relative path to add
     *
     * @return Url
     */
    public function addPath($relativePath)
    {
        if ($relativePath != '/' && is_string($relativePath) && strlen($relativePath) > 0) {
            // Add a leading slash if needed
            if ($relativePath[0] != '/') {
                $relativePath = '/' . $relativePath;
            }
            $this->setPath(str_replace('//', '/', $this->path . $relativePath));
        }

        return $this;
    }

    /**
     * Get the path part of the URL
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Get the path segments of the URL as an array
     *
     * @return array
     */
    public function getPathSegments()
    {
        return array_slice(explode('/', $this->getPath()), 1);
    }

    /**
     * Set the password part of the URL
     *
     * @param string $password Password to set
     *
     * @return Url
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get the password part of the URL
     *
     * @return null|string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set the username part of the URL
     *
     * @param string $username Username to set
     *
     * @return Url
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get the username part of the URl
     *
     * @return null|string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Get the query part of the URL as a QueryString object
     *
     * @return QueryString
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Set the query part of the URL
     *
     * @param QueryString|string|array $query Query to set
     *
     * @return Url
     */
    public function setQuery($query)
    {
        if (is_string($query)) {
            $output = null;
            parse_str($query, $output);
            $this->query = new QueryString($output);
        } elseif (is_array($query)) {
            $this->query = new QueryString($query);
        } elseif ($query instanceof QueryString) {
            $this->query = $query;
        }

        return $this;
    }

    /**
     * Get the fragment part of the URL
     *
     * @return null|string
     */
    public function getFragment()
    {
        return $this->fragment;
    }

    /**
     * Set the fragment part of the URL
     *
     * @param string $fragment Fragment to set
     *
     * @return Url
     */
    public function setFragment($fragment)
    {
        $this->fragment = $fragment;

        return $this;
    }

    /**
     * Check if this is an absolute URL
     *
     * @return bool
     */
    public function isAbsolute()
    {
        return $this->scheme && $this->host;
    }

    /**
     * Combine the URL with another URL. Follows the rules specific in RFC 3986 section 5.4.
     *
     * @param string $url           Relative URL to combine with
     * @param bool   $strictRfc3986 Set to true to use strict RFC 3986 compliance when merging paths. When first
     *                              released, Guzzle used an incorrect algorithm for combining relative URL paths. In
     *                              order to not break users, we introduced this flag to allow the merging of URLs based
     *                              on strict RFC 3986 section 5.4.1. This means that "http://a.com/foo/baz" merged with
     *                              "bar" would become "http://a.com/foo/bar". When this value is set to false, it would
     *                              become "http://a.com/foo/baz/bar".
     * @return Url
     * @throws InvalidArgumentException
     * @link http://tools.ietf.org/html/rfc3986#section-5.4
     */
    public function combine($url, $strictRfc3986 = false)
    {
        $url = self::factory($url);

        // Use the more absolute URL as the base URL
        if (!$this->isAbsolute() && $url->isAbsolute()) {
            $url = $url->combine($this);
        }

        // Passing a URL with a scheme overrides everything
        if ($buffer = $url->getScheme()) {
            $this->scheme = $buffer;
            $this->host = $url->getHost();
            $this->port = $url->getPort();
            $this->username = $url->getUsername();
            $this->password = $url->getPassword();
            $this->path = $url->getPath();
            $this->query = $url->getQuery();
            $this->fragment = $url->getFragment();
            return $this;
        }

        // Setting a host overrides the entire rest of the URL
        if ($buffer = $url->getHost()) {
            $this->host = $buffer;
            $this->port = $url->getPort();
            $this->username = $url->getUsername();
            $this->password = $url->getPassword();
            $this->path = $url->getPath();
            $this->query = $url->getQuery();
            $this->fragment = $url->getFragment();
            return $this;
        }

        $path = $url->getPath();
        $query = $url->getQuery();

        if (!$path) {
            if (count($query)) {
                $this->addQuery($query, $strictRfc3986);
            }
        } else {
            if ($path[0] == '/') {
                $this->path = $path;
            } elseif ($strictRfc3986) {
                $this->path .= '/../' . $path;
            } else {
                $this->path .= '/' . $path;
            }
            $this->normalizePath();
            $this->addQuery($query, $strictRfc3986);
        }

        $this->fragment = $url->getFragment();

        return $this;
    }

    private function addQuery(QueryString $new, $strictRfc386)
    {
        if (!$strictRfc386) {
            $new->merge($this->query);
        }

        $this->query = $new;
    }
}
<?php

namespace Guzzle\Http\Curl;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Response;

/**
 * Mediator between curl handles and request objects
 */
class RequestMediator
{
    /** @var RequestInterface */
    protected $request;

    /** @var bool Whether or not to emit read/write events */
    protected $emitIo;

    /**
     * @param RequestInterface $request Request to mediate
     * @param bool             $emitIo  Set to true to dispatch events on input and output
     */
    public function __construct(RequestInterface $request, $emitIo = false)
    {
        $this->request = $request;
        $this->emitIo = $emitIo;
    }

    /**
     * Receive a response header from curl
     *
     * @param resource $curl   Curl handle
     * @param string   $header Received header
     *
     * @return int
     */
    public function receiveResponseHeader($curl, $header)
    {
        static $normalize = array("\r", "\n");
        $length = strlen($header);
        $header = str_replace($normalize, '', $header);

        if (strpos($header, 'HTTP/') === 0) {

            $startLine = explode(' ', $header, 3);
            $code = $startLine[1];
            $status = isset($startLine[2]) ? $startLine[2] : '';

            // Only download the body of the response to the specified response
            // body when a successful response is received.
            if ($code >= 200 && $code < 300) {
                $body = $this->request->getResponseBody();
            } else {
                $body = EntityBody::factory();
            }

            $response = new Response($code, null, $body);
            $response->setStatus($code, $status);
            $this->request->startResponse($response);

            $this->request->dispatch('request.receive.status_line', array(
                'request'       => $this,
                'line'          => $header,
                'status_code'   => $code,
                'reason_phrase' => $status
            ));

        } elseif ($pos = strpos($header, ':')) {
            $this->request->getResponse()->addHeader(
                trim(substr($header, 0, $pos)),
                trim(substr($header, $pos + 1))
            );
        }

        return $length;
    }

    /**
     * Received a progress notification
     *
     * @param int        $downloadSize Total download size
     * @param int        $downloaded   Amount of bytes downloaded
     * @param int        $uploadSize   Total upload size
     * @param int        $uploaded     Amount of bytes uploaded
     * @param resource   $handle       CurlHandle object
     */
    public function progress($downloadSize, $downloaded, $uploadSize, $uploaded, $handle = null)
    {
        $this->request->dispatch('curl.callback.progress', array(
            'request'       => $this->request,
            'handle'        => $handle,
            'download_size' => $downloadSize,
            'downloaded'    => $downloaded,
            'upload_size'   => $uploadSize,
            'uploaded'      => $uploaded
        ));
    }

    /**
     * Write data to the response body of a request
     *
     * @param resource $curl  Curl handle
     * @param string   $write Data that was received
     *
     * @return int
     */
    public function writeResponseBody($curl, $write)
    {
        if ($this->emitIo) {
            $this->request->dispatch('curl.callback.write', array(
                'request' => $this->request,
                'write'   => $write
            ));
        }

        if ($response = $this->request->getResponse()) {
            return $response->getBody()->write($write);
        } else {
            // Unexpected data received before response headers - abort transfer
            return 0;
        }
    }

    /**
     * Read data from the request body and send it to curl
     *
     * @param resource $ch     Curl handle
     * @param resource $fd     File descriptor
     * @param int      $length Amount of data to read
     *
     * @return string
     */
    public function readRequestBody($ch, $fd, $length)
    {
        if (!($body = $this->request->getBody())) {
            return '';
        }

        $read = (string) $body->read($length);
        if ($this->emitIo) {
            $this->request->dispatch('curl.callback.read', array('request' => $this->request, 'read' => $read));
        }

        return $read;
    }
}
<?php

namespace Guzzle\Http\Curl;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\EntityEnclosingRequest;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Parser\ParserRegistry;
use Guzzle\Http\Url;

/**
 * Immutable wrapper for a cURL handle
 */
class CurlHandle
{
    const BODY_AS_STRING = 'body_as_string';
    const PROGRESS = 'progress';
    const DEBUG = 'debug';

    /** @var Collection Curl options */
    protected $options;

    /** @var resource Curl resource handle */
    protected $handle;

    /** @var int CURLE_* error */
    protected $errorNo = CURLE_OK;

    /**
     * Factory method to create a new curl handle based on an HTTP request.
     *
     * There are some helpful options you can set to enable specific behavior:
     * - debug:    Set to true to enable cURL debug functionality to track the actual headers sent over the wire.
     * - progress: Set to true to enable progress function callbacks.
     *
     * @param RequestInterface $request Request
     *
     * @return CurlHandle
     * @throws RuntimeException
     */
    public static function factory(RequestInterface $request)
    {
        $requestCurlOptions = $request->getCurlOptions();
        $mediator = new RequestMediator($request, $requestCurlOptions->get('emit_io'));
        $tempContentLength = null;
        $method = $request->getMethod();
        $bodyAsString = $requestCurlOptions->get(self::BODY_AS_STRING);

        // Prepare url
        $url = (string)$request->getUrl();
        if(($pos = strpos($url, '#')) !== false ){
            // strip fragment from url
            $url = substr($url, 0, $pos);
        }

        // Array of default cURL options.
        $curlOptions = array(
            CURLOPT_URL            => $url,
            CURLOPT_CONNECTTIMEOUT => 150,
            CURLOPT_RETURNTRANSFER => false,
            CURLOPT_HEADER         => false,
            CURLOPT_PORT           => $request->getPort(),
            CURLOPT_HTTPHEADER     => array(),
            CURLOPT_WRITEFUNCTION  => array($mediator, 'writeResponseBody'),
            CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'),
            CURLOPT_HTTP_VERSION   => $request->getProtocolVersion() === '1.0'
                ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1,
            // Verifies the authenticity of the peer's certificate
            CURLOPT_SSL_VERIFYPEER => 1,
            // Certificate must indicate that the server is the server to which you meant to connect
            CURLOPT_SSL_VERIFYHOST => 2
        );

        if (defined('CURLOPT_PROTOCOLS')) {
            // Allow only HTTP and HTTPS protocols
            $curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
        }

        // Add CURLOPT_ENCODING if Accept-Encoding header is provided
        if ($acceptEncodingHeader = $request->getHeader('Accept-Encoding')) {
            $curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader;
            // Let cURL set the Accept-Encoding header, prevents duplicate values
            $request->removeHeader('Accept-Encoding');
        }

        // Enable curl debug information if the 'debug' param was set
        if ($requestCurlOptions->get('debug')) {
            $curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+');
            // @codeCoverageIgnoreStart
            if (false === $curlOptions[CURLOPT_STDERR]) {
                throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR');
            }
            // @codeCoverageIgnoreEnd
            $curlOptions[CURLOPT_VERBOSE] = true;
        }

        // Specify settings according to the HTTP method
        if ($method == 'GET') {
            $curlOptions[CURLOPT_HTTPGET] = true;
        } elseif ($method == 'HEAD') {
            $curlOptions[CURLOPT_NOBODY] = true;
            // HEAD requests do not use a write function
            unset($curlOptions[CURLOPT_WRITEFUNCTION]);
        } elseif (!($request instanceof EntityEnclosingRequest)) {
            $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
        } else {

            $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;

            // Handle sending raw bodies in a request
            if ($request->getBody()) {
                // You can send the body as a string using curl's CURLOPT_POSTFIELDS
                if ($bodyAsString) {
                    $curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody();
                    // Allow curl to add the Content-Length for us to account for the times when
                    // POST redirects are followed by GET requests
                    if ($tempContentLength = $request->getHeader('Content-Length')) {
                        $tempContentLength = (int) (string) $tempContentLength;
                    }
                    // Remove the curl generated Content-Type header if none was set manually
                    if (!$request->hasHeader('Content-Type')) {
                        $curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:';
                    }
                } else {
                    $curlOptions[CURLOPT_UPLOAD] = true;
                    // Let cURL handle setting the Content-Length header
                    if ($tempContentLength = $request->getHeader('Content-Length')) {
                        $tempContentLength = (int) (string) $tempContentLength;
                        $curlOptions[CURLOPT_INFILESIZE] = $tempContentLength;
                    }
                    // Add a callback for curl to read data to send with the request only if a body was specified
                    $curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody');
                    // Attempt to seek to the start of the stream
                    $request->getBody()->seek(0);
                }

            } else {

                // Special handling for POST specific fields and files
                $postFields = false;
                if (count($request->getPostFiles())) {
                    $postFields = $request->getPostFields()->useUrlEncoding(false)->urlEncode();
                    foreach ($request->getPostFiles() as $key => $data) {
                        $prefixKeys = count($data) > 1;
                        foreach ($data as $index => $file) {
                            // Allow multiple files in the same key
                            $fieldKey = $prefixKeys ? "{$key}[{$index}]" : $key;
                            $postFields[$fieldKey] = $file->getCurlValue();
                        }
                    }
                } elseif (count($request->getPostFields())) {
                    $postFields = (string) $request->getPostFields()->useUrlEncoding(true);
                }

                if ($postFields !== false) {
                    if ($method == 'POST') {
                        unset($curlOptions[CURLOPT_CUSTOMREQUEST]);
                        $curlOptions[CURLOPT_POST] = true;
                    }
                    $curlOptions[CURLOPT_POSTFIELDS] = $postFields;
                    $request->removeHeader('Content-Length');
                }
            }

            // If the Expect header is not present, prevent curl from adding it
            if (!$request->hasHeader('Expect')) {
                $curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:';
            }
        }

        // If a Content-Length header was specified but we want to allow curl to set one for us
        if (null !== $tempContentLength) {
            $request->removeHeader('Content-Length');
        }

        // Set custom cURL options
        foreach ($requestCurlOptions->toArray() as $key => $value) {
            if (is_numeric($key)) {
                $curlOptions[$key] = $value;
            }
        }

        // Do not set an Accept header by default
        if (!isset($curlOptions[CURLOPT_ENCODING])) {
            $curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:';
        }

        // Add any custom headers to the request. Empty headers will cause curl to not send the header at all.
        foreach ($request->getHeaderLines() as $line) {
            $curlOptions[CURLOPT_HTTPHEADER][] = $line;
        }

        // Add the content-length header back if it was temporarily removed
        if (null !== $tempContentLength) {
            $request->setHeader('Content-Length', $tempContentLength);
        }

        // Apply the options to a new cURL handle.
        $handle = curl_init();
        // Enable the progress function if the 'progress' param was set
        if ($requestCurlOptions->get('progress')) {
            // Wrap the function in a function that provides the curl handle to the mediator's progress function
            // Using this rather than injecting the handle into the mediator prevents a circular reference
            $curlOptions[CURLOPT_PROGRESSFUNCTION] = function () use ($mediator, $handle) {
                $args = func_get_args();
                $args[] = $handle;

                // PHP 5.5 pushed the handle onto the start of the args
                if (is_resource($args[0])) {
                    array_shift($args);
                }

                call_user_func_array(array($mediator, 'progress'), $args);
            };
            $curlOptions[CURLOPT_NOPROGRESS] = false;
        }

        curl_setopt_array($handle, $curlOptions);

        return new static($handle, $curlOptions);
    }

    /**
     * Construct a new CurlHandle object that wraps a cURL handle
     *
     * @param resource         $handle  Configured cURL handle resource
     * @param Collection|array $options Curl options to use with the handle
     *
     * @throws InvalidArgumentException
     */
    public function __construct($handle, $options)
    {
        if ( $handle === null) {
            printf("this is get _class");
            printf(get_class($handle));
            throw new InvalidArgumentException('Invalid handle provided');
        }
        if (is_array($options)) {
            $this->options = new Collection($options);
        } elseif ($options instanceof Collection) {
            $this->options = $options;
        } else {
            throw new InvalidArgumentException('Expected array or Collection');
        }
        $this->handle = $handle;
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Close the curl handle
     */
    public function close()
    {
        if ($this->handle !== null) {
            curl_close($this->handle);
            unset($this->handle);
        }
        $this->handle = null;
    }

    /**
     * Check if the handle is available and still OK
     *
     * @return bool
     */
    public function isAvailable()
    {
        return $this->handle !== null;
    }

    /**
     * Get the last error that occurred on the cURL handle
     *
     * @return string
     */
    public function getError()
    {
        return $this->isAvailable() ? curl_error($this->handle) : '';
    }

    /**
     * Get the last error number that occurred on the cURL handle
     *
     * @return int
     */
    public function getErrorNo()
    {
        if ($this->errorNo) {
            return $this->errorNo;
        }

        return $this->isAvailable() ? curl_errno($this->handle) : CURLE_OK;
    }

    /**
     * Set the curl error number
     *
     * @param int $error Error number to set
     *
     * @return CurlHandle
     */
    public function setErrorNo($error)
    {
        $this->errorNo = $error;

        return $this;
    }

    /**
     * Get cURL curl_getinfo data
     *
     * @param int $option Option to retrieve. Pass null to retrieve all data as an array.
     *
     * @return array|mixed
     */
    public function getInfo($option = null)
    {
        if ($this->handle === null) {
            return null;
        }

        if (null !== $option) {
            return curl_getinfo($this->handle, $option) ?: null;
        }

        return curl_getinfo($this->handle) ?: array();
    }

    /**
     * Get the stderr output
     *
     * @param bool $asResource Set to TRUE to get an fopen resource
     *
     * @return string|resource|null
     */
    public function getStderr($asResource = false)
    {
        $stderr = $this->getOptions()->get(CURLOPT_STDERR);
        if (!$stderr) {
            return null;
        }

        if ($asResource) {
            return $stderr;
        }

        fseek($stderr, 0);
        $e = stream_get_contents($stderr);
        fseek($stderr, 0, SEEK_END);

        return $e;
    }

    /**
     * Get the URL that this handle is connecting to
     *
     * @return Url
     */
    public function getUrl()
    {
        return Url::factory($this->options->get(CURLOPT_URL));
    }

    /**
     * Get the wrapped curl handle
     *
     * @return resource|null Returns the cURL handle or null if it was closed
     */
    public function getHandle()
    {
        return $this->isAvailable() ? $this->handle : null;
    }

    /**
     * Get the cURL setopt options of the handle. Changing values in the return object will have no effect on the curl
     * handle after it is created.
     *
     * @return Collection
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Update a request based on the log messages of the CurlHandle
     *
     * @param RequestInterface $request Request to update
     */
    public function updateRequestFromTransfer(RequestInterface $request)
    {
        if (!$request->getResponse()) {
            return;
        }

        // Update the transfer stats of the response
        $request->getResponse()->setInfo($this->getInfo());

        if (!$log = $this->getStderr(true)) {
            return;
        }

        // Parse the cURL stderr output for outgoing requests
        $headers = '';
        fseek($log, 0);
        while (($line = fgets($log)) !== false) {
            if ($line && $line[0] == '>') {
                $headers = substr(trim($line), 2) . "\r\n";
                while (($line = fgets($log)) !== false) {
                    if ($line[0] == '*' || $line[0] == '<') {
                        break;
                    } else {
                        $headers .= trim($line) . "\r\n";
                    }
                }
            }
        }

        // Add request headers to the request exactly as they were sent
        if ($headers) {
            $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($headers);
            if (!empty($parsed['headers'])) {
                $request->setHeaders(array());
                foreach ($parsed['headers'] as $name => $value) {
                    $request->setHeader($name, $value);
                }
            }
            if (!empty($parsed['version'])) {
                $request->setProtocolVersion($parsed['version']);
            }
        }
    }

    /**
     * Parse the config and replace curl.* configurators into the constant based values so it can be used elsewhere
     *
     * @param array|Collection $config The configuration we want to parse
     *
     * @return array
     */
    public static function parseCurlConfig($config)
    {
        $curlOptions = array();
        foreach ($config as $key => $value) {
            if (is_string($key) && defined($key)) {
                // Convert constants represented as string to constant int values
                $key = constant($key);
            }
            if (is_string($value) && defined($value)) {
                $value = constant($value);
            }
            $curlOptions[$key] = $value;
        }

        return $curlOptions;
    }
}
<?php

namespace Guzzle\Http\Curl;

/**
 * Class used for querying curl_version data
 */
class CurlVersion
{
    /** @var array curl_version() information */
    protected $version;

    /** @var CurlVersion */
    protected static $instance;

    /** @var string Default user agent */
    protected $userAgent;

    /**
     * @return CurlVersion
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Get all of the curl_version() data
     *
     * @return array
     */
    public function getAll()
    {
        if (!$this->version) {
            $this->version = curl_version();
        }

        return $this->version;
    }

    /**
     * Get a specific type of curl information
     *
     * @param string $type Version information to retrieve. This value is one of:
     *     - version_number:     cURL 24 bit version number
     *     - version:            cURL version number, as a string
     *     - ssl_version_number: OpenSSL 24 bit version number
     *     - ssl_version:        OpenSSL version number, as a string
     *     - libz_version:       zlib version number, as a string
     *     - host:               Information about the host where cURL was built
     *     - features:           A bitmask of the CURL_VERSION_XXX constants
     *     - protocols:          An array of protocols names supported by cURL
     *
     * @return string|float|bool if the $type is found, and false if not found
     */
    public function get($type)
    {
        $version = $this->getAll();

        return isset($version[$type]) ? $version[$type] : false;
    }
}
<?php

namespace Guzzle\Http\Curl;

use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Common\Event;
use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Exception\RequestException;

/**
 * Send {@see RequestInterface} objects in parallel using curl_multi
 */
class CurlMulti extends AbstractHasDispatcher implements CurlMultiInterface
{
    /** @var resource cURL multi handle. */
    protected $multiHandle;

    /** @var array Attached {@see RequestInterface} objects. */
    protected $requests;

    /** @var \SplObjectStorage RequestInterface to CurlHandle hash */
    protected $handles;

    /** @var array Hash mapping curl handle resource IDs to request objects */
    protected $resourceHash;

    /** @var array Queued exceptions */
    protected $exceptions = array();

    /** @var array Requests that succeeded */
    protected $successful = array();

    /** @var array cURL multi error values and codes */
    protected $multiErrors = array(
        CURLM_BAD_HANDLE      => array('CURLM_BAD_HANDLE', 'The passed-in handle is not a valid CURLM handle.'),
        CURLM_BAD_EASY_HANDLE => array('CURLM_BAD_EASY_HANDLE', "An easy handle was not good/valid. It could mean that it isn't an easy handle at all, or possibly that the handle already is in used by this or another multi handle."),
        CURLM_OUT_OF_MEMORY   => array('CURLM_OUT_OF_MEMORY', 'You are doomed.'),
        CURLM_INTERNAL_ERROR  => array('CURLM_INTERNAL_ERROR', 'This can only be returned if libcurl bugs. Please report it to us!')
    );

    /** @var float */
    protected $selectTimeout;

    public function __construct($selectTimeout = 1.0)
    {
        $this->selectTimeout = $selectTimeout;
        $this->multiHandle = curl_multi_init();
        // @codeCoverageIgnoreStart
        if ($this->multiHandle === false) {
            throw new CurlException('Unable to create multi handle');
        }
        // @codeCoverageIgnoreEnd
        $this->reset();
    }

    public function __destruct()
    {
        if ($this->multiHandle !== null) {
            curl_multi_close($this->multiHandle);
        }
    }

    public function add(RequestInterface $request)
    {
        $this->requests[] = $request;
        // If requests are currently transferring and this is async, then the
        // request must be prepared now as the send() method is not called.
        $this->beforeSend($request);
        $this->dispatch(self::ADD_REQUEST, array('request' => $request));

        return $this;
    }

    public function all()
    {
        return $this->requests;
    }

    public function remove(RequestInterface $request)
    {
        $this->removeHandle($request);
        if (($index = array_search($request, $this->requests, true)) !== false) {
            $request = $this->requests[$index];
            unset($this->requests[$index]);
            $this->requests = array_values($this->requests);
            $this->dispatch(self::REMOVE_REQUEST, array('request' => $request));
            return true;
        }

        return false;
    }

    public function reset($hard = false)
    {
        // Remove each request
        if ($this->requests) {
            foreach ($this->requests as $request) {
                $this->remove($request);
            }
        }

        $this->handles = new \SplObjectStorage();
        $this->requests = $this->resourceHash = $this->exceptions = $this->successful = array();
    }

    public function send()
    {
        $this->perform();
        $exceptions = $this->exceptions;
        $successful = $this->successful;
        $this->reset();

        if ($exceptions) {
            $this->throwMultiException($exceptions, $successful);
        }
    }

    public function count()
    {
        return count($this->requests);
    }

    /**
     * Build and throw a MultiTransferException
     *
     * @param array $exceptions Exceptions encountered
     * @param array $successful Successful requests
     * @throws MultiTransferException
     */
    protected function throwMultiException(array $exceptions, array $successful)
    {
        $multiException = new MultiTransferException('Errors during multi transfer');

        while ($e = array_shift($exceptions)) {
            $multiException->addFailedRequestWithException($e['request'], $e['exception']);
        }

        // Add successful requests
        foreach ($successful as $request) {
            if (!$multiException->containsRequest($request)) {
                $multiException->addSuccessfulRequest($request);
            }
        }

        throw $multiException;
    }

    /**
     * Prepare for sending
     *
     * @param RequestInterface $request Request to prepare
     * @throws \Exception on error preparing the request
     */
    protected function beforeSend(RequestInterface $request)
    {
        try {
            $state = $request->setState(RequestInterface::STATE_TRANSFER);
            if ($state == RequestInterface::STATE_TRANSFER) {
                $this->addHandle($request);
            } else {
                // Requests might decide they don't need to be sent just before
                // transfer (e.g. CachePlugin)
                $this->remove($request);
                if ($state == RequestInterface::STATE_COMPLETE) {
                    $this->successful[] = $request;
                }
            }
        } catch (\Exception $e) {
            // Queue the exception to be thrown when sent
            $this->removeErroredRequest($request, $e);
        }
    }

    private function addHandle(RequestInterface $request)
    {
        $handle = $this->createCurlHandle($request)->getHandle();
        $this->checkCurlResult(
            curl_multi_add_handle($this->multiHandle, $handle)
        );
    }

    /**
     * Create a curl handle for a request
     *
     * @param RequestInterface $request Request
     *
     * @return CurlHandle
     */
    protected function createCurlHandle(RequestInterface $request)
    {
        $wrapper = CurlHandle::factory($request);
        $this->handles[$request] = $wrapper;
        $this->resourceHash[(int) $wrapper->getHandle()] = $request;

        return $wrapper;
    }

    /**
     * Get the data from the multi handle
     */
    protected function perform()
    {
        $event = new Event(array('curl_multi' => $this));

        while ($this->requests) {
            // Notify each request as polling
            $blocking = $total = 0;
            foreach ($this->requests as $request) {
                ++$total;
                $event['request'] = $request;
                $request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event);
                // The blocking variable just has to be non-falsey to block the loop
                if ($request->getParams()->hasKey(self::BLOCKING)) {
                    ++$blocking;
                }
            }
            if ($blocking == $total) {
                // Sleep to prevent eating CPU because no requests are actually pending a select call
                usleep(500);
            } else {
                $this->executeHandles();
            }
        }
    }

    /**
     * Execute and select curl handles
     */
    private function executeHandles()
    {
        // The first curl_multi_select often times out no matter what, but is usually required for fast transfers
        $selectTimeout = 0.001;
        $active = false;
        do {
            while (($mrc = curl_multi_exec($this->multiHandle, $active)) == CURLM_CALL_MULTI_PERFORM);
            $this->checkCurlResult($mrc);
            $this->processMessages();
            if ($active && curl_multi_select($this->multiHandle, $selectTimeout) === -1) {
                // Perform a usleep if a select returns -1: https://bugs.php.net/bug.php?id=61141
                usleep(150);
            }
            $selectTimeout = $this->selectTimeout;
        } while ($active);
    }

    /**
     * Process any received curl multi messages
     */
    private function processMessages()
    {
        while ($done = curl_multi_info_read($this->multiHandle)) {
            $request = $this->resourceHash[(int) $done['handle']];
            try {
                $this->processResponse($request, $this->handles[$request], $done);
                $this->successful[] = $request;
            } catch (\Exception $e) {
                $this->removeErroredRequest($request, $e);
            }
        }
    }

    /**
     * Remove a request that encountered an exception
     *
     * @param RequestInterface $request Request to remove
     * @param \Exception       $e       Exception encountered
     */
    protected function removeErroredRequest(RequestInterface $request, \Exception $e = null)
    {
        $this->exceptions[] = array('request' => $request, 'exception' => $e);
        $this->remove($request);
        $this->dispatch(self::MULTI_EXCEPTION, array('exception' => $e, 'all_exceptions' => $this->exceptions));
    }

    /**
     * Check for errors and fix headers of a request based on a curl response
     *
     * @param RequestInterface $request Request to process
     * @param CurlHandle       $handle  Curl handle object
     * @param array            $curl    Array returned from curl_multi_info_read
     *
     * @throws CurlException on Curl error
     */
    protected function processResponse(RequestInterface $request, CurlHandle $handle, array $curl)
    {
        // Set the transfer stats on the response
        $handle->updateRequestFromTransfer($request);
        // Check if a cURL exception occurred, and if so, notify things
        $curlException = $this->isCurlException($request, $handle, $curl);

        // Always remove completed curl handles.  They can be added back again
        // via events if needed (e.g. ExponentialBackoffPlugin)
        $this->removeHandle($request);

        if (!$curlException) {
            if ($this->validateResponseWasSet($request)) {
                $state = $request->setState(
                    RequestInterface::STATE_COMPLETE,
                    array('handle' => $handle)
                );
                // Only remove the request if it wasn't resent as a result of
                // the state change
                if ($state != RequestInterface::STATE_TRANSFER) {
                    $this->remove($request);
                }
            }
            return;
        }

        // Set the state of the request to an error
        $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $curlException));
        // Allow things to ignore the error if possible
        if ($state != RequestInterface::STATE_TRANSFER) {
            $this->remove($request);
        }

        // The error was not handled, so fail
        if ($state == RequestInterface::STATE_ERROR) {
            /** @var CurlException $curlException */
            throw $curlException;
        }
    }

    /**
     * Remove a curl handle from the curl multi object
     *
     * @param RequestInterface $request Request that owns the handle
     */
    protected function removeHandle(RequestInterface $request)
    {
        if (isset($this->handles[$request])) {
            $handle = $this->handles[$request];
            curl_multi_remove_handle($this->multiHandle, $handle->getHandle());
            unset($this->handles[$request]);
            unset($this->resourceHash[(int) $handle->getHandle()]);
            $handle->close();
        }
    }

    /**
     * Check if a cURL transfer resulted in what should be an exception
     *
     * @param RequestInterface $request Request to check
     * @param CurlHandle       $handle  Curl handle object
     * @param array            $curl    Array returned from curl_multi_info_read
     *
     * @return CurlException|bool
     */
    private function isCurlException(RequestInterface $request, CurlHandle $handle, array $curl)
    {
        if (CURLM_OK == $curl['result'] || CURLM_CALL_MULTI_PERFORM == $curl['result']) {
            return false;
        }

        $handle->setErrorNo($curl['result']);
        $e = new CurlException(sprintf('[curl] %s: %s [url] %s',
            $handle->getErrorNo(), $handle->getError(), $handle->getUrl()));
        $e->setCurlHandle($handle)
            ->setRequest($request)
            ->setCurlInfo($handle->getInfo())
            ->setError($handle->getError(), $handle->getErrorNo());

        return $e;
    }

    /**
     * Throw an exception for a cURL multi response if needed
     *
     * @param int $code Curl response code
     * @throws CurlException
     */
    private function checkCurlResult($code)
    {
        if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) {
            throw new CurlException(isset($this->multiErrors[$code])
                ? "cURL error: {$code} ({$this->multiErrors[$code][0]}): cURL message: {$this->multiErrors[$code][1]}"
                : 'Unexpected cURL error: ' . $code
            );
        }
    }

    /**
     * @link https://github.com/guzzle/guzzle/issues/710
     */
    private function validateResponseWasSet(RequestInterface $request)
    {
        if ($request->getResponse()) {
            return true;
        }

        $body = $request instanceof EntityEnclosingRequestInterface
            ? $request->getBody()
            : null;

        if (!$body) {
            $rex = new RequestException(
                'No response was received for a request with no body. This'
                . ' could mean that you are saturating your network.'
            );
            $rex->setRequest($request);
            $this->removeErroredRequest($request, $rex);
        } elseif (!$body->isSeekable() || !$body->seek(0)) {
            // Nothing we can do with this. Sorry!
            $rex = new RequestException(
                'The connection was unexpectedly closed. The request would'
                . ' have been retried, but attempting to rewind the'
                . ' request body failed.'
            );
            $rex->setRequest($request);
            $this->removeErroredRequest($request, $rex);
        } else {
            $this->remove($request);
            // Add the request back to the batch to retry automatically.
            $this->requests[] = $request;
            $this->addHandle($request);
        }

        return false;
    }
}
<?php

namespace Guzzle\Http\Curl;

use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\Message\RequestInterface;

/**
 * Proxies requests and connections to a pool of internal curl_multi handles. Each recursive call will add requests
 * to the next available CurlMulti handle.
 */
class CurlMultiProxy extends AbstractHasDispatcher implements CurlMultiInterface
{
    protected $handles = array();
    protected $groups = array();
    protected $queued = array();
    protected $maxHandles;
    protected $selectTimeout;

    /**
     * @param int   $maxHandles The maximum number of idle CurlMulti handles to allow to remain open
     * @param float $selectTimeout timeout for curl_multi_select
     */
    public function __construct($maxHandles = 3, $selectTimeout = 1.0)
    {
        $this->maxHandles = $maxHandles;
        $this->selectTimeout = $selectTimeout;
        // You can get some weird "Too many open files" errors when sending a large amount of requests in parallel.
        // These two statements autoload classes before a system runs out of file descriptors so that you can get back
        // valuable error messages if you run out.
        class_exists('Guzzle\Http\Message\Response');
        class_exists('Guzzle\Http\Exception\CurlException');
    }

    public function add(RequestInterface $request)
    {
        $this->queued[] = $request;

        return $this;
    }

    public function all()
    {
        $requests = $this->queued;
        foreach ($this->handles as $handle) {
            $requests = array_merge($requests, $handle->all());
        }

        return $requests;
    }

    public function remove(RequestInterface $request)
    {
        foreach ($this->queued as $i => $r) {
            if ($request === $r) {
                unset($this->queued[$i]);
                return true;
            }
        }

        foreach ($this->handles as $handle) {
            if ($handle->remove($request)) {
                return true;
            }
        }

        return false;
    }

    public function reset($hard = false)
    {
        $this->queued = array();
        $this->groups = array();
        foreach ($this->handles as $handle) {
            $handle->reset();
        }
        if ($hard) {
            $this->handles = array();
        }

        return $this;
    }

    public function send()
    {
        if ($this->queued) {
            $group = $this->getAvailableHandle();
            // Add this handle to a list of handles than is claimed
            $this->groups[] = $group;
            while ($request = array_shift($this->queued)) {
                $group->add($request);
            }
            try {
                $group->send();
                array_pop($this->groups);
                $this->cleanupHandles();
            } catch (\Exception $e) {
                // Remove the group and cleanup if an exception was encountered and no more requests in group
                if (!$group->count()) {
                    array_pop($this->groups);
                    $this->cleanupHandles();
                }
                throw $e;
            }
        }
    }

    public function count()
    {
        return count($this->all());
    }

    /**
     * Get an existing available CurlMulti handle or create a new one
     *
     * @return CurlMulti
     */
    protected function getAvailableHandle()
    {
        // Grab a handle that is not claimed
        foreach ($this->handles as $h) {
            if (!in_array($h, $this->groups, true)) {
                return $h;
            }
        }

        // All are claimed, so create one
        $handle = new CurlMulti($this->selectTimeout);
        $handle->setEventDispatcher($this->getEventDispatcher());
        $this->handles[] = $handle;

        return $handle;
    }

    /**
     * Trims down unused CurlMulti handles to limit the number of open connections
     */
    protected function cleanupHandles()
    {
        if ($diff = max(0, count($this->handles) - $this->maxHandles)) {
            for ($i = count($this->handles) - 1; $i > 0 && $diff > 0; $i--) {
                if (!count($this->handles[$i])) {
                    unset($this->handles[$i]);
                    $diff--;
                }
            }
            $this->handles = array_values($this->handles);
        }
    }
}
<?php

namespace Guzzle\Http\Curl;

use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\Exception\ExceptionCollection;
use Guzzle\Http\Message\RequestInterface;

/**
 * Interface for sending a pool of {@see RequestInterface} objects in parallel
 */
interface CurlMultiInterface extends \Countable, HasDispatcherInterface
{
    const POLLING_REQUEST = 'curl_multi.polling_request';
    const ADD_REQUEST = 'curl_multi.add_request';
    const REMOVE_REQUEST = 'curl_multi.remove_request';
    const MULTI_EXCEPTION = 'curl_multi.exception';
    const BLOCKING = 'curl_multi.blocking';

    /**
     * Add a request to the pool.
     *
     * @param RequestInterface $request Request to add
     *
     * @return CurlMultiInterface
     */
    public function add(RequestInterface $request);

    /**
     * Get an array of attached {@see RequestInterface} objects
     *
     * @return array
     */
    public function all();

    /**
     * Remove a request from the pool.
     *
     * @param RequestInterface $request Request to remove
     *
     * @return bool Returns true on success or false on failure
     */
    public function remove(RequestInterface $request);

    /**
     * Reset the state and remove any attached RequestInterface objects
     *
     * @param bool $hard Set to true to close and reopen any open multi handles
     */
    public function reset($hard = false);

    /**
     * Send a pool of {@see RequestInterface} requests.
     *
     * @throws ExceptionCollection if any requests threw exceptions during the transfer.
     */
    public function send();
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;

/**
 * Client interface for send HTTP requests
 */
interface ClientInterface extends HasDispatcherInterface
{
    const CREATE_REQUEST = 'client.create_request';

    /** @var string RFC 1123 HTTP-Date */
    const HTTP_DATE = 'D, d M Y H:i:s \G\M\T';

    /**
     * Set the configuration object to use with the client
     *
     * @param array|Collection $config Parameters that define how the client behaves
     *
     * @return self
     */
    public function setConfig($config);

    /**
     * Get a configuration setting or all of the configuration settings. The Collection result of this method can be
     * modified to change the configuration settings of a client.
     *
     * A client should honor the following special values:
     *
     * - request.options: Associative array of default RequestFactory options to apply to each request
     * - request.params: Associative array of request parameters (data values) to apply to each request
     * - curl.options: Associative array of cURL configuration settings to apply to each request
     * - ssl.certificate_authority: Path a CAINFO, CAPATH, true to use strict defaults, or false to disable verification
     * - redirect.disable: Set to true to disable redirects
     *
     * @param bool|string $key Configuration value to retrieve. Set to FALSE to retrieve all values of the client.
     *                         The object return can be modified, and modifications will affect the client's config.
     * @return mixed|Collection
     * @see \Guzzle\Http\Message\RequestFactoryInterface::applyOptions for a full list of request.options options
     */
    public function getConfig($key = false);

    /**
     * Create and return a new {@see RequestInterface} configured for the client.
     *
     * Use an absolute path to override the base path of the client, or a relative path to append to the base path of
     * the client. The URI can contain the query string as well. Use an array to provide a URI template and additional
     * variables to use in the URI template expansion.
     *
     * @param string                                    $method  HTTP method. Defaults to GET
     * @param string|array                              $uri     Resource URI.
     * @param array|Collection                          $headers HTTP headers
     * @param string|resource|array|EntityBodyInterface $body    Entity body of request (POST/PUT) or response (GET)
     * @param array                                     $options Array of options to apply to the request
     *
     * @return RequestInterface
     * @throws InvalidArgumentException if a URI array is passed that does not contain exactly two elements: the URI
     *                                  followed by template variables
     */
    public function createRequest(
        $method = RequestInterface::GET,
        $uri = null,
        $headers = null,
        $body = null,
        array $options = array()
    );

    /**
     * Create a GET request for the client
     *
     * @param string|array     $uri     Resource URI
     * @param array|Collection $headers HTTP headers
     * @param array            $options Options to apply to the request. For BC compatibility, you can also pass a
     *                                  string to tell Guzzle to download the body of the response to a particular
     *                                  location. Use the 'body' option instead for forward compatibility.
     * @return RequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function get($uri = null, $headers = null, $options = array());

    /**
     * Create a HEAD request for the client
     *
     * @param string|array     $uri     Resource URI
     * @param array|Collection $headers HTTP headers
     * @param array            $options Options to apply to the request
     *
     * @return RequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function head($uri = null, $headers = null, array $options = array());

    /**
     * Create a DELETE request for the client
     *
     * @param string|array                        $uri     Resource URI
     * @param array|Collection                    $headers HTTP headers
     * @param string|resource|EntityBodyInterface $body    Body to send in the request
     * @param array                               $options Options to apply to the request
     *
     * @return EntityEnclosingRequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function delete($uri = null, $headers = null, $body = null, array $options = array());

    /**
     * Create a PUT request for the client
     *
     * @param string|array                        $uri     Resource URI
     * @param array|Collection                    $headers HTTP headers
     * @param string|resource|EntityBodyInterface $body    Body to send in the request
     * @param array                               $options Options to apply to the request
     *
     * @return EntityEnclosingRequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function put($uri = null, $headers = null, $body = null, array $options = array());

    /**
     * Create a PATCH request for the client
     *
     * @param string|array                        $uri     Resource URI
     * @param array|Collection                    $headers HTTP headers
     * @param string|resource|EntityBodyInterface $body    Body to send in the request
     * @param array                               $options Options to apply to the request
     *
     * @return EntityEnclosingRequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function patch($uri = null, $headers = null, $body = null, array $options = array());

    /**
     * Create a POST request for the client
     *
     * @param string|array                                $uri      Resource URI
     * @param array|Collection                            $headers  HTTP headers
     * @param array|Collection|string|EntityBodyInterface $postBody POST body. Can be a string, EntityBody, or
     *                                                    associative array of POST fields to send in the body of the
     *                                                    request. Prefix a value in the array with the @ symbol to
     *                                                    reference a file.
     * @param array                                       $options Options to apply to the request
     *
     * @return EntityEnclosingRequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function post($uri = null, $headers = null, $postBody = null, array $options = array());

    /**
     * Create an OPTIONS request for the client
     *
     * @param string|array $uri     Resource URI
     * @param array        $options Options to apply to the request
     *
     * @return RequestInterface
     * @see    Guzzle\Http\ClientInterface::createRequest()
     */
    public function options($uri = null, array $options = array());

    /**
     * Sends a single request or an array of requests in parallel
     *
     * @param array|RequestInterface $requests One or more RequestInterface objects to send
     *
     * @return \Guzzle\Http\Message\Response|array Returns a single Response or an array of Response objects
     */
    public function send($requests);

    /**
     * Get the client's base URL as either an expanded or raw URI template
     *
     * @param bool $expand Set to FALSE to get the raw base URL without URI template expansion
     *
     * @return string|null
     */
    public function getBaseUrl($expand = true);

    /**
     * Set the base URL of the client
     *
     * @param string $url The base service endpoint URL of the webservice
     *
     * @return self
     */
    public function setBaseUrl($url);

    /**
     * Set the User-Agent header to be used on all requests from the client
     *
     * @param string $userAgent      User agent string
     * @param bool   $includeDefault Set to true to prepend the value to Guzzle's default user agent string
     *
     * @return self
     */
    public function setUserAgent($userAgent, $includeDefault = false);

    /**
     * Set SSL verification options.
     *
     * Setting $certificateAuthority to TRUE will result in the bundled cacert.pem being used to verify against the
     * remote host.
     *
     * Alternate certificates to verify against can be specified with the $certificateAuthority option set to the full
     * path to a certificate file, or the path to a directory containing certificates.
     *
     * Setting $certificateAuthority to FALSE will turn off peer verification, unset the bundled cacert.pem, and
     * disable host verification. Please don't do this unless you really know what you're doing, and why you're doing
     * it.
     *
     * @param string|bool $certificateAuthority bool, file path, or directory path
     * @param bool        $verifyPeer           FALSE to stop from verifying the peer's certificate.
     * @param int         $verifyHost           Set to 1 to check the existence of a common name in the SSL peer
     *                                          certificate. 2 to check the existence of a common name and also verify
     *                                          that it matches the hostname provided.
     * @return self
     */
    public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2);
}
<?php

namespace Guzzle\Http;

use Guzzle\Stream\StreamInterface;

/**
 * Entity body used with an HTTP request or response
 */
interface EntityBodyInterface extends StreamInterface
{
    /**
     * Specify a custom callback used to rewind a non-seekable stream. This can be useful entity enclosing requests
     * that are redirected.
     *
     * @param mixed $callable Callable to invoke to rewind a non-seekable stream. The callback must accept an
     *                        EntityBodyInterface object, perform the rewind if possible, and return a boolean
     *                        representing whether or not the rewind was successful.
     * @return self
     */
    public function setRewindFunction($callable);

    /**
     * If the stream is readable, compress the data in the stream using deflate compression. The uncompressed stream is
     * then closed, and the compressed stream then becomes the wrapped stream.
     *
     * @param string $filter Compression filter
     *
     * @return bool Returns TRUE on success or FALSE on failure
     */
    public function compress($filter = 'zlib.deflate');

    /**
     * Decompress a deflated string. Once uncompressed, the uncompressed string is then used as the wrapped stream.
     *
     * @param string $filter De-compression filter
     *
     * @return bool Returns TRUE on success or FALSE on failure
     */
    public function uncompress($filter = 'zlib.inflate');

    /**
     * Get the Content-Length of the entity body if possible (alias of getSize)
     *
     * @return int|bool Returns the Content-Length or false on failure
     */
    public function getContentLength();

    /**
     * Guess the Content-Type of a local stream
     *
     * @return string|null
     * @see http://www.php.net/manual/en/function.finfo-open.php
     */
    public function getContentType();

    /**
     * Get an MD5 checksum of the stream's contents
     *
     * @param bool $rawOutput    Whether or not to use raw output
     * @param bool $base64Encode Whether or not to base64 encode raw output (only if raw output is true)
     *
     * @return bool|string Returns an MD5 string on success or FALSE on failure
     */
    public function getContentMd5($rawOutput = false, $base64Encode = false);

    /**
     * Get the Content-Encoding of the EntityBody
     *
     * @return bool|string
     */
    public function getContentEncoding();
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Exception\RuntimeException;

/**
 * EntityBody decorator that can cache previously read bytes from a sequentially read tstream
 */
class CachingEntityBody extends AbstractEntityBodyDecorator
{
    /** @var EntityBody Remote stream used to actually pull data onto the buffer */
    protected $remoteStream;

    /** @var int The number of bytes to skip reading due to a write on the temporary buffer */
    protected $skipReadBytes = 0;

    /**
     * We will treat the buffer object as the body of the entity body
     * {@inheritdoc}
     */
    public function __construct(EntityBodyInterface $body)
    {
        $this->remoteStream = $body;
        $this->body = new EntityBody(fopen('php://temp', 'r+'));
    }

    /**
     * Will give the contents of the buffer followed by the exhausted remote stream.
     *
     * Warning: Loads the entire stream into memory
     *
     * @return string
     */
    public function __toString()
    {
        $pos = $this->ftell();
        $this->rewind();

        $str = '';
        while (!$this->isConsumed()) {
            $str .= $this->read(16384);
        }

        $this->seek($pos);

        return $str;
    }

    public function getSize()
    {
        return max($this->body->getSize(), $this->remoteStream->getSize());
    }

    /**
     * {@inheritdoc}
     * @throws RuntimeException When seeking with SEEK_END or when seeking past the total size of the buffer stream
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        if ($whence == SEEK_SET) {
            $byte = $offset;
        } elseif ($whence == SEEK_CUR) {
            $byte = $offset + $this->ftell();
        } else {
            throw new RuntimeException(__CLASS__ . ' supports only SEEK_SET and SEEK_CUR seek operations');
        }

        // You cannot skip ahead past where you've read from the remote stream
        if ($byte > $this->body->getSize()) {
            throw new RuntimeException(
                "Cannot seek to byte {$byte} when the buffered stream only contains {$this->body->getSize()} bytes"
            );
        }

        return $this->body->seek($byte);
    }

    public function rewind()
    {
        return $this->seek(0);
    }

    /**
     * Does not support custom rewind functions
     *
     * @throws RuntimeException
     */
    public function setRewindFunction($callable)
    {
        throw new RuntimeException(__CLASS__ . ' does not support custom stream rewind functions');
    }

    public function read($length)
    {
        // Perform a regular read on any previously read data from the buffer
        $data = $this->body->read($length);
        $remaining = $length - strlen($data);

        // More data was requested so read from the remote stream
        if ($remaining) {
            // If data was written to the buffer in a position that would have been filled from the remote stream,
            // then we must skip bytes on the remote stream to emulate overwriting bytes from that position. This
            // mimics the behavior of other PHP stream wrappers.
            $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes);

            if ($this->skipReadBytes) {
                $len = strlen($remoteData);
                $remoteData = substr($remoteData, $this->skipReadBytes);
                $this->skipReadBytes = max(0, $this->skipReadBytes - $len);
            }

            $data .= $remoteData;
            $this->body->write($remoteData);
        }

        return $data;
    }

    public function write($string)
    {
        // When appending to the end of the currently read stream, you'll want to skip bytes from being read from
        // the remote stream to emulate other stream wrappers. Basically replacing bytes of data of a fixed length.
        $overflow = (strlen($string) + $this->ftell()) - $this->remoteStream->ftell();
        if ($overflow > 0) {
            $this->skipReadBytes += $overflow;
        }

        return $this->body->write($string);
    }

    /**
     * {@inheritdoc}
     * @link http://php.net/manual/en/function.fgets.php
     */
    public function readLine($maxLength = null)
    {
        $buffer = '';
        $size = 0;
        while (!$this->isConsumed()) {
            $byte = $this->read(1);
            $buffer .= $byte;
            // Break when a new line is found or the max length - 1 is reached
            if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
                break;
            }
        }

        return $buffer;
    }

    public function isConsumed()
    {
        return $this->body->isConsumed() && $this->remoteStream->isConsumed();
    }

    /**
     * Close both the remote stream and buffer stream
     */
    public function close()
    {
        return $this->remoteStream->close() && $this->body->close();
    }

    public function setStream($stream, $size = 0)
    {
        $this->remoteStream->setStream($stream, $size);
    }

    public function getContentType()
    {
        return $this->remoteStream->getContentType();
    }

    public function getContentEncoding()
    {
        return $this->remoteStream->getContentEncoding();
    }

    public function getMetaData($key = null)
    {
        return $this->remoteStream->getMetaData($key);
    }

    public function getStream()
    {
        return $this->remoteStream->getStream();
    }

    public function getWrapper()
    {
        return $this->remoteStream->getWrapper();
    }

    public function getWrapperData()
    {
        return $this->remoteStream->getWrapperData();
    }

    public function getStreamType()
    {
        return $this->remoteStream->getStreamType();
    }

    public function getUri()
    {
        return $this->remoteStream->getUri();
    }

    /**
     * Always retrieve custom data from the remote stream
     * {@inheritdoc}
     */
    public function getCustomData($key)
    {
        return $this->remoteStream->getCustomData($key);
    }

    /**
     * Always set custom data on the remote stream
     * {@inheritdoc}
     */
    public function setCustomData($key, $value)
    {
        $this->remoteStream->setCustomData($key, $value);

        return $this;
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Http\QueryAggregator\QueryAggregatorInterface;
use Guzzle\Http\QueryAggregator\PhpAggregator;

/**
 * Query string object to handle managing query string parameters and aggregating those parameters together as a string.
 */
class QueryString extends Collection
{
    /** @var string Used to URL encode with rawurlencode */
    const RFC_3986 = 'RFC 3986';

    /** @var string Used to encode with urlencode */
    const FORM_URLENCODED = 'application/x-www-form-urlencoded';

    /** @var string Constant used to create blank query string values (e.g. ?foo) */
    const BLANK = "_guzzle_blank_";

    /** @var string The query string field separator (e.g. '&') */
    protected $fieldSeparator = '&';

    /** @var string The query string value separator (e.g. '=') */
    protected $valueSeparator = '=';

    /** @var bool URL encode fields and values */
    protected $urlEncode = 'RFC 3986';

    /** @var QueryAggregatorInterface */
    protected $aggregator;

    /** @var array Cached PHP aggregator */
    private static $defaultAggregator = null;

    /**
     * Parse a query string into a QueryString object
     *
     * @param string $query Query string to parse
     *
     * @return self
     */
    public static function fromString($query)
    {
        $q = new static();
        if ($query === '') {
            return $q;
        }

        $foundDuplicates = $foundPhpStyle = false;

        foreach (explode('&', $query) as $kvp) {
            $parts = explode('=', $kvp, 2);
            $key = rawurldecode($parts[0]);
            if ($paramIsPhpStyleArray = substr($key, -2) == '[]') {
                $foundPhpStyle = true;
                $key = substr($key, 0, -2);
            }
            if (isset($parts[1])) {
                $value = rawurldecode(str_replace('+', '%20', $parts[1]));
                if (isset($q[$key])) {
                    $q->add($key, $value);
                    $foundDuplicates = true;
                } elseif ($paramIsPhpStyleArray) {
                    $q[$key] = array($value);
                } else {
                    $q[$key] = $value;
                }
            } else {
                // Uses false by default to represent keys with no trailing "=" sign.
                $q->add($key, false);
            }
        }

        // Use the duplicate aggregator if duplicates were found and not using PHP style arrays
        if ($foundDuplicates && !$foundPhpStyle) {
            $q->setAggregator(new DuplicateAggregator());
        }

        return $q;
    }

    /**
     * Convert the query string parameters to a query string string
     *
     * @return string
     * @throws RuntimeException
     */
    public function __toString()
    {
        if (!$this->data) {
            return '';
        }

        $queryList = array();
        foreach ($this->prepareData($this->data) as $name => $value) {
            $queryList[] = $this->convertKvp($name, $value);
        }

        return implode($this->fieldSeparator, $queryList);
    }

    /**
     * Get the query string field separator
     *
     * @return string
     */
    public function getFieldSeparator()
    {
        return $this->fieldSeparator;
    }

    /**
     * Get the query string value separator
     *
     * @return string
     */
    public function getValueSeparator()
    {
        return $this->valueSeparator;
    }

    /**
     * Returns the type of URL encoding used by the query string
     *
     * One of: false, "RFC 3986", or "application/x-www-form-urlencoded"
     *
     * @return bool|string
     */
    public function getUrlEncoding()
    {
        return $this->urlEncode;
    }

    /**
     * Returns true or false if using URL encoding
     *
     * @return bool
     */
    public function isUrlEncoding()
    {
        return $this->urlEncode !== false;
    }

    /**
     * Provide a function for combining multi-valued query string parameters into a single or multiple fields
     *
     * @param null|QueryAggregatorInterface $aggregator Pass in a QueryAggregatorInterface object to handle converting
     *                                                  deeply nested query string variables into a flattened array.
     *                                                  Pass null to use the default PHP style aggregator. For legacy
     *                                                  reasons, this function accepts a callable that must accepts a
     *                                                  $key, $value, and query object.
     * @return self
     * @see \Guzzle\Http\QueryString::aggregateUsingComma()
     */
    public function setAggregator(QueryAggregatorInterface $aggregator = null)
    {
        // Use the default aggregator if none was set
        if (!$aggregator) {
            if (!self::$defaultAggregator) {
                self::$defaultAggregator = new PhpAggregator();
            }
            $aggregator = self::$defaultAggregator;
        }

        $this->aggregator = $aggregator;

        return $this;
    }

    /**
     * Set whether or not field names and values should be rawurlencoded
     *
     * @param bool|string $encode Set to TRUE to use RFC 3986 encoding (rawurlencode), false to disable encoding, or
     *                            form_urlencoding to use application/x-www-form-urlencoded encoding (urlencode)
     * @return self
     */
    public function useUrlEncoding($encode)
    {
        $this->urlEncode = ($encode === true) ? self::RFC_3986 : $encode;

        return $this;
    }

    /**
     * Set the query string separator
     *
     * @param string $separator The query string separator that will separate fields
     *
     * @return self
     */
    public function setFieldSeparator($separator)
    {
        $this->fieldSeparator = $separator;

        return $this;
    }

    /**
     * Set the query string value separator
     *
     * @param string $separator The query string separator that will separate values from fields
     *
     * @return self
     */
    public function setValueSeparator($separator)
    {
        $this->valueSeparator = $separator;

        return $this;
    }

    /**
     * Returns an array of url encoded field names and values
     *
     * @return array
     */
    public function urlEncode()
    {
        return $this->prepareData($this->data);
    }

    /**
     * URL encodes a value based on the url encoding type of the query string object
     *
     * @param string $value Value to encode
     *
     * @return string
     */
    public function encodeValue($value)
    {
        if ($this->urlEncode == self::RFC_3986) {
            return rawurlencode($value);
        } elseif ($this->urlEncode == self::FORM_URLENCODED) {
            return urlencode($value);
        } else {
            return (string) $value;
        }
    }

    /**
     * Url encode parameter data and convert nested query strings into a flattened hash.
     *
     * @param array $data The data to encode
     *
     * @return array Returns an array of encoded values and keys
     */
    protected function prepareData(array $data)
    {
        // If no aggregator is present then set the default
        if (!$this->aggregator) {
            $this->setAggregator(null);
        }

        $temp = array();
        foreach ($data as $key => $value) {
            if ($value === false || $value === null) {
                // False and null will not include the "=". Use an empty string to include the "=".
                $temp[$this->encodeValue($key)] = $value;
            } elseif (is_array($value)) {
                $temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this));
            } else {
                $temp[$this->encodeValue($key)] = $this->encodeValue($value);
            }
        }

        return $temp;
    }

    /**
     * Converts a key value pair that can contain strings, nulls, false, or arrays
     * into a single string.
     *
     * @param string $name  Name of the field
     * @param mixed  $value Value of the field
     * @return string
     */
    private function convertKvp($name, $value)
    {
        if ($value === self::BLANK || $value === null || $value === false) {
            return $name;
        } elseif (!is_array($value)) {
            return $name . $this->valueSeparator . $value;
        }

        $result = '';
        foreach ($value as $v) {
            $result .= $this->convertKvp($name, $v) . $this->fieldSeparator;
        }

        return rtrim($result, $this->fieldSeparator);
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Event;
use Guzzle\Common\HasDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * EntityBody decorator that emits events for read and write methods
 */
class IoEmittingEntityBody extends AbstractEntityBodyDecorator implements HasDispatcherInterface
{
    /** @var EventDispatcherInterface */
    protected $eventDispatcher;

    public static function getAllEvents()
    {
        return array('body.read', 'body.write');
    }

    /**
     * {@inheritdoc}
     * @codeCoverageIgnore
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;

        return $this;
    }

    public function getEventDispatcher()
    {
        if (!$this->eventDispatcher) {
            $this->eventDispatcher = new EventDispatcher();
        }

        return $this->eventDispatcher;
    }

    public function dispatch($eventName, array $context = array())
    {
        return $this->getEventDispatcher()->dispatch($eventName, new Event($context));
    }

    /**
     * {@inheritdoc}
     * @codeCoverageIgnore
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->getEventDispatcher()->addSubscriber($subscriber);

        return $this;
    }

    public function read($length)
    {
        $event = array(
            'body'   => $this,
            'length' => $length,
            'read'   => $this->body->read($length)
        );
        $this->dispatch('body.read', $event);

        return $event['read'];
    }

    public function write($string)
    {
        $event = array(
            'body'   => $this,
            'write'  => $string,
            'result' => $this->body->write($string)
        );
        $this->dispatch('body.write', $event);

        return $event['result'];
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Guzzle\Stream\StreamRequestFactoryInterface;
use Guzzle\Stream\PhpStreamRequestFactory;

/**
 * Simplified interface to Guzzle that does not require a class to be instantiated
 */
final class StaticClient
{
    /** @var Client Guzzle client */
    private static $client;

    /**
     * Mount the client to a simpler class name for a specific client
     *
     * @param string          $className Class name to use to mount
     * @param ClientInterface $client    Client used to send requests
     */
    public static function mount($className = 'Guzzle', ClientInterface $client = null)
    {
        class_alias(__CLASS__, $className);
        if ($client) {
            self::$client = $client;
        }
    }

    /**
     * @param  string $method  HTTP request method (GET, POST, HEAD, DELETE, PUT, etc)
     * @param  string $url     URL of the request
     * @param  array  $options Options to use with the request. See: Guzzle\Http\Message\RequestFactory::applyOptions()
     * @return \Guzzle\Http\Message\Response|\Guzzle\Stream\Stream
     */
    public static function request($method, $url, $options = array())
    {
        // @codeCoverageIgnoreStart
        if (!self::$client) {
            self::$client = new Client();
        }
        // @codeCoverageIgnoreEnd

        $request = self::$client->createRequest($method, $url, null, null, $options);

        if (isset($options['stream'])) {
            if ($options['stream'] instanceof StreamRequestFactoryInterface) {
                return $options['stream']->fromRequest($request);
            } elseif ($options['stream'] == true) {
                $streamFactory = new PhpStreamRequestFactory();
                return $streamFactory->fromRequest($request);
            }
        }

        return $request->send();
    }

    /**
     * Send a GET request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function get($url, $options = array())
    {
        return self::request('GET', $url, $options);
    }

    /**
     * Send a HEAD request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function head($url, $options = array())
    {
        return self::request('HEAD', $url, $options);
    }

    /**
     * Send a DELETE request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function delete($url, $options = array())
    {
        return self::request('DELETE', $url, $options);
    }

    /**
     * Send a POST request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function post($url, $options = array())
    {
        return self::request('POST', $url, $options);
    }

    /**
     * Send a PUT request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function put($url, $options = array())
    {
        return self::request('PUT', $url, $options);
    }

    /**
     * Send a PATCH request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function patch($url, $options = array())
    {
        return self::request('PATCH', $url, $options);
    }

    /**
     * Send an OPTIONS request
     *
     * @param string $url     URL of the request
     * @param array  $options Array of request options
     *
     * @return \Guzzle\Http\Message\Response
     * @see Guzzle::request for a list of available options
     */
    public static function options($url, $options = array())
    {
        return self::request('OPTIONS', $url, $options);
    }
}
<?php

namespace Guzzle\Http\Exception;

/**
 * Exception when a client error is encountered (4xx codes)
 */
class ClientErrorResponseException extends BadResponseException {}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Common\Exception\GuzzleException;

/**
 * Http exception interface
 */
interface HttpException extends GuzzleException {}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Http request exception thrown when a bad response is received
 */
class BadResponseException extends RequestException
{
    /** @var Response */
    private $response;

    /**
     * Factory method to create a new response exception based on the response code.
     *
     * @param RequestInterface $request  Request
     * @param Response         $response Response received
     *
     * @return BadResponseException
     */
    public static function factory(RequestInterface $request, Response $response)
    {
        if ($response->isClientError()) {
            $label = 'Client error response';
            $class = __NAMESPACE__ . '\\ClientErrorResponseException';
        } elseif ($response->isServerError()) {
            $label = 'Server error response';
            $class = __NAMESPACE__ . '\\ServerErrorResponseException';
        } else {
            $label = 'Unsuccessful response';
            $class = __CLASS__;
        }

        $message = $label . PHP_EOL . implode(PHP_EOL, array(
            '[status code] ' . $response->getStatusCode(),
            '[reason phrase] ' . $response->getReasonPhrase(),
            '[url] ' . $request->getUrl(),
        ));

        $e = new $class($message);
        $e->setResponse($response);
        $e->setRequest($request);

        return $e;
    }

    /**
     * Set the response that caused the exception
     *
     * @param Response $response Response to set
     */
    public function setResponse(Response $response)
    {
        $this->response = $response;
    }

    /**
     * Get the response that caused the exception
     *
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}
<?php

namespace Guzzle\Http\Exception;

class TooManyRedirectsException extends BadResponseException {}
<?php

namespace Guzzle\Http\Exception;

/**
 * Exception when a server error is encountered (5xx codes)
 */
class ServerErrorResponseException extends BadResponseException {}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Common\Exception\ExceptionCollection;
use Guzzle\Http\Message\RequestInterface;

/**
 * Exception encountered during a multi transfer
 */
class MultiTransferException extends ExceptionCollection
{
    protected $successfulRequests = array();
    protected $failedRequests = array();
    protected $exceptionForRequest = array();

    /**
     * Get all of the requests in the transfer
     *
     * @return array
     */
    public function getAllRequests()
    {
        return array_merge($this->successfulRequests, $this->failedRequests);
    }

    /**
     * Add to the array of successful requests
     *
     * @param RequestInterface $request Successful request
     *
     * @return self
     */
    public function addSuccessfulRequest(RequestInterface $request)
    {
        $this->successfulRequests[] = $request;

        return $this;
    }

    /**
     * Add to the array of failed requests
     *
     * @param RequestInterface $request Failed request
     *
     * @return self
     */
    public function addFailedRequest(RequestInterface $request)
    {
        $this->failedRequests[] = $request;

        return $this;
    }

    /**
     * Add to the array of failed requests and associate with exceptions
     *
     * @param RequestInterface $request   Failed request
     * @param \Exception       $exception Exception to add and associate with
     *
     * @return self
     */
    public function addFailedRequestWithException(RequestInterface $request, \Exception $exception)
    {
        $this->add($exception)
             ->addFailedRequest($request)
             ->exceptionForRequest[spl_object_hash($request)] = $exception;

        return $this;
    }

    /**
     * Get the Exception that caused the given $request to fail
     *
     * @param RequestInterface $request Failed command
     *
     * @return \Exception|null
     */
    public function getExceptionForFailedRequest(RequestInterface $request)
    {
        $oid = spl_object_hash($request);

        return isset($this->exceptionForRequest[$oid]) ? $this->exceptionForRequest[$oid] : null;
    }

    /**
     * Set all of the successful requests
     *
     * @param array Array of requests
     *
     * @return self
     */
    public function setSuccessfulRequests(array $requests)
    {
        $this->successfulRequests = $requests;

        return $this;
    }

    /**
     * Set all of the failed requests
     *
     * @param array Array of requests
     *
     * @return self
     */
    public function setFailedRequests(array $requests)
    {
        $this->failedRequests = $requests;

        return $this;
    }

    /**
     * Get an array of successful requests sent in the multi transfer
     *
     * @return array
     */
    public function getSuccessfulRequests()
    {
        return $this->successfulRequests;
    }

    /**
     * Get an array of failed requests sent in the multi transfer
     *
     * @return array
     */
    public function getFailedRequests()
    {
        return $this->failedRequests;
    }

    /**
     * Check if the exception object contains a request
     *
     * @param RequestInterface $request Request to check
     *
     * @return bool
     */
    public function containsRequest(RequestInterface $request)
    {
        return in_array($request, $this->failedRequests, true) || in_array($request, $this->successfulRequests, true);
    }
}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Http\Curl\CurlHandle;

/**
 * cURL request exception
 */
class CurlException extends RequestException
{
    private $curlError;
    private $curlErrorNo;
    private $handle;
    private $curlInfo = array();

    /**
     * Set the cURL error message
     *
     * @param string $error  Curl error
     * @param int    $number Curl error number
     *
     * @return self
     */
    public function setError($error, $number)
    {
        $this->curlError = $error;
        $this->curlErrorNo = $number;

        return $this;
    }

    /**
     * Set the associated curl handle
     *
     * @param CurlHandle $handle Curl handle
     *
     * @return self
     */
    public function setCurlHandle(CurlHandle $handle)
    {
        $this->handle = $handle;

        return $this;
    }

    /**
     * Get the associated cURL handle
     *
     * @return CurlHandle|null
     */
    public function getCurlHandle()
    {
        return $this->handle;
    }

    /**
     * Get the associated cURL error message
     *
     * @return string|null
     */
    public function getError()
    {
        return $this->curlError;
    }

    /**
     * Get the associated cURL error number
     *
     * @return int|null
     */
    public function getErrorNo()
    {
        return $this->curlErrorNo;
    }

    /**
     * Returns curl information about the transfer
     *
     * @return array
     */
    public function getCurlInfo()
    {
        return $this->curlInfo;
    }

    /**
     * Set curl transfer information
     *
     * @param array $info Array of curl transfer information
     *
     * @return self
     * @link http://php.net/manual/en/function.curl-getinfo.php
     */
    public function setCurlInfo(array $info)
    {
        $this->curlInfo = $info;

        return $this;
    }
}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Common\Exception\RuntimeException;

class CouldNotRewindStreamException extends RuntimeException implements HttpException {}
<?php

namespace Guzzle\Http\Exception;

use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\Message\RequestInterface;

/**
 * Http request exception
 */
class RequestException extends RuntimeException implements HttpException
{
    /** @var RequestInterface */
    protected $request;

    /**
     * Set the request that caused the exception
     *
     * @param RequestInterface $request Request to set
     *
     * @return RequestException
     */
    public function setRequest(RequestInterface $request)
    {
        $this->request = $request;

        return $this;
    }

    /**
     * Get the request that caused the exception
     *
     * @return RequestInterface
     */
    public function getRequest()
    {
        return $this->request;
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Event;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\Url;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Exception\TooManyRedirectsException;
use Guzzle\Http\Exception\CouldNotRewindStreamException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Plugin to implement HTTP redirects. Can redirect like a web browser or using strict RFC 2616 compliance
 */
class RedirectPlugin implements EventSubscriberInterface
{
    const REDIRECT_COUNT = 'redirect.count';
    const MAX_REDIRECTS = 'redirect.max';
    const STRICT_REDIRECTS = 'redirect.strict';
    const PARENT_REQUEST = 'redirect.parent_request';
    const DISABLE = 'redirect.disable';

    /**
     * @var int Default number of redirects allowed when no setting is supplied by a request
     */
    protected $defaultMaxRedirects = 5;

    public static function getSubscribedEvents()
    {
        return array(
            'request.sent'        => array('onRequestSent', 100),
            'request.clone'       => 'cleanupRequest',
            'request.before_send' => 'cleanupRequest'
        );
    }

    /**
     * Clean up the parameters of a request when it is cloned
     *
     * @param Event $event Event emitted
     */
    public function cleanupRequest(Event $event)
    {
        $params = $event['request']->getParams();
        unset($params[self::REDIRECT_COUNT]);
        unset($params[self::PARENT_REQUEST]);
    }

    /**
     * Called when a request receives a redirect response
     *
     * @param Event $event Event emitted
     */
    public function onRequestSent(Event $event)
    {
        $response = $event['response'];
        $request = $event['request'];

        // Only act on redirect requests with Location headers
        if (!$response || $request->getParams()->get(self::DISABLE)) {
            return;
        }

        // Trace the original request based on parameter history
        $original = $this->getOriginalRequest($request);

        // Terminating condition to set the effective response on the original request
        if (!$response->isRedirect() || !$response->hasHeader('Location')) {
            if ($request !== $original) {
                // This is a terminating redirect response, so set it on the original request
                $response->getParams()->set(self::REDIRECT_COUNT, $original->getParams()->get(self::REDIRECT_COUNT));
                $original->setResponse($response);
                $response->setEffectiveUrl($request->getUrl());
            }
            return;
        }

        $this->sendRedirectRequest($original, $request, $response);
    }

    /**
     * Get the original request that initiated a series of redirects
     *
     * @param RequestInterface $request Request to get the original request from
     *
     * @return RequestInterface
     */
    protected function getOriginalRequest(RequestInterface $request)
    {
        $original = $request;
        // The number of redirects is held on the original request, so determine which request that is
        while ($parent = $original->getParams()->get(self::PARENT_REQUEST)) {
            $original = $parent;
        }

        return $original;
    }

    /**
     * Create a redirect request for a specific request object
     *
     * Takes into account strict RFC compliant redirection (e.g. redirect POST with POST) vs doing what most clients do
     * (e.g. redirect POST with GET).
     *
     * @param RequestInterface $request    Request being redirected
     * @param RequestInterface $original   Original request
     * @param int              $statusCode Status code of the redirect
     * @param string           $location   Location header of the redirect
     *
     * @return RequestInterface Returns a new redirect request
     * @throws CouldNotRewindStreamException If the body needs to be rewound but cannot
     */
    protected function createRedirectRequest(
        RequestInterface $request,
        $statusCode,
        $location,
        RequestInterface $original
    ) {
        $redirectRequest = null;
        $strict = $original->getParams()->get(self::STRICT_REDIRECTS);

        // Switch method to GET for 303 redirects.  301 and 302 redirects also switch to GET unless we are forcing RFC
        // compliance to emulate what most browsers do.  NOTE: IE only switches methods on 301/302 when coming from a POST.
        if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || (!$strict && $statusCode <= 302))) {
            $redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET');
        } else {
            $redirectRequest = clone $request;
        }

        $redirectRequest->setIsRedirect(true);
        // Always use the same response body when redirecting
        $redirectRequest->setResponseBody($request->getResponseBody());

        $location = Url::factory($location);
        // If the location is not absolute, then combine it with the original URL
        if (!$location->isAbsolute()) {
            $originalUrl = $redirectRequest->getUrl(true);
            // Remove query string parameters and just take what is present on the redirect Location header
            $originalUrl->getQuery()->clear();
            $location = $originalUrl->combine((string) $location, true);
        }

        $redirectRequest->setUrl($location);

        // Add the parent request to the request before it sends (make sure it's before the onRequestClone event too)
        $redirectRequest->getEventDispatcher()->addListener(
            'request.before_send',
            $func = function ($e) use (&$func, $request, $redirectRequest) {
                $redirectRequest->getEventDispatcher()->removeListener('request.before_send', $func);
                $e['request']->getParams()->set(RedirectPlugin::PARENT_REQUEST, $request);
            }
        );

        // Rewind the entity body of the request if needed
        if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) {
            $body = $redirectRequest->getBody();
            // Only rewind the body if some of it has been read already, and throw an exception if the rewind fails
            if ($body->ftell() && !$body->rewind()) {
                throw new CouldNotRewindStreamException(
                    'Unable to rewind the non-seekable entity body of the request after redirecting. cURL probably '
                    . 'sent part of body before the redirect occurred. Try adding acustom rewind function using on the '
                    . 'entity body of the request using setRewindFunction().'
                );
            }
        }

        return $redirectRequest;
    }

    /**
     * Prepare the request for redirection and enforce the maximum number of allowed redirects per client
     *
     * @param RequestInterface $original  Original request
     * @param RequestInterface $request   Request to prepare and validate
     * @param Response         $response  The current response
     *
     * @return RequestInterface
     */
    protected function prepareRedirection(RequestInterface $original, RequestInterface $request, Response $response)
    {
        $params = $original->getParams();
        // This is a new redirect, so increment the redirect counter
        $current = $params[self::REDIRECT_COUNT] + 1;
        $params[self::REDIRECT_COUNT] = $current;
        // Use a provided maximum value or default to a max redirect count of 5
        $max = isset($params[self::MAX_REDIRECTS]) ? $params[self::MAX_REDIRECTS] : $this->defaultMaxRedirects;

        // Throw an exception if the redirect count is exceeded
        if ($current > $max) {
            $this->throwTooManyRedirectsException($original, $max);
            return false;
        } else {
            // Create a redirect request based on the redirect rules set on the request
            return $this->createRedirectRequest(
                $request,
                $response->getStatusCode(),
                trim($response->getLocation()),
                $original
            );
        }
    }

    /**
     * Send a redirect request and handle any errors
     *
     * @param RequestInterface $original The originating request
     * @param RequestInterface $request  The current request being redirected
     * @param Response         $response The response of the current request
     *
     * @throws BadResponseException|\Exception
     */
    protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response)
    {
        // Validate and create a redirect request based on the original request and current response
        if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) {
            try {
                $redirectRequest->send();
            } catch (BadResponseException $e) {
                $e->getResponse();
                if (!$e->getResponse()) {
                    throw $e;
                }
            }
        }
    }

    /**
     * Throw a too many redirects exception for a request
     *
     * @param RequestInterface $original Request
     * @param int              $max      Max allowed redirects
     *
     * @throws TooManyRedirectsException when too many redirects have been issued
     */
    protected function throwTooManyRedirectsException(RequestInterface $original, $max)
    {
        $original->getEventDispatcher()->addListener(
            'request.complete',
            $func = function ($e) use (&$func, $original, $max) {
                $original->getEventDispatcher()->removeListener('request.complete', $func);
                $str = "{$max} redirects were issued for this request:\n" . $e['request']->getRawHeaders();
                throw new TooManyRedirectsException($str);
            }
        );
    }
}
{
    "name": "guzzle/http",
    "description": "HTTP libraries used by Guzzle",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["http client", "http", "client", "Guzzle", "curl"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/common": "self.version",
        "guzzle/parser": "self.version",
        "guzzle/stream": "self.version"
    },
    "suggest": {
        "ext-curl": "*"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Http": "" }
    },
    "target-dir": "Guzzle/Http",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Common\Collection;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Common\Exception\ExceptionCollection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\Version;
use Guzzle\Parser\ParserRegistry;
use Guzzle\Parser\UriTemplate\UriTemplateInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\RequestFactoryInterface;
use Guzzle\Http\Curl\CurlMultiInterface;
use Guzzle\Http\Curl\CurlMultiProxy;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Curl\CurlVersion;

/**
 * HTTP client
 */
class Client extends AbstractHasDispatcher implements ClientInterface
{
    /** @deprecated Use [request.options][params] */
    const REQUEST_PARAMS = 'request.params';

    const REQUEST_OPTIONS = 'request.options';
    const CURL_OPTIONS = 'curl.options';
    const SSL_CERT_AUTHORITY = 'ssl.certificate_authority';
    const DISABLE_REDIRECTS = RedirectPlugin::DISABLE;
    const DEFAULT_SELECT_TIMEOUT = 1.0;
    const MAX_HANDLES = 3;

    /** @var Collection Default HTTP headers to set on each request */
    protected $defaultHeaders;

    /** @var string The user agent string to set on each request */
    protected $userAgent;

    /** @var Collection Parameter object holding configuration data */
    private $config;

    /** @var Url Base URL of the client */
    private $baseUrl;

    /** @var CurlMultiInterface CurlMulti object used internally */
    private $curlMulti;

    /** @var UriTemplateInterface URI template owned by the client */
    private $uriTemplate;

    /** @var RequestFactoryInterface Request factory used by the client */
    protected $requestFactory;

    public static function getAllEvents()
    {
        return array(self::CREATE_REQUEST);
    }

    /**
     * @param string           $baseUrl Base URL of the web service
     * @param array|Collection $config  Configuration settings
     *
     * @throws RuntimeException if cURL is not installed
     */
    public function __construct($baseUrl = '', $config = null)
    {
        if (!extension_loaded('curl')) {
            // @codeCoverageIgnoreStart
            throw new RuntimeException('The PHP cURL extension must be installed to use Guzzle.');
            // @codeCoverageIgnoreEnd
        }
        $this->setConfig($config ?: new Collection());
        $this->initSsl();
        $this->setBaseUrl($baseUrl);
        $this->defaultHeaders = new Collection();
        $this->setRequestFactory(RequestFactory::getInstance());
        $this->userAgent = $this->getDefaultUserAgent();
        if (!$this->config[self::DISABLE_REDIRECTS]) {
            $this->addSubscriber(new RedirectPlugin());
        }
    }

    final public function setConfig($config)
    {
        if ($config instanceof Collection) {
            $this->config = $config;
        } elseif (is_array($config)) {
            $this->config = new Collection($config);
        } else {
            throw new InvalidArgumentException('Config must be an array or Collection');
        }

        return $this;
    }

    final public function getConfig($key = false)
    {
        return $key ? $this->config[$key] : $this->config;
    }

    /**
     * Set a default request option on the client that will be used as a default for each request
     *
     * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo)
     * @param mixed  $value     Value to set
     *
     * @return $this
     */
    public function setDefaultOption($keyOrPath, $value)
    {
        $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath;
        $this->config->setPath($keyOrPath, $value);

        return $this;
    }

    /**
     * Retrieve a default request option from the client
     *
     * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo)
     *
     * @return mixed|null
     */
    public function getDefaultOption($keyOrPath)
    {
        $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath;

        return $this->config->getPath($keyOrPath);
    }

    final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2)
    {
        $opts = $this->config[self::CURL_OPTIONS] ?: array();

        if ($certificateAuthority === true) {
            // use bundled CA bundle, set secure defaults
            $opts[CURLOPT_CAINFO] = __DIR__ . '/Resources/cacert.pem';
            $opts[CURLOPT_SSL_VERIFYPEER] = true;
            $opts[CURLOPT_SSL_VERIFYHOST] = 2;
        } elseif ($certificateAuthority === false) {
            unset($opts[CURLOPT_CAINFO]);
            $opts[CURLOPT_SSL_VERIFYPEER] = false;
            $opts[CURLOPT_SSL_VERIFYHOST] = 0;
        } elseif ($verifyPeer !== true && $verifyPeer !== false && $verifyPeer !== 1 && $verifyPeer !== 0) {
            throw new InvalidArgumentException('verifyPeer must be 1, 0 or boolean');
        } elseif ($verifyHost !== 0 && $verifyHost !== 1 && $verifyHost !== 2) {
            throw new InvalidArgumentException('verifyHost must be 0, 1 or 2');
        } else {
            $opts[CURLOPT_SSL_VERIFYPEER] = $verifyPeer;
            $opts[CURLOPT_SSL_VERIFYHOST] = $verifyHost;
            if (is_file($certificateAuthority)) {
                unset($opts[CURLOPT_CAPATH]);
                $opts[CURLOPT_CAINFO] = $certificateAuthority;
            } elseif (is_dir($certificateAuthority)) {
                unset($opts[CURLOPT_CAINFO]);
                $opts[CURLOPT_CAPATH] = $certificateAuthority;
            } else {
                throw new RuntimeException(
                    'Invalid option passed to ' . self::SSL_CERT_AUTHORITY . ': ' . $certificateAuthority
                );
            }
        }

        $this->config->set(self::CURL_OPTIONS, $opts);

        return $this;
    }

    public function createRequest($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array())
    {
        if (!$uri) {
            $url = $this->getBaseUrl();
        } else {
            if (!is_array($uri)) {
                $templateVars = null;
            } else {
                list($uri, $templateVars) = $uri;
            }
            if (strpos($uri, '://')) {
                // Use absolute URLs as-is
                $url = $this->expandTemplate($uri, $templateVars);
            } else {
                $url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars));
            }
        }

        // If default headers are provided, then merge them under any explicitly provided headers for the request
        if (count($this->defaultHeaders)) {
            if (!$headers) {
                $headers = $this->defaultHeaders->toArray();
            } elseif (is_array($headers)) {
                $headers += $this->defaultHeaders->toArray();
            } elseif ($headers instanceof Collection) {
                $headers = $headers->toArray() + $this->defaultHeaders->toArray();
            }
        }

        return $this->prepareRequest($this->requestFactory->create($method, (string) $url, $headers, $body), $options);
    }

    public function getBaseUrl($expand = true)
    {
        return $expand ? $this->expandTemplate($this->baseUrl) : $this->baseUrl;
    }

    public function setBaseUrl($url)
    {
        $this->baseUrl = $url;

        return $this;
    }

    public function setUserAgent($userAgent, $includeDefault = false)
    {
        if ($includeDefault) {
            $userAgent .= ' ' . $this->getDefaultUserAgent();
        }
        $this->userAgent = $userAgent;

        return $this;
    }

    /**
     * Get the default User-Agent string to use with Guzzle
     *
     * @return string
     */
    public function getDefaultUserAgent()
    {
        return 'Guzzle/' . Version::VERSION
            . ' curl/' . CurlVersion::getInstance()->get('version')
            . ' PHP/' . PHP_VERSION;
    }

    public function get($uri = null, $headers = null, $options = array())
    {
        // BC compat: $options can be a string, resource, etc to specify where the response body is downloaded
        return is_array($options)
            ? $this->createRequest('GET', $uri, $headers, null, $options)
            : $this->createRequest('GET', $uri, $headers, $options);
    }

    public function head($uri = null, $headers = null, array $options = array())
    {
        return $this->createRequest('HEAD', $uri, $headers, null, $options);
    }

    public function delete($uri = null, $headers = null, $body = null, array $options = array())
    {
        return $this->createRequest('DELETE', $uri, $headers, $body, $options);
    }

    public function put($uri = null, $headers = null, $body = null, array $options = array())
    {
        return $this->createRequest('PUT', $uri, $headers, $body, $options);
    }

    public function patch($uri = null, $headers = null, $body = null, array $options = array())
    {
        return $this->createRequest('PATCH', $uri, $headers, $body, $options);
    }

    public function post($uri = null, $headers = null, $postBody = null, array $options = array())
    {
        return $this->createRequest('POST', $uri, $headers, $postBody, $options);
    }

    public function options($uri = null, array $options = array())
    {
        return $this->createRequest('OPTIONS', $uri, $options);
    }

    public function send($requests)
    {
        if (!($requests instanceof RequestInterface)) {
            return $this->sendMultiple($requests);
        }

        try {
            /** @var $requests RequestInterface  */
            $this->getCurlMulti()->add($requests)->send();
            return $requests->getResponse();
        } catch (ExceptionCollection $e) {
            throw $e->getFirst();
        }
    }

    /**
     * Set a curl multi object to be used internally by the client for transferring requests.
     *
     * @param CurlMultiInterface $curlMulti Multi object
     *
     * @return self
     */
    public function setCurlMulti(CurlMultiInterface $curlMulti)
    {
        $this->curlMulti = $curlMulti;

        return $this;
    }

    /**
     * @return CurlMultiInterface|CurlMultiProxy
     */
    public function getCurlMulti()
    {
        if (!$this->curlMulti) {
            $this->curlMulti = new CurlMultiProxy(
                self::MAX_HANDLES,
                $this->getConfig('select_timeout') ?: self::DEFAULT_SELECT_TIMEOUT
            );
        }

        return $this->curlMulti;
    }

    public function setRequestFactory(RequestFactoryInterface $factory)
    {
        $this->requestFactory = $factory;

        return $this;
    }

    /**
     * Set the URI template expander to use with the client
     *
     * @param UriTemplateInterface $uriTemplate URI template expander
     *
     * @return self
     */
    public function setUriTemplate(UriTemplateInterface $uriTemplate)
    {
        $this->uriTemplate = $uriTemplate;

        return $this;
    }

    /**
     * Expand a URI template while merging client config settings into the template variables
     *
     * @param string $template  Template to expand
     * @param array  $variables Variables to inject
     *
     * @return string
     */
    protected function expandTemplate($template, array $variables = null)
    {
        $expansionVars = $this->getConfig()->toArray();
        if ($variables) {
            $expansionVars = $variables + $expansionVars;
        }

        return $this->getUriTemplate()->expand($template, $expansionVars);
    }

    /**
     * Get the URI template expander used by the client
     *
     * @return UriTemplateInterface
     */
    protected function getUriTemplate()
    {
        if (!$this->uriTemplate) {
            $this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template');
        }

        return $this->uriTemplate;
    }

    /**
     * Send multiple requests in parallel
     *
     * @param array $requests Array of RequestInterface objects
     *
     * @return array Returns an array of Response objects
     */
    protected function sendMultiple(array $requests)
    {
        $curlMulti = $this->getCurlMulti();
        foreach ($requests as $request) {
            $curlMulti->add($request);
        }
        $curlMulti->send();

        /** @var $request RequestInterface */
        $result = array();
        foreach ($requests as $request) {
            $result[] = $request->getResponse();
        }

        return $result;
    }

    /**
     * Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request.
     *
     * @param RequestInterface $request Request to prepare for the client
     * @param array            $options Options to apply to the request
     *
     * @return RequestInterface
     */
    protected function prepareRequest(RequestInterface $request, array $options = array())
    {
        $request->setClient($this)->setEventDispatcher(clone $this->getEventDispatcher());

        if ($curl = $this->config[self::CURL_OPTIONS]) {
            $request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl));
        }

        if ($params = $this->config[self::REQUEST_PARAMS]) {
            Version::warn('request.params is deprecated. Use request.options to add default request options.');
            $request->getParams()->overwriteWith($params);
        }

        if ($this->userAgent && !$request->hasHeader('User-Agent')) {
            $request->setHeader('User-Agent', $this->userAgent);
        }

        if ($defaults = $this->config[self::REQUEST_OPTIONS]) {
            $this->requestFactory->applyOptions($request, $defaults, RequestFactoryInterface::OPTIONS_AS_DEFAULTS);
        }

        if ($options) {
            $this->requestFactory->applyOptions($request, $options);
        }

        $this->dispatch('client.create_request', array('client' => $this, 'request' => $request));

        return $request;
    }

    /**
     * Initializes SSL settings
     */
    protected function initSsl()
    {
        $authority = $this->config[self::SSL_CERT_AUTHORITY];

        if ($authority === 'system') {
            return;
        }

        if ($authority === null) {
            $authority = true;
        }

        if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') {
            $authority = self::extractPharCacert(__DIR__ . '/Resources/cacert.pem');
        }

        $this->setSslVerification($authority);
    }

    /**
     * @deprecated
     */
    public function getDefaultHeaders()
    {
        Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to retrieve default request options');
        return $this->defaultHeaders;
    }

    /**
     * @deprecated
     */
    public function setDefaultHeaders($headers)
    {
        Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to specify default request options');
        if ($headers instanceof Collection) {
            $this->defaultHeaders = $headers;
        } elseif (is_array($headers)) {
            $this->defaultHeaders = new Collection($headers);
        } else {
            throw new InvalidArgumentException('Headers must be an array or Collection');
        }

        return $this;
    }

    /**
     * @deprecated
     */
    public function preparePharCacert($md5Check = true)
    {
        return sys_get_temp_dir() . '/guzzle-cacert.pem';
    }

    /**
     * Copies the phar cacert from a phar into the temp directory.
     *
     * @param string $pharCacertPath Path to the phar cacert. For example:
     *                               'phar://aws.phar/Guzzle/Http/Resources/cacert.pem'
     *
     * @return string Returns the path to the extracted cacert file.
     * @throws \RuntimeException Throws if the phar cacert cannot be found or
     *                           the file cannot be copied to the temp dir.
     */
    public static function extractPharCacert($pharCacertPath)
    {
        // Copy the cacert.pem file from the phar if it is not in the temp
        // folder.
        $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem';

        if (!file_exists($pharCacertPath)) {
            throw new \RuntimeException("Could not find $pharCacertPath");
        }

        if (!file_exists($certFile) ||
            filesize($certFile) != filesize($pharCacertPath)
        ) {
            if (!copy($pharCacertPath, $certFile)) {
                throw new \RuntimeException(
                    "Could not copy {$pharCacertPath} to {$certFile}: "
                    . var_export(error_get_last(), true)
                );
            }
        }

        return $certFile;
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Stream\Stream;

/**
 * Abstract decorator used to wrap entity bodies
 */
class AbstractEntityBodyDecorator implements EntityBodyInterface
{
    /** @var EntityBodyInterface Decorated entity body */
    protected $body;

    /**
     * @param EntityBodyInterface $body Entity body to decorate
     */
    public function __construct(EntityBodyInterface $body)
    {
        $this->body = $body;
    }

    public function __toString()
    {
        return (string) $this->body;
    }

    /**
     * Allow decorators to implement custom methods
     *
     * @param string $method Missing method name
     * @param array  $args   Method arguments
     *
     * @return mixed
     */
    public function __call($method, array $args)
    {
        return call_user_func_array(array($this->body, $method), $args);
    }

    public function close()
    {
        return $this->body->close();
    }

    public function setRewindFunction($callable)
    {
        $this->body->setRewindFunction($callable);

        return $this;
    }

    public function rewind()
    {
        return $this->body->rewind();
    }

    public function compress($filter = 'zlib.deflate')
    {
        return $this->body->compress($filter);
    }

    public function uncompress($filter = 'zlib.inflate')
    {
        return $this->body->uncompress($filter);
    }

    public function getContentLength()
    {
        return $this->getSize();
    }

    public function getContentType()
    {
        return $this->body->getContentType();
    }

    public function getContentMd5($rawOutput = false, $base64Encode = false)
    {
        $hash = Stream::getHash($this, 'md5', $rawOutput);

        return $hash && $base64Encode ? base64_encode($hash) : $hash;
    }

    public function getContentEncoding()
    {
        return $this->body->getContentEncoding();
    }

    public function getMetaData($key = null)
    {
        return $this->body->getMetaData($key);
    }

    public function getStream()
    {
        return $this->body->getStream();
    }

    public function setStream($stream, $size = 0)
    {
        $this->body->setStream($stream, $size);

        return $this;
    }

    public function detachStream()
    {
        $this->body->detachStream();

        return $this;
    }

    public function getWrapper()
    {
        return $this->body->getWrapper();
    }

    public function getWrapperData()
    {
        return $this->body->getWrapperData();
    }

    public function getStreamType()
    {
        return $this->body->getStreamType();
    }

    public function getUri()
    {
        return $this->body->getUri();
    }

    public function getSize()
    {
        return $this->body->getSize();
    }

    public function isReadable()
    {
        return $this->body->isReadable();
    }

    public function isRepeatable()
    {
        return $this->isSeekable() && $this->isReadable();
    }

    public function isWritable()
    {
        return $this->body->isWritable();
    }

    public function isConsumed()
    {
        return $this->body->isConsumed();
    }

    /**
     * Alias of isConsumed()
     * {@inheritdoc}
     */
    public function feof()
    {
        return $this->isConsumed();
    }

    public function isLocal()
    {
        return $this->body->isLocal();
    }

    public function isSeekable()
    {
        return $this->body->isSeekable();
    }

    public function setSize($size)
    {
        $this->body->setSize($size);

        return $this;
    }

    public function seek($offset, $whence = SEEK_SET)
    {
        return $this->body->seek($offset, $whence);
    }

    public function read($length)
    {
        return $this->body->read($length);
    }

    public function write($string)
    {
        return $this->body->write($string);
    }

    public function readLine($maxLength = null)
    {
        return $this->body->readLine($maxLength);
    }

    public function ftell()
    {
        return $this->body->ftell();
    }

    public function getCustomData($key)
    {
        return $this->body->getCustomData($key);
    }

    public function setCustomData($key, $value)
    {
        $this->body->setCustomData($key, $value);

        return $this;
    }
}
<?php

namespace Guzzle\Http;

use Guzzle\Stream\StreamInterface;

/**
 * EntityBody decorator used to return only a subset of an entity body
 */
class ReadLimitEntityBody extends AbstractEntityBodyDecorator
{
    /** @var int Limit the number of bytes that can be read */
    protected $limit;

    /** @var int Offset to start reading from */
    protected $offset;

    /**
     * @param EntityBodyInterface $body   Body to wrap
     * @param int                 $limit  Total number of bytes to allow to be read from the stream
     * @param int                 $offset Position to seek to before reading (only works on seekable streams)
     */
    public function __construct(EntityBodyInterface $body, $limit, $offset = 0)
    {
        parent::__construct($body);
        $this->setLimit($limit)->setOffset($offset);
    }

    /**
     * Returns only a subset of the decorated entity body when cast as a string
     * {@inheritdoc}
     */
    public function __toString()
    {
        if (!$this->body->isReadable() ||
            (!$this->body->isSeekable() && $this->body->isConsumed())
        ) {
            return '';
        }

        $originalPos = $this->body->ftell();
        $this->body->seek($this->offset);
        $data = '';
        while (!$this->feof()) {
            $data .= $this->read(1048576);
        }
        $this->body->seek($originalPos);

        return (string) $data ?: '';
    }

    public function isConsumed()
    {
        return $this->body->isConsumed() ||
            ($this->body->ftell() >= $this->offset + $this->limit);
    }

    /**
     * Returns the Content-Length of the limited subset of data
     * {@inheritdoc}
     */
    public function getContentLength()
    {
        $length = $this->body->getContentLength();

        return $length === false
            ? $this->limit
            : min($this->limit, min($length, $this->offset + $this->limit) - $this->offset);
    }

    /**
     * Allow for a bounded seek on the read limited entity body
     * {@inheritdoc}
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        return $whence === SEEK_SET
            ? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset)))
            : false;
    }

    /**
     * Set the offset to start limiting from
     *
     * @param int $offset Offset to seek to and begin byte limiting from
     *
     * @return self
     */
    public function setOffset($offset)
    {
        $this->body->seek($offset);
        $this->offset = $offset;

        return $this;
    }

    /**
     * Set the limit of bytes that the decorator allows to be read from the stream
     *
     * @param int $limit Total number of bytes to allow to be read from the stream
     *
     * @return self
     */
    public function setLimit($limit)
    {
        $this->limit = $limit;

        return $this;
    }

    public function read($length)
    {
        // Check if the current position is less than the total allowed bytes + original offset
        $remaining = ($this->offset + $this->limit) - $this->body->ftell();
        if ($remaining > 0) {
            // Only return the amount of requested data, ensuring that the byte limit is not exceeded
            return $this->body->read(min($remaining, $length));
        } else {
            return false;
        }
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Divides batches using a callable
 */
class BatchClosureDivisor implements BatchDivisorInterface
{
    /** @var callable Method used to divide the batches */
    protected $callable;

    /** @var mixed $context Context passed to the callable */
    protected $context;

    /**
     * @param callable $callable Method used to divide the batches. The method must accept an \SplQueue and return an
     *                           array of arrays containing the divided items.
     * @param mixed    $context  Optional context to pass to the batch divisor
     *
     * @throws InvalidArgumentException if the callable is not callable
     */
    public function __construct($callable, $context = null)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('Must pass a callable');
        }

        $this->callable = $callable;
        $this->context = $context;
    }

    public function createBatches(\SplQueue $queue)
    {
        return call_user_func($this->callable, $queue, $this->context);
    }
}
<?php

namespace Guzzle\Batch;

/**
 * Abstract decorator used when decorating a BatchInterface
 */
abstract class AbstractBatchDecorator implements BatchInterface
{
    /** @var BatchInterface Decorated batch object */
    protected $decoratedBatch;

    /**
     * @param BatchInterface $decoratedBatch  BatchInterface that is being decorated
     */
    public function __construct(BatchInterface $decoratedBatch)
    {
        $this->decoratedBatch = $decoratedBatch;
    }

    /**
     * Allow decorators to implement custom methods
     *
     * @param string $method Missing method name
     * @param array  $args   Method arguments
     *
     * @return mixed
     * @codeCoverageIgnore
     */
    public function __call($method, array $args)
    {
        return call_user_func_array(array($this->decoratedBatch, $method), $args);
    }

    public function add($item)
    {
        $this->decoratedBatch->add($item);

        return $this;
    }

    public function flush()
    {
        return $this->decoratedBatch->flush();
    }

    public function isEmpty()
    {
        return $this->decoratedBatch->isEmpty();
    }

    /**
     * Trace the decorators associated with the batch
     *
     * @return array
     */
    public function getDecorators()
    {
        $found = array($this);
        if (method_exists($this->decoratedBatch, 'getDecorators')) {
            $found = array_merge($found, $this->decoratedBatch->getDecorators());
        }

        return $found;
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Batch\Exception\BatchTransferException;

/**
 * Default batch implementation used to convert queued items into smaller chunks of batches using a
 * {@see BatchDivisorIterface} and transfers each batch using a {@see BatchTransferInterface}.
 *
 * Any exception encountered during a flush operation will throw a {@see BatchTransferException} object containing the
 * batch that failed. After an exception is encountered, you can flush the batch again to attempt to finish transferring
 * any previously created batches or queued items.
 */
class Batch implements BatchInterface
{
    /** @var \SplQueue Queue of items in the queue */
    protected $queue;

    /** @var array Divided batches to be transferred */
    protected $dividedBatches;

    /** @var BatchTransferInterface */
    protected $transferStrategy;

    /** @var BatchDivisorInterface */
    protected $divisionStrategy;

    /**
     * @param BatchTransferInterface $transferStrategy Strategy used to transfer items
     * @param BatchDivisorInterface  $divisionStrategy Divisor used to create batches
     */
    public function __construct(BatchTransferInterface $transferStrategy, BatchDivisorInterface $divisionStrategy)
    {
        $this->transferStrategy = $transferStrategy;
        $this->divisionStrategy = $divisionStrategy;
        $this->queue = new \SplQueue();
        $this->queue->setIteratorMode(\SplQueue::IT_MODE_DELETE);
        $this->dividedBatches = array();
    }

    public function add($item)
    {
        $this->queue->enqueue($item);

        return $this;
    }

    public function flush()
    {
        $this->createBatches();

        $items = array();
        foreach ($this->dividedBatches as $batchIndex => $dividedBatch) {
            while ($dividedBatch->valid()) {
                $batch = $dividedBatch->current();
                $dividedBatch->next();
                try {
                    $this->transferStrategy->transfer($batch);
                    $items = array_merge($items, $batch);
                } catch (\Exception $e) {
                    throw new BatchTransferException($batch, $items, $e, $this->transferStrategy, $this->divisionStrategy);
                }
            }
            // Keep the divided batch down to a minimum in case of a later exception
            unset($this->dividedBatches[$batchIndex]);
        }

        return $items;
    }

    public function isEmpty()
    {
        return count($this->queue) == 0 && count($this->dividedBatches) == 0;
    }

    /**
     * Create batches for any queued items
     */
    protected function createBatches()
    {
        if (count($this->queue)) {
            if ($batches = $this->divisionStrategy->createBatches($this->queue)) {
                // Convert arrays into iterators
                if (is_array($batches)) {
                    $batches = new \ArrayIterator($batches);
                }
                $this->dividedBatches[] = $batches;
            }
        }
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Batch\BatchTransferInterface;
use Guzzle\Batch\BatchDivisorInterface;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;

/**
 * Batch transfer strategy used to efficiently transfer a batch of requests.
 * This class is to be used with {@see Guzzle\Batch\BatchInterface}
 */
class BatchRequestTransfer implements BatchTransferInterface, BatchDivisorInterface
{
    /** @var int Size of each command batch */
    protected $batchSize;

    /**
     * Constructor used to specify how large each batch should be
     *
     * @param int $batchSize Size of each batch
     */
    public function __construct($batchSize = 50)
    {
        $this->batchSize = $batchSize;
    }

    /**
     * Creates batches of requests by grouping requests by their associated curl multi object.
     * {@inheritdoc}
     */
    public function createBatches(\SplQueue $queue)
    {
        // Create batches by client objects
        $groups = new \SplObjectStorage();
        foreach ($queue as $item) {
            if (!$item instanceof RequestInterface) {
                throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
            }
            $client = $item->getClient();
            if (!$groups->contains($client)) {
                $groups->attach($client, array($item));
            } else {
                $current = $groups[$client];
                $current[] = $item;
                $groups[$client] = $current;
            }
        }

        $batches = array();
        foreach ($groups as $batch) {
            $batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize));
        }

        return $batches;
    }

    public function transfer(array $batch)
    {
        if ($batch) {
            reset($batch)->getClient()->send($batch);
        }
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * BatchInterface decorator used to call a method each time flush is called
 */
class NotifyingBatch extends AbstractBatchDecorator
{
    /** @var mixed Callable to call */
    protected $callable;

    /**
     * @param BatchInterface $decoratedBatch Batch object to decorate
     * @param mixed          $callable       Callable to call
     *
     * @throws InvalidArgumentException
     */
    public function __construct(BatchInterface $decoratedBatch, $callable)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('The passed argument is not callable');
        }

        $this->callable = $callable;
        parent::__construct($decoratedBatch);
    }

    public function flush()
    {
        $items = $this->decoratedBatch->flush();
        call_user_func($this->callable, $items);

        return $items;
    }
}
<?php

namespace Guzzle\Batch;

/**
 * Divides batches into smaller batches under a certain size
 */
class BatchSizeDivisor implements BatchDivisorInterface
{
    /** @var int Size of each batch */
    protected $size;

    /** @param int $size Size of each batch */
    public function __construct($size)
    {
        $this->size = $size;
    }

    /**
     * Set the size of each batch
     *
     * @param int $size Size of each batch
     *
     * @return BatchSizeDivisor
     */
    public function setSize($size)
    {
        $this->size = $size;

        return $this;
    }

    /**
     * Get the size of each batch
     *
     * @return int
     */
    public function getSize()
    {
        return $this->size;
    }

    public function createBatches(\SplQueue $queue)
    {
        return array_chunk(iterator_to_array($queue, false), $this->size);
    }
}
<?php

namespace Guzzle\Batch;

/**
 * Interface used for dividing a queue of items into an array of batches
 */
interface BatchDivisorInterface
{
    /**
     * Divide a queue of items into an array batches
     *
     * @param \SplQueue $queue Queue of items to divide into batches. Items are removed as they are iterated.
     *
     * @return array|\Traversable Returns an array or Traversable object that contains arrays of items to transfer
     */
    public function createBatches(\SplQueue $queue);
}
<?php

namespace Guzzle\Batch;

/**
 * Interface for efficiently transferring items in a queue using batches
 */
interface BatchInterface
{
    /**
     * Add an item to the queue
     *
     * @param mixed $item Item to add
     *
     * @return self
     */
    public function add($item);

    /**
     * Flush the batch and transfer the items
     *
     * @return array Returns an array flushed items
     */
    public function flush();

    /**
     * Check if the batch is empty and has further items to transfer
     *
     * @return bool
     */
    public function isEmpty();
}
<?php

namespace Guzzle\Batch;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Batch transfer strategy where transfer logic can be defined via a Closure.
 * This class is to be used with {@see Guzzle\Batch\BatchInterface}
 */
class BatchClosureTransfer implements BatchTransferInterface
{
    /** @var callable A closure that performs the transfer */
    protected $callable;

    /** @var mixed $context Context passed to the callable */
    protected $context;

    /**
     * @param mixed $callable Callable that performs the transfer. This function should accept two arguments:
     *                        (array $batch, mixed $context).
     * @param mixed $context  Optional context to pass to the batch divisor
     *
     * @throws InvalidArgumentException
     */
    public function __construct($callable, $context = null)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('Argument must be callable');
        }

        $this->callable = $callable;
        $this->context = $context;
    }

    public function transfer(array $batch)
    {
        return empty($batch) ? null : call_user_func($this->callable, $batch, $this->context);
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Batch\BatchTransferInterface;
use Guzzle\Batch\BatchDivisorInterface;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Exception\InconsistentClientTransferException;

/**
 * Efficiently transfers multiple commands in parallel per client
 * This class is to be used with {@see Guzzle\Batch\BatchInterface}
 */
class BatchCommandTransfer implements BatchTransferInterface, BatchDivisorInterface
{
    /** @var int Size of each command batch */
    protected $batchSize;

    /**
     * @param int $batchSize Size of each batch
     */
    public function __construct($batchSize = 50)
    {
        $this->batchSize = $batchSize;
    }

    /**
     * Creates batches by grouping commands by their associated client
     * {@inheritdoc}
     */
    public function createBatches(\SplQueue $queue)
    {
        $groups = new \SplObjectStorage();
        foreach ($queue as $item) {
            if (!$item instanceof CommandInterface) {
                throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface');
            }
            $client = $item->getClient();
            if (!$groups->contains($client)) {
                $groups->attach($client, new \ArrayObject(array($item)));
            } else {
                $groups[$client]->append($item);
            }
        }

        $batches = array();
        foreach ($groups as $batch) {
            $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize));
        }

        return $batches;
    }

    public function transfer(array $batch)
    {
        if (empty($batch)) {
            return;
        }

        // Get the client of the first found command
        $client = reset($batch)->getClient();

        // Keep a list of all commands with invalid clients
        $invalid = array_filter($batch, function ($command) use ($client) {
            return $command->getClient() !== $client;
        });

        if (!empty($invalid)) {
            throw new InconsistentClientTransferException($invalid);
        }

        $client->execute($batch);
    }
}
<?php

namespace Guzzle\Batch;

/**
 * BatchInterface decorator used to add automatic flushing of the queue when the size of the queue reaches a threshold.
 */
class FlushingBatch extends AbstractBatchDecorator
{
    /** @var int The threshold for which to automatically flush */
    protected $threshold;

    /** @var int Current number of items known to be in the queue */
    protected $currentTotal = 0;

    /**
     * @param BatchInterface $decoratedBatch  BatchInterface that is being decorated
     * @param int            $threshold       Flush when the number in queue matches the threshold
     */
    public function __construct(BatchInterface $decoratedBatch, $threshold)
    {
        $this->threshold = $threshold;
        parent::__construct($decoratedBatch);
    }

    /**
     * Set the auto-flush threshold
     *
     * @param int $threshold The auto-flush threshold
     *
     * @return FlushingBatch
     */
    public function setThreshold($threshold)
    {
        $this->threshold = $threshold;

        return $this;
    }

    /**
     * Get the auto-flush threshold
     *
     * @return int
     */
    public function getThreshold()
    {
        return $this->threshold;
    }

    public function add($item)
    {
        $this->decoratedBatch->add($item);
        if (++$this->currentTotal >= $this->threshold) {
            $this->currentTotal = 0;
            $this->decoratedBatch->flush();
        }

        return $this;
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Batch\Exception\BatchTransferException;

/**
 * BatchInterface decorator used to buffer exceptions encountered during a transfer.  The exceptions can then later be
 * processed after a batch flush has completed.
 */
class ExceptionBufferingBatch extends AbstractBatchDecorator
{
    /** @var array Array of BatchTransferException exceptions */
    protected $exceptions = array();

    public function flush()
    {
        $items = array();

        while (!$this->decoratedBatch->isEmpty()) {
            try {
                $transferredItems = $this->decoratedBatch->flush();
            } catch (BatchTransferException $e) {
                $this->exceptions[] = $e;
                $transferredItems = $e->getTransferredItems();
            }
            $items = array_merge($items, $transferredItems);
        }

        return $items;
    }

    /**
     * Get the buffered exceptions
     *
     * @return array Array of BatchTransferException objects
     */
    public function getExceptions()
    {
        return $this->exceptions;
    }

    /**
     * Clear the buffered exceptions
     */
    public function clearExceptions()
    {
        $this->exceptions = array();
    }
}
<?php

namespace Guzzle\Batch;

/**
 * BatchInterface decorator used to keep a history of items that were added to the batch.  You must clear the history
 * manually to remove items from the history.
 */
class HistoryBatch extends AbstractBatchDecorator
{
    /** @var array Items in the history */
    protected $history = array();

    public function add($item)
    {
        $this->history[] = $item;
        $this->decoratedBatch->add($item);

        return $this;
    }

    /**
     * Get the batch history
     *
     * @return array
     */
    public function getHistory()
    {
        return $this->history;
    }

    /**
     * Clear the batch history
     */
    public function clearHistory()
    {
        $this->history = array();
    }
}
<?php

namespace Guzzle\Batch\Exception;

use Guzzle\Common\Exception\GuzzleException;
use Guzzle\Batch\BatchTransferInterface as TransferStrategy;
use Guzzle\Batch\BatchDivisorInterface as DivisorStrategy;

/**
 * Exception thrown during a batch transfer
 */
class BatchTransferException extends \Exception implements GuzzleException
{
    /** @var array The batch being sent when the exception occurred */
    protected $batch;

    /** @var TransferStrategy The transfer strategy in use when the exception occurred */
    protected $transferStrategy;

    /** @var DivisorStrategy The divisor strategy in use when the exception occurred */
    protected $divisorStrategy;

    /** @var array Items transferred at the point in which the exception was encountered */
    protected $transferredItems;

    /**
     * @param array            $batch            The batch being sent when the exception occurred
     * @param array            $transferredItems Items transferred at the point in which the exception was encountered
     * @param \Exception       $exception        Exception encountered
     * @param TransferStrategy $transferStrategy The transfer strategy in use when the exception occurred
     * @param DivisorStrategy  $divisorStrategy  The divisor strategy in use when the exception occurred
     */
    public function __construct(
        array $batch,
        array $transferredItems,
        \Exception $exception,
        TransferStrategy $transferStrategy = null,
        DivisorStrategy $divisorStrategy = null
    ) {
        $this->batch = $batch;
        $this->transferredItems = $transferredItems;
        $this->transferStrategy = $transferStrategy;
        $this->divisorStrategy = $divisorStrategy;
        parent::__construct(
            'Exception encountered while transferring batch: ' . $exception->getMessage(),
            $exception->getCode(),
            $exception
        );
    }

    /**
     * Get the batch that we being sent when the exception occurred
     *
     * @return array
     */
    public function getBatch()
    {
        return $this->batch;
    }

    /**
     * Get the items transferred at the point in which the exception was encountered
     *
     * @return array
     */
    public function getTransferredItems()
    {
        return $this->transferredItems;
    }

    /**
     * Get the transfer strategy
     *
     * @return TransferStrategy
     */
    public function getTransferStrategy()
    {
        return $this->transferStrategy;
    }

    /**
     * Get the divisor strategy
     *
     * @return DivisorStrategy
     */
    public function getDivisorStrategy()
    {
        return $this->divisorStrategy;
    }
}
<?php

namespace Guzzle\Batch;

/**
 * Interface used for transferring batches of items
 */
interface BatchTransferInterface
{
    /**
     * Transfer an array of items
     *
     * @param array $batch Array of items to transfer
     */
    public function transfer(array $batch);
}
{
    "name": "guzzle/batch",
    "description": "Guzzle batch component for batching requests, commands, or custom transfers",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["batch", "HTTP", "REST", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/common": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Batch": "" }
    },
    "suggest": {
        "guzzle/http": "self.version",
        "guzzle/service": "self.version"
    },
    "target-dir": "Guzzle/Batch",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Batch;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;

/**
 * Builder used to create custom batch objects
 */
class BatchBuilder
{
    /** @var bool Whether or not the batch should automatically flush*/
    protected $autoFlush = false;

    /** @var bool Whether or not to maintain a batch history */
    protected $history = false;

    /** @var bool Whether or not to buffer exceptions encountered in transfer */
    protected $exceptionBuffering = false;

    /** @var mixed Callable to invoke each time a flush completes */
    protected $afterFlush;

    /** @var BatchTransferInterface Object used to transfer items in the queue */
    protected $transferStrategy;

    /** @var BatchDivisorInterface Object used to divide the queue into batches */
    protected $divisorStrategy;

    /** @var array of Mapped transfer strategies by handle name */
    protected static $mapping = array(
        'request' => 'Guzzle\Batch\BatchRequestTransfer',
        'command' => 'Guzzle\Batch\BatchCommandTransfer'
    );

    /**
     * Create a new instance of the BatchBuilder
     *
     * @return BatchBuilder
     */
    public static function factory()
    {
        return new self();
    }

    /**
     * Automatically flush the batch when the size of the queue reaches a certain threshold. Adds {@see FlushingBatch}.
     *
     * @param $threshold Number of items to allow in the queue before a flush
     *
     * @return BatchBuilder
     */
    public function autoFlushAt($threshold)
    {
        $this->autoFlush = $threshold;

        return $this;
    }

    /**
     * Maintain a history of all items that have been transferred using the batch. Adds {@see HistoryBatch}.
     *
     * @return BatchBuilder
     */
    public function keepHistory()
    {
        $this->history = true;

        return $this;
    }

    /**
     * Buffer exceptions thrown during transfer so that you can transfer as much as possible, and after a transfer
     * completes, inspect each exception that was thrown. Enables the {@see ExceptionBufferingBatch} decorator.
     *
     * @return BatchBuilder
     */
    public function bufferExceptions()
    {
        $this->exceptionBuffering = true;

        return $this;
    }

    /**
     * Notify a callable each time a batch flush completes. Enables the {@see NotifyingBatch} decorator.
     *
     * @param mixed $callable Callable function to notify
     *
     * @return BatchBuilder
     * @throws InvalidArgumentException if the argument is not callable
     */
    public function notify($callable)
    {
        $this->afterFlush = $callable;

        return $this;
    }

    /**
     * Configures the batch to transfer batches of requests. Associates a {@see \Guzzle\Http\BatchRequestTransfer}
     * object as both the transfer and divisor strategy.
     *
     * @param int $batchSize Batch size for each batch of requests
     *
     * @return BatchBuilder
     */
    public function transferRequests($batchSize = 50)
    {
        $className = self::$mapping['request'];
        $this->transferStrategy = new $className($batchSize);
        $this->divisorStrategy = $this->transferStrategy;

        return $this;
    }

    /**
     * Configures the batch to transfer batches commands. Associates as
     * {@see \Guzzle\Service\Command\BatchCommandTransfer} as both the transfer and divisor strategy.
     *
     * @param int $batchSize Batch size for each batch of commands
     *
     * @return BatchBuilder
     */
    public function transferCommands($batchSize = 50)
    {
        $className = self::$mapping['command'];
        $this->transferStrategy = new $className($batchSize);
        $this->divisorStrategy = $this->transferStrategy;

        return $this;
    }

    /**
     * Specify the strategy used to divide the queue into an array of batches
     *
     * @param BatchDivisorInterface $divisorStrategy Strategy used to divide a batch queue into batches
     *
     * @return BatchBuilder
     */
    public function createBatchesWith(BatchDivisorInterface $divisorStrategy)
    {
        $this->divisorStrategy = $divisorStrategy;

        return $this;
    }

    /**
     * Specify the strategy used to transport the items when flush is called
     *
     * @param BatchTransferInterface $transferStrategy How items are transferred
     *
     * @return BatchBuilder
     */
    public function transferWith(BatchTransferInterface $transferStrategy)
    {
        $this->transferStrategy = $transferStrategy;

        return $this;
    }

    /**
     * Create and return the instantiated batch
     *
     * @return BatchInterface
     * @throws RuntimeException if no transfer strategy has been specified
     */
    public function build()
    {
        if (!$this->transferStrategy) {
            throw new RuntimeException('No transfer strategy has been specified');
        }

        if (!$this->divisorStrategy) {
            throw new RuntimeException('No divisor strategy has been specified');
        }

        $batch = new Batch($this->transferStrategy, $this->divisorStrategy);

        if ($this->exceptionBuffering) {
            $batch = new ExceptionBufferingBatch($batch);
        }

        if ($this->afterFlush) {
            $batch = new NotifyingBatch($batch, $this->afterFlush);
        }

        if ($this->autoFlush) {
            $batch = new FlushingBatch($batch, $this->autoFlush);
        }

        if ($this->history) {
            $batch = new HistoryBatch($batch);
        }

        return $batch;
    }
}
<?php

namespace Guzzle\Log;

/**
 * Adapter class that allows Guzzle to log data to various logging implementations.
 */
interface LogAdapterInterface
{
    /**
     * Log a message at a priority
     *
     * @param string  $message  Message to log
     * @param integer $priority Priority of message (use the \LOG_* constants of 0 - 7)
     * @param array   $extras   Extra information to log in event
     */
    public function log($message, $priority = LOG_INFO, $extras = array());
}
<?php

namespace Guzzle\Log;

use Monolog\Logger;

/**
 * @deprecated
 * @codeCoverageIgnore
 */
class MonologLogAdapter extends AbstractLogAdapter
{
    /**
     * syslog to Monolog mappings
     */
    private static $mapping = array(
        LOG_DEBUG   => Logger::DEBUG,
        LOG_INFO    => Logger::INFO,
        LOG_WARNING => Logger::WARNING,
        LOG_ERR     => Logger::ERROR,
        LOG_CRIT    => Logger::CRITICAL,
        LOG_ALERT   => Logger::ALERT
    );

    public function __construct(Logger $logObject)
    {
        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->addRecord(self::$mapping[$priority], $message, $extras);
    }
}
<?php

namespace Guzzle\Log;

/**
 * Logs messages using Closures. Closures combined with filtering can trigger application events based on log messages.
 */
class ClosureLogAdapter extends AbstractLogAdapter
{
    public function __construct($logObject)
    {
        if (!is_callable($logObject)) {
            throw new \InvalidArgumentException('Object must be callable');
        }

        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        call_user_func($this->log, $message, $priority, $extras);
    }
}
<?php

namespace Guzzle\Log;

/**
 * Stores all log messages in an array
 */
class ArrayLogAdapter implements LogAdapterInterface
{
    protected $logs = array();

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->logs[] = array('message' => $message, 'priority' => $priority, 'extras' => $extras);
    }

    /**
     * Get logged entries
     *
     * @return array
     */
    public function getLogs()
    {
        return $this->logs;
    }

    /**
     * Clears logged entries
     */
    public function clearLogs()
    {
        $this->logs = array();
    }
}
<?php

namespace Guzzle\Log;

use Psr\Log\LogLevel;
use Psr\Log\LoggerInterface;

/**
 * PSR-3 log adapter
 *
 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
 */
class PsrLogAdapter extends AbstractLogAdapter
{
    /**
     * syslog to PSR-3 mappings
     */
    private static $mapping = array(
        LOG_DEBUG   => LogLevel::DEBUG,
        LOG_INFO    => LogLevel::INFO,
        LOG_WARNING => LogLevel::WARNING,
        LOG_ERR     => LogLevel::ERROR,
        LOG_CRIT    => LogLevel::CRITICAL,
        LOG_ALERT   => LogLevel::ALERT
    );

    public function __construct(LoggerInterface $logObject)
    {
        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->log(self::$mapping[$priority], $message, $extras);
    }
}
<?php

namespace Guzzle\Log;

/**
 * Adapter class that allows Guzzle to log data using various logging implementations
 */
abstract class AbstractLogAdapter implements LogAdapterInterface
{
    protected $log;

    public function getLogObject()
    {
        return $this->log;
    }
}
<?php

namespace Guzzle\Log;

use Zend\Log\Logger;

/**
 * Adapts a Zend Framework 2 logger object
 */
class Zf2LogAdapter extends AbstractLogAdapter
{
    public function __construct(Logger $logObject)
    {
        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->log($priority, $message, $extras);
    }
}
<?php

namespace Guzzle\Log;

use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Message formatter used in various places in the framework
 *
 * Format messages using a template that can contain the the following variables:
 *
 * - {request}:       Full HTTP request message
 * - {response}:      Full HTTP response message
 * - {ts}:            Timestamp
 * - {host}:          Host of the request
 * - {method}:        Method of the request
 * - {url}:           URL of the request
 * - {host}:          Host of the request
 * - {protocol}:      Request protocol
 * - {version}:       Protocol version
 * - {resource}:      Resource of the request (path + query + fragment)
 * - {port}:          Port of the request
 * - {hostname}:      Hostname of the machine that sent the request
 * - {code}:          Status code of the response (if available)
 * - {phrase}:        Reason phrase of the response  (if available)
 * - {curl_error}:    Curl error message (if available)
 * - {curl_code}:     Curl error code (if available)
 * - {curl_stderr}:   Curl standard error (if available)
 * - {connect_time}:  Time in seconds it took to establish the connection (if available)
 * - {total_time}:    Total transaction time in seconds for last transfer (if available)
 * - {req_header_*}:  Replace `*` with the lowercased name of a request header to add to the message
 * - {res_header_*}:  Replace `*` with the lowercased name of a response header to add to the message
 * - {req_body}:      Request body
 * - {res_body}:      Response body
 */
class MessageFormatter
{
    const DEFAULT_FORMAT = "{hostname} {req_header_User-Agent} - [{ts}] \"{method} {resource} {protocol}/{version}\" {code} {res_header_Content-Length}";
    const DEBUG_FORMAT = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{curl_stderr}";
    const SHORT_FORMAT = '[{ts}] "{method} {resource} {protocol}/{version}" {code}';

    /**
     * @var string Template used to format log messages
     */
    protected $template;

    /**
     * @param string $template Log message template
     */
    public function __construct($template = self::DEFAULT_FORMAT)
    {
        $this->template = $template ?: self::DEFAULT_FORMAT;
    }

    /**
     * Set the template to use for logging
     *
     * @param string $template Log message template
     *
     * @return self
     */
    public function setTemplate($template)
    {
        $this->template = $template;

        return $this;
    }

    /**
     * Returns a formatted message
     *
     * @param RequestInterface $request    Request that was sent
     * @param Response         $response   Response that was received
     * @param CurlHandle       $handle     Curl handle associated with the message
     * @param array            $customData Associative array of custom template data
     *
     * @return string
     */
    public function format(
        RequestInterface $request,
        Response $response = null,
        CurlHandle $handle = null,
        array $customData = array()
    ) {
        $cache = $customData;

        return preg_replace_callback(
            '/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
            function (array $matches) use ($request, $response, $handle, &$cache) {

                if (array_key_exists($matches[1], $cache)) {
                    return $cache[$matches[1]];
                }

                $result = '';
                switch ($matches[1]) {
                    case 'request':
                        $result = (string) $request;
                        break;
                    case 'response':
                        $result = (string) $response;
                        break;
                    case 'req_body':
                        $result = $request instanceof EntityEnclosingRequestInterface
                            ? (string) $request->getBody() : '';
                        break;
                    case 'res_body':
                        $result = $response ? $response->getBody(true) : '';
                        break;
                    case 'ts':
                        $result = gmdate('c');
                        break;
                    case 'method':
                        $result = $request->getMethod();
                        break;
                    case 'url':
                        $result = (string) $request->getUrl();
                        break;
                    case 'resource':
                        $result = $request->getResource();
                        break;
                    case 'protocol':
                        $result = 'HTTP';
                        break;
                    case 'version':
                        $result = $request->getProtocolVersion();
                        break;
                    case 'host':
                        $result = $request->getHost();
                        break;
                    case 'hostname':
                        $result = gethostname();
                        break;
                    case 'port':
                        $result = $request->getPort();
                        break;
                    case 'code':
                        $result = $response ? $response->getStatusCode() : '';
                        break;
                    case 'phrase':
                        $result = $response ? $response->getReasonPhrase() : '';
                        break;
                    case 'connect_time':
                        $result = $handle && $handle->getInfo(CURLINFO_CONNECT_TIME)
                            ? $handle->getInfo(CURLINFO_CONNECT_TIME)
                            : ($response ? $response->getInfo('connect_time') : '');
                        break;
                    case 'total_time':
                        $result = $handle && $handle->getInfo(CURLINFO_TOTAL_TIME)
                            ? $handle->getInfo(CURLINFO_TOTAL_TIME)
                            : ($response ? $response->getInfo('total_time') : '');
                        break;
                    case 'curl_error':
                        $result = $handle ? $handle->getError() : '';
                        break;
                    case 'curl_code':
                        $result = $handle ? $handle->getErrorNo() : '';
                        break;
                    case 'curl_stderr':
                        $result =  $handle ? $handle->getStderr() : '';
                        break;
                    default:
                        if (strpos($matches[1], 'req_header_') === 0) {
                            $result = $request->getHeader(substr($matches[1], 11));
                        } elseif ($response && strpos($matches[1], 'res_header_') === 0) {
                            $result = $response->getHeader(substr($matches[1], 11));
                        }
                }

                $cache[$matches[1]] = $result;
                return $result;
            },
            $this->template
        );
    }
}
<?php

namespace Guzzle\Log;

use Guzzle\Common\Version;

/**
 * Adapts a Zend Framework 1 logger object
 * @deprecated
 * @codeCoverageIgnore
 */
class Zf1LogAdapter extends AbstractLogAdapter
{
    public function __construct(\Zend_Log $logObject)
    {
        $this->log = $logObject;
        Version::warn(__CLASS__ . ' is deprecated');
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->log($message, $priority, $extras);
    }
}
{
    "name": "guzzle/log",
    "description": "Guzzle log adapter component",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["log", "adapter", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Log": "" }
    },
    "suggest": {
        "guzzle/http": "self.version"
    },
    "target-dir": "Guzzle/Log",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Service;

/**
 * Interface used for loading configuration data (service descriptions, service builder configs, etc)
 *
 * If a loaded configuration data sets includes a top level key containing an 'includes' section, then the data in the
 * file will extend the merged result of all of the included config files.
 */
interface ConfigLoaderInterface
{
    /**
     * Loads configuration data and returns an array of the loaded result
     *
     * @param mixed $config  Data to load (filename or array of data)
     * @param array $options Array of options to use when loading
     *
     * @return mixed
     */
    public function load($config, array $options = array());
}
<?php

namespace Guzzle\Service;

use Guzzle\Cache\CacheAdapterInterface;

/**
 * Decorator that adds caching to a service description loader
 */
class CachingConfigLoader implements ConfigLoaderInterface
{
    /** @var ConfigLoaderInterface */
    protected $loader;

    /** @var CacheAdapterInterface */
    protected $cache;

    /**
     * @param ConfigLoaderInterface $loader Loader used to load the config when there is a cache miss
     * @param CacheAdapterInterface $cache  Object used to cache the loaded result
     */
    public function __construct(ConfigLoaderInterface $loader, CacheAdapterInterface $cache)
    {
        $this->loader = $loader;
        $this->cache = $cache;
    }

    public function load($config, array $options = array())
    {
        if (!is_string($config)) {
            $key = false;
        } else {
            $key = 'loader_' . crc32($config);
            if ($result = $this->cache->fetch($key)) {
                return $result;
            }
        }

        $result = $this->loader->load($config, $options);
        if ($key) {
            $this->cache->save($key, $result);
        }

        return $result;
    }
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * JSON Schema formatter class
 */
class SchemaFormatter
{
    /** @var \DateTimeZone */
    protected static $utcTimeZone;

    /**
     * Format a value by a registered format name
     *
     * @param string $format Registered format used to format the value
     * @param mixed  $value  Value being formatted
     *
     * @return mixed
     */
    public static function format($format, $value)
    {
        switch ($format) {
            case 'date-time':
                return self::formatDateTime($value);
            case 'date-time-http':
                return self::formatDateTimeHttp($value);
            case 'date':
                return self::formatDate($value);
            case 'time':
                return self::formatTime($value);
            case 'timestamp':
                return self::formatTimestamp($value);
            case 'boolean-string':
                return self::formatBooleanAsString($value);
            default:
                return $value;
        }
    }

    /**
     * Create a ISO 8601 (YYYY-MM-DDThh:mm:ssZ) formatted date time value in UTC time
     *
     * @param string|integer|\DateTime $value Date time value
     *
     * @return string
     */
    public static function formatDateTime($value)
    {
        return self::dateFormatter($value, 'Y-m-d\TH:i:s\Z');
    }

    /**
     * Create an HTTP date (RFC 1123 / RFC 822) formatted UTC date-time string
     *
     * @param string|integer|\DateTime $value Date time value
     *
     * @return string
     */
    public static function formatDateTimeHttp($value)
    {
        return self::dateFormatter($value, 'D, d M Y H:i:s \G\M\T');
    }

    /**
     * Create a YYYY-MM-DD formatted string
     *
     * @param string|integer|\DateTime $value Date time value
     *
     * @return string
     */
    public static function formatDate($value)
    {
        return self::dateFormatter($value, 'Y-m-d');
    }

    /**
     * Create a hh:mm:ss formatted string
     *
     * @param string|integer|\DateTime $value Date time value
     *
     * @return string
     */
    public static function formatTime($value)
    {
        return self::dateFormatter($value, 'H:i:s');
    }

    /**
     * Formats a boolean value as a string
     *
     * @param string|integer|bool $value Value to convert to a boolean 'true' / 'false' value
     *
     * @return string
     */
    public static function formatBooleanAsString($value)
    {
        return filter_var($value, FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false';
    }

    /**
     * Return a UNIX timestamp in the UTC timezone
     *
     * @param string|integer|\DateTime $value Time value
     *
     * @return int
     */
    public static function formatTimestamp($value)
    {
        return (int) self::dateFormatter($value, 'U');
    }

    /**
     * Get a UTC DateTimeZone object
     *
     * @return \DateTimeZone
     */
    protected static function getUtcTimeZone()
    {
        // @codeCoverageIgnoreStart
        if (!self::$utcTimeZone) {
            self::$utcTimeZone = new \DateTimeZone('UTC');
        }
        // @codeCoverageIgnoreEnd

        return self::$utcTimeZone;
    }

    /**
     * Perform the actual DateTime formatting
     *
     * @param int|string|\DateTime $dateTime Date time value
     * @param string               $format   Format of the result
     *
     * @return string
     * @throws InvalidArgumentException
     */
    protected static function dateFormatter($dateTime, $format)
    {
        if (is_numeric($dateTime)) {
            return gmdate($format, (int) $dateTime);
        }

        if (is_string($dateTime)) {
            $dateTime = new \DateTime($dateTime);
        }

        if ($dateTime instanceof \DateTime) {
            return $dateTime->setTimezone(self::getUtcTimeZone())->format($format);
        }

        throw new InvalidArgumentException('Date/Time values must be either a string, integer, or DateTime object');
    }
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\ToArrayInterface;

/**
 * Default parameter validator
 */
class SchemaValidator implements ValidatorInterface
{
    /** @var self Cache instance of the object */
    protected static $instance;

    /** @var bool Whether or not integers are converted to strings when an integer is received for a string input */
    protected $castIntegerToStringType;

    /** @var array Errors encountered while validating */
    protected $errors;

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * @param bool $castIntegerToStringType Set to true to convert integers into strings when a required type is a
     *                                      string and the input value is an integer. Defaults to true.
     */
    public function __construct($castIntegerToStringType = true)
    {
        $this->castIntegerToStringType = $castIntegerToStringType;
    }

    public function validate(Parameter $param, &$value)
    {
        $this->errors = array();
        $this->recursiveProcess($param, $value);

        if (empty($this->errors)) {
            return true;
        } else {
            sort($this->errors);
            return false;
        }
    }

    /**
     * Get the errors encountered while validating
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors ?: array();
    }

    /**
     * Recursively validate a parameter
     *
     * @param Parameter $param  API parameter being validated
     * @param mixed     $value  Value to validate and validate. The value may change during this validate.
     * @param string    $path   Current validation path (used for error reporting)
     * @param int       $depth  Current depth in the validation validate
     *
     * @return bool Returns true if valid, or false if invalid
     */
    protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0)
    {
        // Update the value by adding default or static values
        $value = $param->getValue($value);

        $required = $param->getRequired();
        // if the value is null and the parameter is not required or is static, then skip any further recursion
        if ((null === $value && !$required) || $param->getStatic()) {
            return true;
        }

        $type = $param->getType();
        // Attempt to limit the number of times is_array is called by tracking if the value is an array
        $valueIsArray = is_array($value);
        // If a name is set then update the path so that validation messages are more helpful
        if ($name = $param->getName()) {
            $path .= "[{$name}]";
        }

        if ($type == 'object') {

            // Objects are either associative arrays, ToArrayInterface, or some other object
            if ($param->getInstanceOf()) {
                $instance = $param->getInstanceOf();
                if (!($value instanceof $instance)) {
                    $this->errors[] = "{$path} must be an instance of {$instance}";
                    return false;
                }
            }

            // Determine whether or not this "value" has properties and should be traversed
            $traverse = $temporaryValue = false;

            // Convert the value to an array
            if (!$valueIsArray && $value instanceof ToArrayInterface) {
                $value = $value->toArray();
            }

            if ($valueIsArray) {
                // Ensure that the array is associative and not numerically indexed
                if (isset($value[0])) {
                    $this->errors[] = "{$path} must be an array of properties. Got a numerically indexed array.";
                    return false;
                }
                $traverse = true;
            } elseif ($value === null) {
                // Attempt to let the contents be built up by default values if possible
                $value = array();
                $temporaryValue = $valueIsArray = $traverse = true;
            }

            if ($traverse) {

                if ($properties = $param->getProperties()) {
                    // if properties were found, the validate each property of the value
                    foreach ($properties as $property) {
                        $name = $property->getName();
                        if (isset($value[$name])) {
                            $this->recursiveProcess($property, $value[$name], $path, $depth + 1);
                        } else {
                            $current = null;
                            $this->recursiveProcess($property, $current, $path, $depth + 1);
                            // Only set the value if it was populated with something
                            if (null !== $current) {
                                $value[$name] = $current;
                            }
                        }
                    }
                }

                $additional = $param->getAdditionalProperties();
                if ($additional !== true) {
                    // If additional properties were found, then validate each against the additionalProperties attr.
                    $keys = array_keys($value);
                    // Determine the keys that were specified that were not listed in the properties of the schema
                    $diff = array_diff($keys, array_keys($properties));
                    if (!empty($diff)) {
                        // Determine which keys are not in the properties
                        if ($additional instanceOf Parameter) {
                            foreach ($diff as $key) {
                                $this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth);
                            }
                        } else {
                            // if additionalProperties is set to false and there are additionalProperties in the values, then fail
                            foreach ($diff as $prop) {
                                $this->errors[] = sprintf('%s[%s] is not an allowed property', $path, $prop);
                            }
                        }
                    }
                }

                // A temporary value will be used to traverse elements that have no corresponding input value.
                // This allows nested required parameters with default values to bubble up into the input.
                // Here we check if we used a temp value and nothing bubbled up, then we need to remote the value.
                if ($temporaryValue && empty($value)) {
                    $value = null;
                    $valueIsArray = false;
                }
            }

        } elseif ($type == 'array' && $valueIsArray && $param->getItems()) {
            foreach ($value as $i => &$item) {
                // Validate each item in an array against the items attribute of the schema
                $this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1);
            }
        }

        // If the value is required and the type is not null, then there is an error if the value is not set
        if ($required && $value === null && $type != 'null') {
            $message = "{$path} is " . ($param->getType() ? ('a required ' . implode(' or ', (array) $param->getType())) : 'required');
            if ($param->getDescription()) {
                $message .= ': ' . $param->getDescription();
            }
            $this->errors[] = $message;
            return false;
        }

        // Validate that the type is correct. If the type is string but an integer was passed, the class can be
        // instructed to cast the integer to a string to pass validation. This is the default behavior.
        if ($type && (!$type = $this->determineType($type, $value))) {
            if ($this->castIntegerToStringType && $param->getType() == 'string' && is_integer($value)) {
                $value = (string) $value;
            } else {
                $this->errors[] = "{$path} must be of type " . implode(' or ', (array) $param->getType());
            }
        }

        // Perform type specific validation for strings, arrays, and integers
        if ($type == 'string') {

            // Strings can have enums which are a list of predefined values
            if (($enum = $param->getEnum()) && !in_array($value, $enum)) {
                $this->errors[] = "{$path} must be one of " . implode(' or ', array_map(function ($s) {
                    return '"' . addslashes($s) . '"';
                }, $enum));
            }
            // Strings can have a regex pattern that the value must match
            if (($pattern  = $param->getPattern()) && !preg_match($pattern, $value)) {
                $this->errors[] = "{$path} must match the following regular expression: {$pattern}";
            }

            $strLen = null;
            if ($min = $param->getMinLength()) {
                $strLen = strlen($value);
                if ($strLen < $min) {
                    $this->errors[] = "{$path} length must be greater than or equal to {$min}";
                }
            }
            if ($max = $param->getMaxLength()) {
                if (($strLen ?: strlen($value)) > $max) {
                    $this->errors[] = "{$path} length must be less than or equal to {$max}";
                }
            }

        } elseif ($type == 'array') {

            $size = null;
            if ($min = $param->getMinItems()) {
                $size = count($value);
                if ($size < $min) {
                    $this->errors[] = "{$path} must contain {$min} or more elements";
                }
            }
            if ($max = $param->getMaxItems()) {
                if (($size ?: count($value)) > $max) {
                    $this->errors[] = "{$path} must contain {$max} or fewer elements";
                }
            }

        } elseif ($type == 'integer' || $type == 'number' || $type == 'numeric') {
            if (($min = $param->getMinimum()) && $value < $min) {
                $this->errors[] = "{$path} must be greater than or equal to {$min}";
            }
            if (($max = $param->getMaximum()) && $value > $max) {
                $this->errors[] = "{$path} must be less than or equal to {$max}";
            }
        }

        return empty($this->errors);
    }

    /**
     * From the allowable types, determine the type that the variable matches
     *
     * @param string $type  Parameter type
     * @param mixed  $value Value to determine the type
     *
     * @return string|bool Returns the matching type on
     */
    protected function determineType($type, $value)
    {
        foreach ((array) $type as $t) {
            if ($t == 'string' && (is_string($value) || (is_object($value) && method_exists($value, '__toString')))) {
                return 'string';
            } elseif ($t == 'object' && (is_array($value) || is_object($value))) {
                return 'object';
            } elseif ($t == 'array' && is_array($value)) {
                return 'array';
            } elseif ($t == 'integer' && is_integer($value)) {
                return 'integer';
            } elseif ($t == 'boolean' && is_bool($value)) {
                return 'boolean';
            } elseif ($t == 'number' && is_numeric($value)) {
                return 'number';
            } elseif ($t == 'numeric' && is_numeric($value)) {
                return 'numeric';
            } elseif ($t == 'null' && !$value) {
                return 'null';
            } elseif ($t == 'any') {
                return 'any';
            }
        }

        return false;
    }
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\ToArrayInterface;

/**
 * Interface defining data objects that hold the information of an API operation
 */
interface OperationInterface extends ToArrayInterface
{
    const TYPE_PRIMITIVE = 'primitive';
    const TYPE_CLASS = 'class';
    const TYPE_DOCUMENTATION = 'documentation';
    const TYPE_MODEL = 'model';

    /**
     * Get the service description that the operation belongs to
     *
     * @return ServiceDescriptionInterface|null
     */
    public function getServiceDescription();

    /**
     * Set the service description that the operation belongs to
     *
     * @param ServiceDescriptionInterface $description Service description
     *
     * @return self
     */
    public function setServiceDescription(ServiceDescriptionInterface $description);

    /**
     * Get the params of the operation
     *
     * @return array
     */
    public function getParams();

    /**
     * Returns an array of parameter names
     *
     * @return array
     */
    public function getParamNames();

    /**
     * Check if the operation has a specific parameter by name
     *
     * @param string $name Name of the param
     *
     * @return bool
     */
    public function hasParam($name);

    /**
     * Get a single parameter of the operation
     *
     * @param string $param Parameter to retrieve by name
     *
     * @return Parameter|null
     */
    public function getParam($param);

    /**
     * Get the HTTP method of the operation
     *
     * @return string|null
     */
    public function getHttpMethod();

    /**
     * Get the concrete operation class that implements this operation
     *
     * @return string
     */
    public function getClass();

    /**
     * Get the name of the operation
     *
     * @return string|null
     */
    public function getName();

    /**
     * Get a short summary of what the operation does
     *
     * @return string|null
     */
    public function getSummary();

    /**
     * Get a longer text field to explain the behavior of the operation
     *
     * @return string|null
     */
    public function getNotes();

    /**
     * Get the documentation URL of the operation
     *
     * @return string|null
     */
    public function getDocumentationUrl();

    /**
     * Get what is returned from the method. Can be a primitive, class name, or model. For example, the responseClass
     * could be 'array', which would inherently use a responseType of 'primitive'. Using a class name would set a
     * responseType of 'class'. Specifying a model by ID will use a responseType of 'model'.
     *
     * @return string|null
     */
    public function getResponseClass();

    /**
     * Get information about how the response is unmarshalled: One of 'primitive', 'class', 'model', or 'documentation'
     *
     * @return string
     */
    public function getResponseType();

    /**
     * Get notes about the response of the operation
     *
     * @return string|null
     */
    public function getResponseNotes();

    /**
     * Get whether or not the operation is deprecated
     *
     * @return bool
     */
    public function getDeprecated();

    /**
     * Get the URI that will be merged into the generated request
     *
     * @return string
     */
    public function getUri();

    /**
     * Get the errors that could be encountered when executing the operation
     *
     * @return array
     */
    public function getErrorResponses();

    /**
     * Get extra data from the operation
     *
     * @param string $name Name of the data point to retrieve
     *
     * @return mixed|null
     */
    public function getData($name);
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Service\AbstractConfigLoader;
use Guzzle\Service\Exception\DescriptionBuilderException;

/**
 * Loader for service descriptions
 */
class ServiceDescriptionLoader extends AbstractConfigLoader
{
    protected function build($config, array $options)
    {
        $operations = array();
        if (!empty($config['operations'])) {
            foreach ($config['operations'] as $name => $op) {
                $name = $op['name'] = isset($op['name']) ? $op['name'] : $name;
                // Extend other operations
                if (!empty($op['extends'])) {
                    $this->resolveExtension($name, $op, $operations);
                }
                $op['parameters'] = isset($op['parameters']) ? $op['parameters'] : array();
                $operations[$name] = $op;
            }
        }

        return new ServiceDescription(array(
            'apiVersion'  => isset($config['apiVersion']) ? $config['apiVersion'] : null,
            'baseUrl'     => isset($config['baseUrl']) ? $config['baseUrl'] : null,
            'description' => isset($config['description']) ? $config['description'] : null,
            'operations'  => $operations,
            'models'      => isset($config['models']) ? $config['models'] : null
        ) + $config);
    }

    /**
     * @param string $name       Name of the operation
     * @param array  $op         Operation value array
     * @param array  $operations Currently loaded operations
     * @throws DescriptionBuilderException when extending a non-existent operation
     */
    protected function resolveExtension($name, array &$op, array &$operations)
    {
        $resolved = array();
        $original = empty($op['parameters']) ? false: $op['parameters'];
        $hasClass = !empty($op['class']);
        foreach ((array) $op['extends'] as $extendedCommand) {
            if (empty($operations[$extendedCommand])) {
                throw new DescriptionBuilderException("{$name} extends missing operation {$extendedCommand}");
            }
            $toArray = $operations[$extendedCommand];
            $resolved = empty($resolved)
                ? $toArray['parameters']
                : array_merge($resolved, $toArray['parameters']);

            $op = $op + $toArray;
            if (!$hasClass && isset($toArray['class'])) {
                $op['class'] = $toArray['class'];
            }
        }
        $op['parameters'] = $original ? array_merge($resolved, $original) : $resolved;
    }
}
<?php

namespace Guzzle\Service\Description;

/**
 * A ServiceDescription stores service information based on a service document
 */
interface ServiceDescriptionInterface extends \Serializable
{
    /**
     * Get the basePath/baseUrl of the description
     *
     * @return string
     */
    public function getBaseUrl();

    /**
     * Get the API operations of the service
     *
     * @return array Returns an array of {@see OperationInterface} objects
     */
    public function getOperations();

    /**
     * Check if the service has an operation by name
     *
     * @param string $name Name of the operation to check
     *
     * @return bool
     */
    public function hasOperation($name);

    /**
     * Get an API operation by name
     *
     * @param string $name Name of the command
     *
     * @return OperationInterface|null
     */
    public function getOperation($name);

    /**
     * Get a specific model from the description
     *
     * @param string $id ID of the model
     *
     * @return Parameter|null
     */
    public function getModel($id);

    /**
     * Get all service description models
     *
     * @return array
     */
    public function getModels();

    /**
     * Check if the description has a specific model by name
     *
     * @param string $id ID of the model
     *
     * @return bool
     */
    public function hasModel($id);

    /**
     * Get the API version of the service
     *
     * @return string
     */
    public function getApiVersion();

    /**
     * Get the name of the API
     *
     * @return string
     */
    public function getName();

    /**
     * Get a summary of the purpose of the API
     *
     * @return string
     */
    public function getDescription();

    /**
     * Get arbitrary data from the service description that is not part of the Guzzle spec
     *
     * @param string $key Data key to retrieve
     *
     * @return null|mixed
     */
    public function getData($key);

    /**
     * Set arbitrary data on the service description
     *
     * @param string $key   Data key to set
     * @param mixed  $value Value to set
     *
     * @return self
     */
    public function setData($key, $value);
}
<?php

namespace Guzzle\Service\Description;

/**
 * Validator responsible for preparing and validating parameters against the parameter's schema
 */
interface ValidatorInterface
{
    /**
     * Validate a value against the acceptable types, regular expressions, minimum, maximums, instanceOf, enums, etc
     * Add default and static values to the passed in variable. If the validation completes successfully, the input
     * must be run correctly through the matching schema's filters attribute.
     *
     * @param Parameter $param Schema that is being validated against the value
     * @param mixed     $value Value to validate and process. The value may change during this process.
     *
     * @return bool  Returns true if the input data is valid for the schema
     */
    public function validate(Parameter $param, &$value);

    /**
     * Get validation errors encountered while validating
     *
     * @return array
     */
    public function getErrors();
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\ToArrayInterface;

/**
 * A ServiceDescription stores service information based on a service document
 */
class ServiceDescription implements ServiceDescriptionInterface, ToArrayInterface
{
    /** @var array Array of {@see OperationInterface} objects */
    protected $operations = array();

    /** @var array Array of API models */
    protected $models = array();

    /** @var string Name of the API */
    protected $name;

    /** @var string API version */
    protected $apiVersion;

    /** @var string Summary of the API */
    protected $description;

    /** @var array Any extra API data */
    protected $extraData = array();

    /** @var ServiceDescriptionLoader Factory used in factory method */
    protected static $descriptionLoader;

    /** @var string baseUrl/basePath */
    protected $baseUrl;

    /**
     * {@inheritdoc}
     * @param string|array $config  File to build or array of operation information
     * @param array        $options Service description factory options
     *
     * @return self
     */
    public static function factory($config, array $options = array())
    {
        // @codeCoverageIgnoreStart
        if (!self::$descriptionLoader) {
            self::$descriptionLoader = new ServiceDescriptionLoader();
        }
        // @codeCoverageIgnoreEnd

        return self::$descriptionLoader->load($config, $options);
    }

    /**
     * @param array $config Array of configuration data
     */
    public function __construct(array $config = array())
    {
        $this->fromArray($config);
    }

    public function serialize()
    {
        return json_encode($this->toArray());
    }

    public function unserialize($json)
    {
        $this->operations = array();
        $this->fromArray(json_decode($json, true));
    }

    public function toArray()
    {
        $result = array(
            'name'        => $this->name,
            'apiVersion'  => $this->apiVersion,
            'baseUrl'     => $this->baseUrl,
            'description' => $this->description
        ) + $this->extraData;
        $result['operations'] = array();
        foreach ($this->getOperations() as $name => $operation) {
            $result['operations'][$operation->getName() ?: $name] = $operation->toArray();
        }
        if (!empty($this->models)) {
            $result['models'] = array();
            foreach ($this->models as $id => $model) {
                $result['models'][$id] = $model instanceof Parameter ? $model->toArray(): $model;
            }
        }

        return array_filter($result);
    }

    public function getBaseUrl()
    {
        return $this->baseUrl;
    }

    /**
     * Set the baseUrl of the description
     *
     * @param string $baseUrl Base URL of each operation
     *
     * @return self
     */
    public function setBaseUrl($baseUrl)
    {
        $this->baseUrl = $baseUrl;

        return $this;
    }

    public function getOperations()
    {
        foreach (array_keys($this->operations) as $name) {
            $this->getOperation($name);
        }

        return $this->operations;
    }

    public function hasOperation($name)
    {
        return isset($this->operations[$name]);
    }

    public function getOperation($name)
    {
        // Lazily retrieve and build operations
        if (!isset($this->operations[$name])) {
            return null;
        }

        if (!($this->operations[$name] instanceof Operation)) {
            $this->operations[$name] = new Operation($this->operations[$name], $this);
        }

        return $this->operations[$name];
    }

    /**
     * Add a operation to the service description
     *
     * @param OperationInterface $operation Operation to add
     *
     * @return self
     */
    public function addOperation(OperationInterface $operation)
    {
        $this->operations[$operation->getName()] = $operation->setServiceDescription($this);

        return $this;
    }

    public function getModel($id)
    {
        if (!isset($this->models[$id])) {
            return null;
        }

        if (!($this->models[$id] instanceof Parameter)) {
            $this->models[$id] = new Parameter($this->models[$id] + array('name' => $id), $this);
        }

        return $this->models[$id];
    }

    public function getModels()
    {
        // Ensure all models are converted into parameter objects
        foreach (array_keys($this->models) as $id) {
            $this->getModel($id);
        }

        return $this->models;
    }

    public function hasModel($id)
    {
        return isset($this->models[$id]);
    }

    /**
     * Add a model to the service description
     *
     * @param Parameter $model Model to add
     *
     * @return self
     */
    public function addModel(Parameter $model)
    {
        $this->models[$model->getName()] = $model;

        return $this;
    }

    public function getApiVersion()
    {
        return $this->apiVersion;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function getData($key)
    {
        return isset($this->extraData[$key]) ? $this->extraData[$key] : null;
    }

    public function setData($key, $value)
    {
        $this->extraData[$key] = $value;

        return $this;
    }

    /**
     * Initialize the state from an array
     *
     * @param array $config Configuration data
     * @throws InvalidArgumentException
     */
    protected function fromArray(array $config)
    {
        // Keep a list of default keys used in service descriptions that is later used to determine extra data keys
        static $defaultKeys = array('name', 'models', 'apiVersion', 'baseUrl', 'description');
        // Pull in the default configuration values
        foreach ($defaultKeys as $key) {
            if (isset($config[$key])) {
                $this->{$key} = $config[$key];
            }
        }

        // Account for the Swagger name for Guzzle's baseUrl
        if (isset($config['basePath'])) {
            $this->baseUrl = $config['basePath'];
        }

        // Ensure that the models and operations properties are always arrays
        $this->models = (array) $this->models;
        $this->operations = (array) $this->operations;

        // We want to add operations differently than adding the other properties
        $defaultKeys[] = 'operations';

        // Create operations for each operation
        if (isset($config['operations'])) {
            foreach ($config['operations'] as $name => $operation) {
                if (!($operation instanceof Operation) && !is_array($operation)) {
                    throw new InvalidArgumentException('Invalid operation in service description: '
                        . gettype($operation));
                }
                $this->operations[$name] = $operation;
            }
        }

        // Get all of the additional properties of the service description and store them in a data array
        foreach (array_diff(array_keys($config), $defaultKeys) as $key) {
            $this->extraData[$key] = $config[$key];
        }
    }
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * Data object holding the information of an API command
 */
class Operation implements OperationInterface
{
    /** @var string Default command class to use when none is specified */
    const DEFAULT_COMMAND_CLASS = 'Guzzle\\Service\\Command\\OperationCommand';

    /** @var array Hashmap of properties that can be specified. Represented as a hash to speed up constructor. */
    protected static $properties = array(
        'name' => true, 'httpMethod' => true, 'uri' => true, 'class' => true, 'responseClass' => true,
        'responseType' => true, 'responseNotes' => true, 'notes' => true, 'summary' => true, 'documentationUrl' => true,
        'deprecated' => true, 'data' => true, 'parameters' => true, 'additionalParameters' => true,
        'errorResponses' => true
    );

    /** @var array Parameters */
    protected $parameters = array();

    /** @var Parameter Additional parameters schema */
    protected $additionalParameters;

    /** @var string Name of the command */
    protected $name;

    /** @var string HTTP method */
    protected $httpMethod;

    /** @var string This is a short summary of what the operation does */
    protected $summary;

    /** @var string A longer text field to explain the behavior of the operation. */
    protected $notes;

    /** @var string Reference URL providing more information about the operation */
    protected $documentationUrl;

    /** @var string HTTP URI of the command */
    protected $uri;

    /** @var string Class of the command object */
    protected $class;

    /** @var string This is what is returned from the method */
    protected $responseClass;

    /** @var string Type information about the response */
    protected $responseType;

    /** @var string Information about the response returned by the operation */
    protected $responseNotes;

    /** @var bool Whether or not the command is deprecated */
    protected $deprecated;

    /** @var array Array of errors that could occur when running the command */
    protected $errorResponses;

    /** @var ServiceDescriptionInterface */
    protected $description;

    /** @var array Extra operation information */
    protected $data;

    /**
     * Builds an Operation object using an array of configuration data:
     * - name:               (string) Name of the command
     * - httpMethod:         (string) HTTP method of the operation
     * - uri:                (string) URI template that can create a relative or absolute URL
     * - class:              (string) Concrete class that implements this command
     * - parameters:         (array) Associative array of parameters for the command. {@see Parameter} for information.
     * - summary:            (string) This is a short summary of what the operation does
     * - notes:              (string) A longer text field to explain the behavior of the operation.
     * - documentationUrl:   (string) Reference URL providing more information about the operation
     * - responseClass:      (string) This is what is returned from the method. Can be a primitive, PSR-0 compliant
     *                       class name, or model.
     * - responseNotes:      (string) Information about the response returned by the operation
     * - responseType:       (string) One of 'primitive', 'class', 'model', or 'documentation'. If not specified, this
     *                       value will be automatically inferred based on whether or not there is a model matching the
     *                       name, if a matching PSR-0 compliant class name is found, or set to 'primitive' by default.
     * - deprecated:         (bool) Set to true if this is a deprecated command
     * - errorResponses:     (array) Errors that could occur when executing the command. Array of hashes, each with a
     *                       'code' (the HTTP response code), 'reason' (response reason phrase or description of the
     *                       error), and 'class' (a custom exception class that would be thrown if the error is
     *                       encountered).
     * - data:               (array) Any extra data that might be used to help build or serialize the operation
     * - additionalParameters: (null|array) Parameter schema to use when an option is passed to the operation that is
     *                                      not in the schema
     *
     * @param array                       $config      Array of configuration data
     * @param ServiceDescriptionInterface $description Service description used to resolve models if $ref tags are found
     */
    public function __construct(array $config = array(), ServiceDescriptionInterface $description = null)
    {
        $this->description = $description;

        // Get the intersection of the available properties and properties set on the operation
        foreach (array_intersect_key($config, self::$properties) as $key => $value) {
            $this->{$key} = $value;
        }

        $this->class = $this->class ?: self::DEFAULT_COMMAND_CLASS;
        $this->deprecated = (bool) $this->deprecated;
        $this->errorResponses = $this->errorResponses ?: array();
        $this->data = $this->data ?: array();

        if (!$this->responseClass) {
            $this->responseClass = 'array';
            $this->responseType = 'primitive';
        } elseif ($this->responseType) {
            // Set the response type to perform validation
            $this->setResponseType($this->responseType);
        } else {
            // A response class was set and no response type was set, so guess what the type is
            $this->inferResponseType();
        }

        // Parameters need special handling when adding
        if ($this->parameters) {
            foreach ($this->parameters as $name => $param) {
                if ($param instanceof Parameter) {
                    $param->setName($name)->setParent($this);
                } elseif (is_array($param)) {
                    $param['name'] = $name;
                    $this->addParam(new Parameter($param, $this->description));
                }
            }
        }

        if ($this->additionalParameters) {
            if ($this->additionalParameters instanceof Parameter) {
                $this->additionalParameters->setParent($this);
            } elseif (is_array($this->additionalParameters)) {
                $this->setadditionalParameters(new Parameter($this->additionalParameters, $this->description));
            }
        }
    }

    public function toArray()
    {
        $result = array();
        // Grab valid properties and filter out values that weren't set
        foreach (array_keys(self::$properties) as $check) {
            if ($value = $this->{$check}) {
                $result[$check] = $value;
            }
        }
        // Remove the name property
        unset($result['name']);
        // Parameters need to be converted to arrays
        $result['parameters'] = array();
        foreach ($this->parameters as $key => $param) {
            $result['parameters'][$key] = $param->toArray();
        }
        // Additional parameters need to be cast to an array
        if ($this->additionalParameters instanceof Parameter) {
            $result['additionalParameters'] = $this->additionalParameters->toArray();
        }

        return $result;
    }

    public function getServiceDescription()
    {
        return $this->description;
    }

    public function setServiceDescription(ServiceDescriptionInterface $description)
    {
        $this->description = $description;

        return $this;
    }

    public function getParams()
    {
        return $this->parameters;
    }

    public function getParamNames()
    {
        return array_keys($this->parameters);
    }

    public function hasParam($name)
    {
        return isset($this->parameters[$name]);
    }

    public function getParam($param)
    {
        return isset($this->parameters[$param]) ? $this->parameters[$param] : null;
    }

    /**
     * Add a parameter to the command
     *
     * @param Parameter $param Parameter to add
     *
     * @return self
     */
    public function addParam(Parameter $param)
    {
        $this->parameters[$param->getName()] = $param;
        $param->setParent($this);

        return $this;
    }

    /**
     * Remove a parameter from the command
     *
     * @param string $name Name of the parameter to remove
     *
     * @return self
     */
    public function removeParam($name)
    {
        unset($this->parameters[$name]);

        return $this;
    }

    public function getHttpMethod()
    {
        return $this->httpMethod;
    }

    /**
     * Set the HTTP method of the command
     *
     * @param string $httpMethod Method to set
     *
     * @return self
     */
    public function setHttpMethod($httpMethod)
    {
        $this->httpMethod = $httpMethod;

        return $this;
    }

    public function getClass()
    {
        return $this->class;
    }

    /**
     * Set the concrete class of the command
     *
     * @param string $className Concrete class name
     *
     * @return self
     */
    public function setClass($className)
    {
        $this->class = $className;

        return $this;
    }

    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the name of the command
     *
     * @param string $name Name of the command
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getSummary()
    {
        return $this->summary;
    }

    /**
     * Set a short summary of what the operation does
     *
     * @param string $summary Short summary of the operation
     *
     * @return self
     */
    public function setSummary($summary)
    {
        $this->summary = $summary;

        return $this;
    }

    public function getNotes()
    {
        return $this->notes;
    }

    /**
     * Set a longer text field to explain the behavior of the operation.
     *
     * @param string $notes Notes on the operation
     *
     * @return self
     */
    public function setNotes($notes)
    {
        $this->notes = $notes;

        return $this;
    }

    public function getDocumentationUrl()
    {
        return $this->documentationUrl;
    }

    /**
     * Set the URL pointing to additional documentation on the command
     *
     * @param string $docUrl Documentation URL
     *
     * @return self
     */
    public function setDocumentationUrl($docUrl)
    {
        $this->documentationUrl = $docUrl;

        return $this;
    }

    public function getResponseClass()
    {
        return $this->responseClass;
    }

    /**
     * Set what is returned from the method. Can be a primitive, class name, or model. For example: 'array',
     * 'Guzzle\\Foo\\Baz', or 'MyModelName' (to reference a model by ID).
     *
     * @param string $responseClass Type of response
     *
     * @return self
     */
    public function setResponseClass($responseClass)
    {
        $this->responseClass = $responseClass;
        $this->inferResponseType();

        return $this;
    }

    public function getResponseType()
    {
        return $this->responseType;
    }

    /**
     * Set qualifying information about the responseClass. One of 'primitive', 'class', 'model', or 'documentation'
     *
     * @param string $responseType Response type information
     *
     * @return self
     * @throws InvalidArgumentException
     */
    public function setResponseType($responseType)
    {
        static $types = array(
            self::TYPE_PRIMITIVE => true,
            self::TYPE_CLASS => true,
            self::TYPE_MODEL => true,
            self::TYPE_DOCUMENTATION => true
        );
        if (!isset($types[$responseType])) {
            throw new InvalidArgumentException('responseType must be one of ' . implode(', ', array_keys($types)));
        }

        $this->responseType = $responseType;

        return $this;
    }

    public function getResponseNotes()
    {
        return $this->responseNotes;
    }

    /**
     * Set notes about the response of the operation
     *
     * @param string $notes Response notes
     *
     * @return self
     */
    public function setResponseNotes($notes)
    {
        $this->responseNotes = $notes;

        return $this;
    }

    public function getDeprecated()
    {
        return $this->deprecated;
    }

    /**
     * Set whether or not the command is deprecated
     *
     * @param bool $isDeprecated Set to true to mark as deprecated
     *
     * @return self
     */
    public function setDeprecated($isDeprecated)
    {
        $this->deprecated = $isDeprecated;

        return $this;
    }

    public function getUri()
    {
        return $this->uri;
    }

    /**
     * Set the URI template of the command
     *
     * @param string $uri URI template to set
     *
     * @return self
     */
    public function setUri($uri)
    {
        $this->uri = $uri;

        return $this;
    }

    public function getErrorResponses()
    {
        return $this->errorResponses;
    }

    /**
     * Add an error to the command
     *
     * @param string $code   HTTP response code
     * @param string $reason HTTP response reason phrase or information about the error
     * @param string $class  Exception class associated with the error
     *
     * @return self
     */
    public function addErrorResponse($code, $reason, $class)
    {
        $this->errorResponses[] = array('code' => $code, 'reason' => $reason, 'class' => $class);

        return $this;
    }

    /**
     * Set all of the error responses of the operation
     *
     * @param array $errorResponses Hash of error name to a hash containing a code, reason, class
     *
     * @return self
     */
    public function setErrorResponses(array $errorResponses)
    {
        $this->errorResponses = $errorResponses;

        return $this;
    }

    public function getData($name)
    {
        return isset($this->data[$name]) ? $this->data[$name] : null;
    }

    /**
     * Set a particular data point on the operation
     *
     * @param string $name  Name of the data value
     * @param mixed  $value Value to set
     *
     * @return self
     */
    public function setData($name, $value)
    {
        $this->data[$name] = $value;

        return $this;
    }

    /**
     * Get the additionalParameters of the operation
     *
     * @return Parameter|null
     */
    public function getAdditionalParameters()
    {
        return $this->additionalParameters;
    }

    /**
     * Set the additionalParameters of the operation
     *
     * @param Parameter|null $parameter Parameter to set
     *
     * @return self
     */
    public function setAdditionalParameters($parameter)
    {
        if ($this->additionalParameters = $parameter) {
            $this->additionalParameters->setParent($this);
        }

        return $this;
    }

    /**
     * Infer the response type from the responseClass value
     */
    protected function inferResponseType()
    {
        static $primitives = array('array' => 1, 'boolean' => 1, 'string' => 1, 'integer' => 1, '' => 1);
        if (isset($primitives[$this->responseClass])) {
            $this->responseType = self::TYPE_PRIMITIVE;
        } elseif ($this->description && $this->description->hasModel($this->responseClass)) {
            $this->responseType = self::TYPE_MODEL;
        } else {
            $this->responseType = self::TYPE_CLASS;
        }
    }
}
<?php

namespace Guzzle\Service\Description;

use Guzzle\Common\Exception\InvalidArgumentException;

/**
 * API parameter object used with service descriptions
 */
class Parameter
{
    protected $name;
    protected $description;
    protected $serviceDescription;
    protected $type;
    protected $required;
    protected $enum;
    protected $pattern;
    protected $minimum;
    protected $maximum;
    protected $minLength;
    protected $maxLength;
    protected $minItems;
    protected $maxItems;
    protected $default;
    protected $static;
    protected $instanceOf;
    protected $filters;
    protected $location;
    protected $sentAs;
    protected $data;
    protected $properties = array();
    protected $additionalProperties;
    protected $items;
    protected $parent;
    protected $ref;
    protected $format;
    protected $propertiesCache = null;

    /**
     * Create a new Parameter using an associative array of data. The array can contain the following information:
     * - name:          (string) Unique name of the parameter
     * - type:          (string|array) Type of variable (string, number, integer, boolean, object, array, numeric,
     *                  null, any). Types are using for validation and determining the structure of a parameter. You
     *                  can use a union type by providing an array of simple types. If one of the union types matches
     *                  the provided value, then the value is valid.
     * - instanceOf:    (string) When the type is an object, you can specify the class that the object must implement
     * - required:      (bool) Whether or not the parameter is required
     * - default:       (mixed) Default value to use if no value is supplied
     * - static:        (bool) Set to true to specify that the parameter value cannot be changed from the default
     * - description:   (string) Documentation of the parameter
     * - location:      (string) The location of a request used to apply a parameter. Custom locations can be registered
     *                  with a command, but the defaults are uri, query, header, body, json, xml, postField, postFile.
     * - sentAs:        (string) Specifies how the data being modeled is sent over the wire. For example, you may wish
     *                  to include certain headers in a response model that have a normalized casing of FooBar, but the
     *                  actual header is x-foo-bar. In this case, sentAs would be set to x-foo-bar.
     * - filters:       (array) Array of static method names to to run a parameter value through. Each value in the
     *                  array must be a string containing the full class path to a static method or an array of complex
     *                  filter information. You can specify static methods of classes using the full namespace class
     *                  name followed by '::' (e.g. Foo\Bar::baz()). Some filters require arguments in order to properly
     *                  filter a value. For complex filters, use a hash containing a 'method' key pointing to a static
     *                  method, and an 'args' key containing an array of positional arguments to pass to the method.
     *                  Arguments can contain keywords that are replaced when filtering a value: '@value' is replaced
     *                  with the value being validated, '@api' is replaced with the Parameter object.
     * - properties:    When the type is an object, you can specify nested parameters
     * - additionalProperties: (array) This attribute defines a schema for all properties that are not explicitly
     *                  defined in an object type definition. If specified, the value MUST be a schema or a boolean. If
     *                  false is provided, no additional properties are allowed beyond the properties defined in the
     *                  schema. The default value is an empty schema which allows any value for additional properties.
     * - items:         This attribute defines the allowed items in an instance array, and MUST be a schema or an array
     *                  of schemas. The default value is an empty schema which allows any value for items in the
     *                  instance array.
     *                  When this attribute value is a schema and the instance value is an array, then all the items
     *                  in the array MUST be valid according to the schema.
     * - pattern:       When the type is a string, you can specify the regex pattern that a value must match
     * - enum:          When the type is a string, you can specify a list of acceptable values
     * - minItems:      (int) Minimum number of items allowed in an array
     * - maxItems:      (int) Maximum number of items allowed in an array
     * - minLength:     (int) Minimum length of a string
     * - maxLength:     (int) Maximum length of a string
     * - minimum:       (int) Minimum value of an integer
     * - maximum:       (int) Maximum value of an integer
     * - data:          (array) Any additional custom data to use when serializing, validating, etc
     * - format:        (string) Format used to coax a value into the correct format when serializing or unserializing.
     *                  You may specify either an array of filters OR a format, but not both.
     *                  Supported values: date-time, date, time, timestamp, date-time-http
     * - $ref:          (string) String referencing a service description model. The parameter is replaced by the
     *                  schema contained in the model.
     *
     * @param array                       $data        Array of data as seen in service descriptions
     * @param ServiceDescriptionInterface $description Service description used to resolve models if $ref tags are found
     *
     * @throws InvalidArgumentException
     */
    public function __construct(array $data = array(), ServiceDescriptionInterface $description = null)
    {
        if ($description) {
            if (isset($data['$ref'])) {
                if ($model = $description->getModel($data['$ref'])) {
                    $data = $model->toArray() + $data;
                }
            } elseif (isset($data['extends'])) {
                // If this parameter extends from another parameter then start with the actual data
                // union in the parent's data (e.g. actual supersedes parent)
                if ($extends = $description->getModel($data['extends'])) {
                    $data += $extends->toArray();
                }
            }
        }

        // Pull configuration data into the parameter
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }

        $this->serviceDescription = $description;
        $this->required = (bool) $this->required;
        $this->data = (array) $this->data;

        if ($this->filters) {
            $this->setFilters((array) $this->filters);
        }

        if ($this->type == 'object' && $this->additionalProperties === null) {
            $this->additionalProperties = true;
        }
    }

    /**
     * Convert the object to an array
     *
     * @return array
     */
    public function toArray()
    {
        static $checks = array('required', 'description', 'static', 'type', 'format', 'instanceOf', 'location', 'sentAs',
            'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'data', 'enum',
            'filters');

        $result = array();

        // Anything that is in the `Items` attribute of an array *must* include it's name if available
        if ($this->parent instanceof self && $this->parent->getType() == 'array' && isset($this->name)) {
            $result['name'] = $this->name;
        }

        foreach ($checks as $c) {
            if ($value = $this->{$c}) {
                $result[$c] = $value;
            }
        }

        if ($this->default !== null) {
            $result['default'] = $this->default;
        }

        if ($this->items !== null) {
            $result['items'] = $this->getItems()->toArray();
        }

        if ($this->additionalProperties !== null) {
            $result['additionalProperties'] = $this->getAdditionalProperties();
            if ($result['additionalProperties'] instanceof self) {
                $result['additionalProperties'] = $result['additionalProperties']->toArray();
            }
        }

        if ($this->type == 'object' && $this->properties) {
            $result['properties'] = array();
            foreach ($this->getProperties() as $name => $property) {
                $result['properties'][$name] = $property->toArray();
            }
        }

        return $result;
    }

    /**
     * Get the default or static value of the command based on a value
     *
     * @param string $value Value that is currently set
     *
     * @return mixed Returns the value, a static value if one is present, or a default value
     */
    public function getValue($value)
    {
        if ($this->static || ($this->default !== null && $value === null)) {
            return $this->default;
        }

        return $value;
    }

    /**
     * Run a value through the filters OR format attribute associated with the parameter
     *
     * @param mixed $value Value to filter
     *
     * @return mixed Returns the filtered value
     */
    public function filter($value)
    {
        // Formats are applied exclusively and supersed filters
        if ($this->format) {
            return SchemaFormatter::format($this->format, $value);
        }

        // Convert Boolean values
        if ($this->type == 'boolean' && !is_bool($value)) {
            $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
        }

        // Apply filters to the value
        if ($this->filters) {
            foreach ($this->filters as $filter) {
                if (is_array($filter)) {
                    // Convert complex filters that hold value place holders
                    foreach ($filter['args'] as &$data) {
                        if ($data == '@value') {
                            $data = $value;
                        } elseif ($data == '@api') {
                            $data = $this;
                        }
                    }
                    $value = call_user_func_array($filter['method'], $filter['args']);
                } else {
                    $value = call_user_func($filter, $value);
                }
            }
        }

        return $value;
    }

    /**
     * Get the name of the parameter
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get the key of the parameter, where sentAs will supersede name if it is set
     *
     * @return string
     */
    public function getWireName()
    {
        return $this->sentAs ?: $this->name;
    }

    /**
     * Set the name of the parameter
     *
     * @param string $name Name to set
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get the type(s) of the parameter
     *
     * @return string|array
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set the type(s) of the parameter
     *
     * @param string|array $type Type of parameter or array of simple types used in a union
     *
     * @return self
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get if the parameter is required
     *
     * @return bool
     */
    public function getRequired()
    {
        return $this->required;
    }

    /**
     * Set if the parameter is required
     *
     * @param bool $isRequired Whether or not the parameter is required
     *
     * @return self
     */
    public function setRequired($isRequired)
    {
        $this->required = (bool) $isRequired;

        return $this;
    }

    /**
     * Get the default value of the parameter
     *
     * @return string|null
     */
    public function getDefault()
    {
        return $this->default;
    }

    /**
     * Set the default value of the parameter
     *
     * @param string|null $default Default value to set
     *
     * @return self
     */
    public function setDefault($default)
    {
        $this->default = $default;

        return $this;
    }

    /**
     * Get the description of the parameter
     *
     * @return string|null
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set the description of the parameter
     *
     * @param string $description Description
     *
     * @return self
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get the minimum acceptable value for an integer
     *
     * @return int|null
     */
    public function getMinimum()
    {
        return $this->minimum;
    }

    /**
     * Set the minimum acceptable value for an integer
     *
     * @param int|null $min Minimum
     *
     * @return self
     */
    public function setMinimum($min)
    {
        $this->minimum = $min;

        return $this;
    }

    /**
     * Get the maximum acceptable value for an integer
     *
     * @return int|null
     */
    public function getMaximum()
    {
        return $this->maximum;
    }

    /**
     * Set the maximum acceptable value for an integer
     *
     * @param int $max Maximum
     *
     * @return self
     */
    public function setMaximum($max)
    {
        $this->maximum = $max;

        return $this;
    }

    /**
     * Get the minimum allowed length of a string value
     *
     * @return int
     */
    public function getMinLength()
    {
        return $this->minLength;
    }

    /**
     * Set the minimum allowed length of a string value
     *
     * @param int|null $min Minimum
     *
     * @return self
     */
    public function setMinLength($min)
    {
        $this->minLength = $min;

        return $this;
    }

    /**
     * Get the maximum allowed length of a string value
     *
     * @return int|null
     */
    public function getMaxLength()
    {
        return $this->maxLength;
    }

    /**
     * Set the maximum allowed length of a string value
     *
     * @param int $max Maximum length
     *
     * @return self
     */
    public function setMaxLength($max)
    {
        $this->maxLength = $max;

        return $this;
    }

    /**
     * Get the maximum allowed number of items in an array value
     *
     * @return int|null
     */
    public function getMaxItems()
    {
        return $this->maxItems;
    }

    /**
     * Set the maximum allowed number of items in an array value
     *
     * @param int $max Maximum
     *
     * @return self
     */
    public function setMaxItems($max)
    {
        $this->maxItems = $max;

        return $this;
    }

    /**
     * Get the minimum allowed number of items in an array value
     *
     * @return int
     */
    public function getMinItems()
    {
        return $this->minItems;
    }

    /**
     * Set the minimum allowed number of items in an array value
     *
     * @param int|null $min Minimum
     *
     * @return self
     */
    public function setMinItems($min)
    {
        $this->minItems = $min;

        return $this;
    }

    /**
     * Get the location of the parameter
     *
     * @return string|null
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Set the location of the parameter
     *
     * @param string|null $location Location of the parameter
     *
     * @return self
     */
    public function setLocation($location)
    {
        $this->location = $location;

        return $this;
    }

    /**
     * Get the sentAs attribute of the parameter that used with locations to sentAs an attribute when it is being
     * applied to a location.
     *
     * @return string|null
     */
    public function getSentAs()
    {
        return $this->sentAs;
    }

    /**
     * Set the sentAs attribute
     *
     * @param string|null $name Name of the value as it is sent over the wire
     *
     * @return self
     */
    public function setSentAs($name)
    {
        $this->sentAs = $name;

        return $this;
    }

    /**
     * Retrieve a known property from the parameter by name or a data property by name. When not specific name value
     * is specified, all data properties will be returned.
     *
     * @param string|null $name Specify a particular property name to retrieve
     *
     * @return array|mixed|null
     */
    public function getData($name = null)
    {
        if (!$name) {
            return $this->data;
        }

        if (isset($this->data[$name])) {
            return $this->data[$name];
        } elseif (isset($this->{$name})) {
            return $this->{$name};
        }

        return null;
    }

    /**
     * Set the extra data properties of the parameter or set a specific extra property
     *
     * @param string|array|null $nameOrData The name of a specific extra to set or an array of extras to set
     * @param mixed|null        $data       When setting a specific extra property, specify the data to set for it
     *
     * @return self
     */
    public function setData($nameOrData, $data = null)
    {
        if (is_array($nameOrData)) {
            $this->data = $nameOrData;
        } else {
            $this->data[$nameOrData] = $data;
        }

        return $this;
    }

    /**
     * Get whether or not the default value can be changed
     *
     * @return mixed|null
     */
    public function getStatic()
    {
        return $this->static;
    }

    /**
     * Set to true if the default value cannot be changed
     *
     * @param bool $static True or false
     *
     * @return self
     */
    public function setStatic($static)
    {
        $this->static = (bool) $static;

        return $this;
    }

    /**
     * Get an array of filters used by the parameter
     *
     * @return array
     */
    public function getFilters()
    {
        return $this->filters ?: array();
    }

    /**
     * Set the array of filters used by the parameter
     *
     * @param array $filters Array of functions to use as filters
     *
     * @return self
     */
    public function setFilters(array $filters)
    {
        $this->filters = array();
        foreach ($filters as $filter) {
            $this->addFilter($filter);
        }

        return $this;
    }

    /**
     * Add a filter to the parameter
     *
     * @param string|array $filter Method to filter the value through
     *
     * @return self
     * @throws InvalidArgumentException
     */
    public function addFilter($filter)
    {
        if (is_array($filter)) {
            if (!isset($filter['method'])) {
                throw new InvalidArgumentException('A [method] value must be specified for each complex filter');
            }
        }

        if (!$this->filters) {
            $this->filters = array($filter);
        } else {
            $this->filters[] = $filter;
        }

        return $this;
    }

    /**
     * Get the parent object (an {@see OperationInterface} or {@see Parameter}
     *
     * @return OperationInterface|Parameter|null
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Set the parent object of the parameter
     *
     * @param OperationInterface|Parameter|null $parent Parent container of the parameter
     *
     * @return self
     */
    public function setParent($parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get the properties of the parameter
     *
     * @return array
     */
    public function getProperties()
    {
        if (!$this->propertiesCache) {
            $this->propertiesCache = array();
            foreach (array_keys($this->properties) as $name) {
                $this->propertiesCache[$name] = $this->getProperty($name);
            }
        }

        return $this->propertiesCache;
    }

    /**
     * Get a specific property from the parameter
     *
     * @param string $name Name of the property to retrieve
     *
     * @return null|Parameter
     */
    public function getProperty($name)
    {
        if (!isset($this->properties[$name])) {
            return null;
        }

        if (!($this->properties[$name] instanceof self)) {
            $this->properties[$name]['name'] = $name;
            $this->properties[$name] = new static($this->properties[$name], $this->serviceDescription);
            $this->properties[$name]->setParent($this);
        }

        return $this->properties[$name];
    }

    /**
     * Remove a property from the parameter
     *
     * @param string $name Name of the property to remove
     *
     * @return self
     */
    public function removeProperty($name)
    {
        unset($this->properties[$name]);
        $this->propertiesCache = null;

        return $this;
    }

    /**
     * Add a property to the parameter
     *
     * @param Parameter $property Properties to set
     *
     * @return self
     */
    public function addProperty(Parameter $property)
    {
        $this->properties[$property->getName()] = $property;
        $property->setParent($this);
        $this->propertiesCache = null;

        return $this;
    }

    /**
     * Get the additionalProperties value of the parameter
     *
     * @return bool|Parameter|null
     */
    public function getAdditionalProperties()
    {
        if (is_array($this->additionalProperties)) {
            $this->additionalProperties = new static($this->additionalProperties, $this->serviceDescription);
            $this->additionalProperties->setParent($this);
        }

        return $this->additionalProperties;
    }

    /**
     * Set the additionalProperties value of the parameter
     *
     * @param bool|Parameter|null $additional Boolean to allow any, an Parameter to specify a schema, or false to disallow
     *
     * @return self
     */
    public function setAdditionalProperties($additional)
    {
        $this->additionalProperties = $additional;

        return $this;
    }

    /**
     * Set the items data of the parameter
     *
     * @param Parameter|null $items Items to set
     *
     * @return self
     */
    public function setItems(Parameter $items = null)
    {
        if ($this->items = $items) {
            $this->items->setParent($this);
        }

        return $this;
    }

    /**
     * Get the item data of the parameter
     *
     * @return Parameter|null
     */
    public function getItems()
    {
        if (is_array($this->items)) {
            $this->items = new static($this->items, $this->serviceDescription);
            $this->items->setParent($this);
        }

        return $this->items;
    }

    /**
     * Get the class that the parameter must implement
     *
     * @return null|string
     */
    public function getInstanceOf()
    {
        return $this->instanceOf;
    }

    /**
     * Set the class that the parameter must be an instance of
     *
     * @param string|null $instanceOf Class or interface name
     *
     * @return self
     */
    public function setInstanceOf($instanceOf)
    {
        $this->instanceOf = $instanceOf;

        return $this;
    }

    /**
     * Get the enum of strings that are valid for the parameter
     *
     * @return array|null
     */
    public function getEnum()
    {
        return $this->enum;
    }

    /**
     * Set the enum of strings that are valid for the parameter
     *
     * @param array|null $enum Array of strings or null
     *
     * @return self
     */
    public function setEnum(array $enum = null)
    {
        $this->enum = $enum;

        return $this;
    }

    /**
     * Get the regex pattern that must match a value when the value is a string
     *
     * @return string
     */
    public function getPattern()
    {
        return $this->pattern;
    }

    /**
     * Set the regex pattern that must match a value when the value is a string
     *
     * @param string $pattern Regex pattern
     *
     * @return self
     */
    public function setPattern($pattern)
    {
        $this->pattern = $pattern;

        return $this;
    }

    /**
     * Get the format attribute of the schema
     *
     * @return string
     */
    public function getFormat()
    {
        return $this->format;
    }

    /**
     * Set the format attribute of the schema
     *
     * @param string $format Format to set (e.g. date, date-time, timestamp, time, date-time-http)
     *
     * @return self
     */
    public function setFormat($format)
    {
        $this->format = $format;

        return $this;
    }
}
<?php

namespace Guzzle\Service;

use Guzzle\Common\FromConfigInterface;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\ClientInterface as HttpClientInterface;
use Guzzle\Service\Exception\CommandTransferException;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\ServiceDescriptionInterface;
use Guzzle\Service\Resource\ResourceIteratorInterface;

/**
 * Client interface for executing commands on a web service.
 */
interface ClientInterface extends HttpClientInterface, FromConfigInterface
{
    /**
     * Get a command by name. First, the client will see if it has a service description and if the service description
     * defines a command by the supplied name. If no dynamic command is found, the client will look for a concrete
     * command class exists matching the name supplied. If neither are found, an InvalidArgumentException is thrown.
     *
     * @param string $name Name of the command to retrieve
     * @param array  $args Arguments to pass to the command
     *
     * @return CommandInterface
     * @throws InvalidArgumentException if no command can be found by name
     */
    public function getCommand($name, array $args = array());

    /**
     * Execute one or more commands
     *
     * @param CommandInterface|array|Traversable $command Command, array of commands or Traversable object containing commands to execute
     *
     * @return mixed Returns the result of the executed command or an array of commands if executing multiple commands
     * @throws InvalidArgumentException if an invalid command is passed
     * @throws CommandTransferException if an exception is encountered when transferring multiple commands
     */
    public function execute($command);

    /**
     * Set the service description of the client
     *
     * @param ServiceDescriptionInterface $service Service description
     *
     * @return ClientInterface
     */
    public function setDescription(ServiceDescriptionInterface $service);

    /**
     * Get the service description of the client
     *
     * @return ServiceDescriptionInterface|null
     */
    public function getDescription();

    /**
     * Get a resource iterator from the client.
     *
     * @param string|CommandInterface $command         Command class or command name.
     * @param array                   $commandOptions  Command options used when creating commands.
     * @param array                   $iteratorOptions Iterator options passed to the iterator when it is instantiated.
     *
     * @return ResourceIteratorInterface
     */
    public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array());
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\LocationVisitor\Request\RequestVisitorInterface;
use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;
use Guzzle\Service\Description\OperationInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Default request serializer that transforms command options and operation parameters into a request
 */
class DefaultRequestSerializer implements RequestSerializerInterface
{
    /** @var VisitorFlyweight $factory Visitor factory */
    protected $factory;

    /** @var self */
    protected static $instance;

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self(VisitorFlyweight::getInstance());
        }

        return self::$instance;
    }

    /**
     * @param VisitorFlyweight $factory Factory to use when creating visitors
     */
    public function __construct(VisitorFlyweight $factory)
    {
        $this->factory = $factory;
    }

    /**
     * Add a location visitor to the serializer
     *
     * @param string                   $location Location to associate with the visitor
     * @param RequestVisitorInterface  $visitor  Visitor to attach
     *
     * @return self
     */
    public function addVisitor($location, RequestVisitorInterface $visitor)
    {
        $this->factory->addRequestVisitor($location, $visitor);

        return $this;
    }

    public function prepare(CommandInterface $command)
    {
        $request = $this->createRequest($command);
        // Keep an array of visitors found in the operation
        $foundVisitors = array();
        $operation = $command->getOperation();

        // Add arguments to the request using the location attribute
        foreach ($operation->getParams() as $name => $arg) {
            /** @var $arg \Guzzle\Service\Description\Parameter */
            $location = $arg->getLocation();
            // Skip 'uri' locations because they've already been processed
            if ($location && $location != 'uri') {
                // Instantiate visitors as they are detected in the properties
                if (!isset($foundVisitors[$location])) {
                    $foundVisitors[$location] = $this->factory->getRequestVisitor($location);
                }
                // Ensure that a value has been set for this parameter
                $value = $command[$name];
                if ($value !== null) {
                    // Apply the parameter value with the location visitor
                    $foundVisitors[$location]->visit($command, $request, $arg, $value);
                }
            }
        }

        // Serialize additional parameters
        if ($additional = $operation->getAdditionalParameters()) {
            if ($visitor = $this->prepareAdditionalParameters($operation, $command, $request, $additional)) {
                $foundVisitors[$additional->getLocation()] = $visitor;
            }
        }

        // Call the after method on each visitor found in the operation
        foreach ($foundVisitors as $visitor) {
            $visitor->after($command, $request);
        }

        return $request;
    }

    /**
     * Serialize additional parameters
     *
     * @param OperationInterface $operation  Operation that owns the command
     * @param CommandInterface   $command    Command to prepare
     * @param RequestInterface   $request    Request to serialize
     * @param Parameter          $additional Additional parameters
     *
     * @return null|RequestVisitorInterface
     */
    protected function prepareAdditionalParameters(
        OperationInterface $operation,
        CommandInterface $command,
        RequestInterface $request,
        Parameter $additional
    ) {
        if (!($location = $additional->getLocation())) {
            return;
        }

        $visitor = $this->factory->getRequestVisitor($location);
        $hidden = $command[$command::HIDDEN_PARAMS];

        foreach ($command->toArray() as $key => $value) {
            // Ignore values that are null or built-in command options
            if ($value !== null
                && !in_array($key, $hidden)
                && !$operation->hasParam($key)
            ) {
                $additional->setName($key);
                $visitor->visit($command, $request, $additional, $value);
            }
        }

        return $visitor;
    }

    /**
     * Create a request for the command and operation
     *
     * @param CommandInterface $command Command to create a request for
     *
     * @return RequestInterface
     */
    protected function createRequest(CommandInterface $command)
    {
        $operation = $command->getOperation();
        $client = $command->getClient();
        $options = $command[AbstractCommand::REQUEST_OPTIONS] ?: array();

        // If the command does not specify a template, then assume the base URL of the client
        if (!($uri = $operation->getUri())) {
            return $client->createRequest($operation->getHttpMethod(), $client->getBaseUrl(), null, null, $options);
        }

        // Get the path values and use the client config settings
        $variables = array();
        foreach ($operation->getParams() as $name => $arg) {
            if ($arg->getLocation() == 'uri') {
                if (isset($command[$name])) {
                    $variables[$name] = $arg->filter($command[$name]);
                    if (!is_array($variables[$name])) {
                        $variables[$name] = (string) $variables[$name];
                    }
                }
            }
        }

        return $client->createRequest($operation->getHttpMethod(), array($uri, $variables), null, null, $options);
    }
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Http\Message\Response;

/**
 * Default HTTP response parser used to marshal JSON responses into arrays and XML responses into SimpleXMLElement
 */
class DefaultResponseParser implements ResponseParserInterface
{
    /** @var self */
    protected static $instance;

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function parse(CommandInterface $command)
    {
        $response = $command->getRequest()->getResponse();

        // Account for hard coded content-type values specified in service descriptions
        if ($contentType = $command['command.expects']) {
            $response->setHeader('Content-Type', $contentType);
        } else {
            $contentType = (string) $response->getHeader('Content-Type');
        }

        return $this->handleParsing($command, $response, $contentType);
    }

    protected function handleParsing(CommandInterface $command, Response $response, $contentType)
    {
        $result = $response;
        if ($result->getBody()) {
            if (stripos($contentType, 'json') !== false) {
                $result = $result->json();
            } elseif (stripos($contentType, 'xml') !== false) {
                $result = $result->xml();
            }
        }

        return $result;
    }
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;

/**
 * Translates command options and operation parameters into a request object
 */
interface RequestSerializerInterface
{
    /**
     * Create a request for a command
     *
     * @param CommandInterface $command Command that will own the request
     *
     * @return RequestInterface
     */
    public function prepare(CommandInterface $command);
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\UnexpectedValueException;
use Guzzle\Http\Message\RequestInterface;

/**
 * A ClosureCommand is a command that allows dynamic commands to be created at runtime using a closure to prepare the
 * request. A closure key and \Closure value must be passed to the command in the constructor. The closure must
 * accept the command object as an argument.
 */
class ClosureCommand extends AbstractCommand
{
    /**
     * {@inheritdoc}
     * @throws InvalidArgumentException if a closure was not passed
     */
    protected function init()
    {
        if (!$this['closure']) {
            throw new InvalidArgumentException('A closure must be passed in the parameters array');
        }
    }

    /**
     * {@inheritdoc}
     * @throws UnexpectedValueException If the closure does not return a request
     */
    protected function build()
    {
        $closure = $this['closure'];
        /** @var $closure \Closure */
        $this->request = $closure($this, $this->operation);

        if (!$this->request || !$this->request instanceof RequestInterface) {
            throw new UnexpectedValueException('Closure command did not return a RequestInterface object');
        }
    }
}
<?php

namespace Guzzle\Service\Command;

/**
 * Interface used to accept a completed OperationCommand and parse the result into a specific response type
 */
interface ResponseClassInterface
{
    /**
     * Create a response model object from a completed command
     *
     * @param OperationCommand $command That serialized the request
     *
     * @return self
     */
    public static function fromCommand(OperationCommand $command);
}
<?php

namespace Guzzle\Service\Command;

/**
 * A command that creates requests based on {@see Guzzle\Service\Description\OperationInterface} objects, and if the
 * matching operation uses a service description model in the responseClass attribute, then this command will marshal
 * the response into an associative array based on the JSON schema of the model.
 */
class OperationCommand extends AbstractCommand
{
    /** @var RequestSerializerInterface */
    protected $requestSerializer;

    /** @var ResponseParserInterface Response parser */
    protected $responseParser;

    /**
     * Set the response parser used with the command
     *
     * @param ResponseParserInterface $parser Response parser
     *
     * @return self
     */
    public function setResponseParser(ResponseParserInterface $parser)
    {
        $this->responseParser = $parser;

        return $this;
    }

    /**
     * Set the request serializer used with the command
     *
     * @param RequestSerializerInterface $serializer Request serializer
     *
     * @return self
     */
    public function setRequestSerializer(RequestSerializerInterface $serializer)
    {
        $this->requestSerializer = $serializer;

        return $this;
    }

    /**
     * Get the request serializer used with the command
     *
     * @return RequestSerializerInterface
     */
    public function getRequestSerializer()
    {
        if (!$this->requestSerializer) {
            // Use the default request serializer if none was found
            $this->requestSerializer = DefaultRequestSerializer::getInstance();
        }

        return $this->requestSerializer;
    }

    /**
     * Get the response parser used for the operation
     *
     * @return ResponseParserInterface
     */
    public function getResponseParser()
    {
        if (!$this->responseParser) {
            // Use the default response parser if none was found
            $this->responseParser = OperationResponseParser::getInstance();
        }

        return $this->responseParser;
    }

    protected function build()
    {
        // Prepare and serialize the request
        $this->request = $this->getRequestSerializer()->prepare($this);
    }

    protected function process()
    {
        // Do not process the response if 'command.response_processing' is set to 'raw'
        $this->result = $this[self::RESPONSE_PROCESSING] == self::TYPE_RAW
            ? $this->request->getResponse()
            : $this->getResponseParser()->parse($this);
    }
}
<?php

namespace Guzzle\Service\Command;

/**
 * Parses the HTTP response of a command and sets the appropriate result on a command object
 */
interface ResponseParserInterface
{
    /**
     * Parse the HTTP response received by the command and update the command's result contents
     *
     * @param CommandInterface $command Command to parse and update
     *
     * @return mixed Returns the result to set on the command
     */
    public function parse(CommandInterface $command);
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Curl\CurlHandle;
use Guzzle\Service\Client;
use Guzzle\Service\ClientInterface;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\OperationInterface;
use Guzzle\Service\Description\ValidatorInterface;
use Guzzle\Service\Description\SchemaValidator;
use Guzzle\Service\Exception\CommandException;
use Guzzle\Service\Exception\ValidationException;

/**
 * Command object to handle preparing and processing client requests and responses of the requests
 */
abstract class AbstractCommand extends Collection implements CommandInterface
{
    // @deprecated: Option used to specify custom headers to add to the generated request
    const HEADERS_OPTION = 'command.headers';
    // @deprecated: Option used to add an onComplete method to a command
    const ON_COMPLETE = 'command.on_complete';
    // @deprecated: Option used to change the entity body used to store a response
    const RESPONSE_BODY = 'command.response_body';

    // Option used to add request options to the request created by a command
    const REQUEST_OPTIONS = 'command.request_options';
    // command values to not count as additionalParameters
    const HIDDEN_PARAMS = 'command.hidden_params';
    // Option used to disable any pre-sending command validation
    const DISABLE_VALIDATION = 'command.disable_validation';
    // Option used to override how a command result will be formatted
    const RESPONSE_PROCESSING = 'command.response_processing';
    // Different response types that commands can use
    const TYPE_RAW = 'raw';
    const TYPE_MODEL = 'model';
    const TYPE_NO_TRANSLATION = 'no_translation';

    /** @var ClientInterface Client object used to execute the command */
    protected $client;

    /** @var RequestInterface The request object associated with the command */
    protected $request;

    /** @var mixed The result of the command */
    protected $result;

    /** @var OperationInterface API information about the command */
    protected $operation;

    /** @var mixed callable */
    protected $onComplete;

    /** @var ValidatorInterface Validator used to prepare and validate properties against a JSON schema */
    protected $validator;

    /**
     * @param array|Collection   $parameters Collection of parameters to set on the command
     * @param OperationInterface $operation Command definition from description
     */
    public function __construct($parameters = array(), OperationInterface $operation = null)
    {
        parent::__construct($parameters);
        $this->operation = $operation ?: $this->createOperation();
        foreach ($this->operation->getParams() as $name => $arg) {
            $currentValue = $this[$name];
            $configValue = $arg->getValue($currentValue);
            // If default or static values are set, then this should always be updated on the config object
            if ($currentValue !== $configValue) {
                $this[$name] = $configValue;
            }
        }

        $headers = $this[self::HEADERS_OPTION];
        if (!$headers instanceof Collection) {
            $this[self::HEADERS_OPTION] = new Collection((array) $headers);
        }

        // You can set a command.on_complete option in your parameters to set an onComplete callback
        if ($onComplete = $this['command.on_complete']) {
            unset($this['command.on_complete']);
            $this->setOnComplete($onComplete);
        }

        // Set the hidden additional parameters
        if (!$this[self::HIDDEN_PARAMS]) {
            $this[self::HIDDEN_PARAMS] = array(
                self::HEADERS_OPTION,
                self::RESPONSE_PROCESSING,
                self::HIDDEN_PARAMS,
                self::REQUEST_OPTIONS
            );
        }

        $this->init();
    }

    /**
     * Custom clone behavior
     */
    public function __clone()
    {
        $this->request = null;
        $this->result = null;
    }

    /**
     * Execute the command in the same manner as calling a function
     *
     * @return mixed Returns the result of {@see AbstractCommand::execute}
     */
    public function __invoke()
    {
        return $this->execute();
    }

    public function getName()
    {
        return $this->operation->getName();
    }

    /**
     * Get the API command information about the command
     *
     * @return OperationInterface
     */
    public function getOperation()
    {
        return $this->operation;
    }

    public function setOnComplete($callable)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('The onComplete function must be callable');
        }

        $this->onComplete = $callable;

        return $this;
    }

    public function execute()
    {
        if (!$this->client) {
            throw new CommandException('A client must be associated with the command before it can be executed.');
        }

        return $this->client->execute($this);
    }

    public function getClient()
    {
        return $this->client;
    }

    public function setClient(ClientInterface $client)
    {
        $this->client = $client;

        return $this;
    }

    public function getRequest()
    {
        if (!$this->request) {
            throw new CommandException('The command must be prepared before retrieving the request');
        }

        return $this->request;
    }

    public function getResponse()
    {
        if (!$this->isExecuted()) {
            $this->execute();
        }

        return $this->request->getResponse();
    }

    public function getResult()
    {
        if (!$this->isExecuted()) {
            $this->execute();
        }

        if (null === $this->result) {
            $this->process();
            // Call the onComplete method if one is set
            if ($this->onComplete) {
                call_user_func($this->onComplete, $this);
            }
        }

        return $this->result;
    }

    public function setResult($result)
    {
        $this->result = $result;

        return $this;
    }

    public function isPrepared()
    {
        return $this->request !== null;
    }

    public function isExecuted()
    {
        return $this->request !== null && $this->request->getState() == 'complete';
    }

    public function prepare()
    {
        if (!$this->isPrepared()) {
            if (!$this->client) {
                throw new CommandException('A client must be associated with the command before it can be prepared.');
            }

            // If no response processing value was specified, then attempt to use the highest level of processing
            if (!isset($this[self::RESPONSE_PROCESSING])) {
                $this[self::RESPONSE_PROCESSING] = self::TYPE_MODEL;
            }

            // Notify subscribers of the client that the command is being prepared
            $this->client->dispatch('command.before_prepare', array('command' => $this));

            // Fail on missing required arguments, and change parameters via filters
            $this->validate();
            // Delegate to the subclass that implements the build method
            $this->build();

            // Add custom request headers set on the command
            if ($headers = $this[self::HEADERS_OPTION]) {
                foreach ($headers as $key => $value) {
                    $this->request->setHeader($key, $value);
                }
            }

            // Add any curl options to the request
            if ($options = $this[Client::CURL_OPTIONS]) {
                $this->request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($options));
            }

            // Set a custom response body
            if ($responseBody = $this[self::RESPONSE_BODY]) {
                $this->request->setResponseBody($responseBody);
            }

            $this->client->dispatch('command.after_prepare', array('command' => $this));
        }

        return $this->request;
    }

    /**
     * Set the validator used to validate and prepare command parameters and nested JSON schemas. If no validator is
     * set, then the command will validate using the default {@see SchemaValidator}.
     *
     * @param ValidatorInterface $validator Validator used to prepare and validate properties against a JSON schema
     *
     * @return self
     */
    public function setValidator(ValidatorInterface $validator)
    {
        $this->validator = $validator;

        return $this;
    }

    public function getRequestHeaders()
    {
        return $this[self::HEADERS_OPTION];
    }

    /**
     * Initialize the command (hook that can be implemented in subclasses)
     */
    protected function init() {}

    /**
     * Create the request object that will carry out the command
     */
    abstract protected function build();

    /**
     * Hook used to create an operation for concrete commands that are not associated with a service description
     *
     * @return OperationInterface
     */
    protected function createOperation()
    {
        return new Operation(array('name' => get_class($this)));
    }

    /**
     * Create the result of the command after the request has been completed.
     * Override this method in subclasses to customize this behavior
     */
    protected function process()
    {
        $this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW
            ? DefaultResponseParser::getInstance()->parse($this)
            : $this->request->getResponse();
    }

    /**
     * Validate and prepare the command based on the schema and rules defined by the command's Operation object
     *
     * @throws ValidationException when validation errors occur
     */
    protected function validate()
    {
        // Do not perform request validation/transformation if it is disable
        if ($this[self::DISABLE_VALIDATION]) {
            return;
        }

        $errors = array();
        $validator = $this->getValidator();
        foreach ($this->operation->getParams() as $name => $schema) {
            $value = $this[$name];
            if (!$validator->validate($schema, $value)) {
                $errors = array_merge($errors, $validator->getErrors());
            } elseif ($value !== $this[$name]) {
                // Update the config value if it changed and no validation errors were encountered
                $this->data[$name] = $value;
            }
        }

        // Validate additional parameters
        $hidden = $this[self::HIDDEN_PARAMS];

        if ($properties = $this->operation->getAdditionalParameters()) {
            foreach ($this->toArray() as $name => $value) {
                // It's only additional if it isn't defined in the schema
                if (!$this->operation->hasParam($name) && !in_array($name, $hidden)) {
                    // Always set the name so that error messages are useful
                    $properties->setName($name);
                    if (!$validator->validate($properties, $value)) {
                        $errors = array_merge($errors, $validator->getErrors());
                    } elseif ($value !== $this[$name]) {
                        $this->data[$name] = $value;
                    }
                }
            }
        }

        if (!empty($errors)) {
            $e = new ValidationException('Validation errors: ' . implode("\n", $errors));
            $e->setErrors($errors);
            throw $e;
        }
    }

    /**
     * Get the validator used to prepare and validate properties. If no validator has been set on the command, then
     * the default {@see SchemaValidator} will be used.
     *
     * @return ValidatorInterface
     */
    protected function getValidator()
    {
        if (!$this->validator) {
            $this->validator = SchemaValidator::getInstance();
        }

        return $this->validator;
    }

    /**
     * Get array of any validation errors
     * If no validator has been set then return false
     */
    public function getValidationErrors()
    {
        if (!$this->validator) {
            return false;
        }

        return $this->validator->getErrors();
    }
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Command\LocationVisitor\VisitorFlyweight;
use Guzzle\Service\Command\LocationVisitor\Response\ResponseVisitorInterface;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\OperationInterface;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Exception\ResponseClassException;
use Guzzle\Service\Resource\Model;

/**
 * Response parser that attempts to marshal responses into an associative array based on models in a service description
 */
class OperationResponseParser extends DefaultResponseParser
{
    /** @var VisitorFlyweight $factory Visitor factory */
    protected $factory;

    /** @var self */
    protected static $instance;

    /** @var bool */
    private $schemaInModels;

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!static::$instance) {
            static::$instance = new static(VisitorFlyweight::getInstance());
        }

        return static::$instance;
    }

    /**
     * @param VisitorFlyweight $factory        Factory to use when creating visitors
     * @param bool             $schemaInModels Set to true to inject schemas into models
     */
    public function __construct(VisitorFlyweight $factory, $schemaInModels = false)
    {
        $this->factory = $factory;
        $this->schemaInModels = $schemaInModels;
    }

    /**
     * Add a location visitor to the command
     *
     * @param string                   $location Location to associate with the visitor
     * @param ResponseVisitorInterface $visitor  Visitor to attach
     *
     * @return self
     */
    public function addVisitor($location, ResponseVisitorInterface $visitor)
    {
        $this->factory->addResponseVisitor($location, $visitor);

        return $this;
    }

    protected function handleParsing(CommandInterface $command, Response $response, $contentType)
    {
        $operation = $command->getOperation();
        $type = $operation->getResponseType();
        $model = null;

        if ($type == OperationInterface::TYPE_MODEL) {
            $model = $operation->getServiceDescription()->getModel($operation->getResponseClass());
        } elseif ($type == OperationInterface::TYPE_CLASS) {
            return $this->parseClass($command);
        }

        if (!$model) {
            // Return basic processing if the responseType is not model or the model cannot be found
            return parent::handleParsing($command, $response, $contentType);
        } elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) {
            // Returns a model with no visiting if the command response processing is not model
            return new Model(parent::handleParsing($command, $response, $contentType));
        } else {
            // Only inject the schema into the model if "schemaInModel" is true
            return new Model($this->visitResult($model, $command, $response), $this->schemaInModels ? $model : null);
        }
    }

    /**
     * Parse a class object
     *
     * @param CommandInterface $command Command to parse into an object
     *
     * @return mixed
     * @throws ResponseClassException
     */
    protected function parseClass(CommandInterface $command)
    {
        // Emit the operation.parse_class event. If a listener injects a 'result' property, then that will be the result
        $event = new CreateResponseClassEvent(array('command' => $command));
        $command->getClient()->getEventDispatcher()->dispatch('command.parse_response', $event);
        if ($result = $event->getResult()) {
            return $result;
        }

        $className = $command->getOperation()->getResponseClass();
        if (!method_exists($className, 'fromCommand')) {
            throw new ResponseClassException("{$className} must exist and implement a static fromCommand() method");
        }

        return $className::fromCommand($command);
    }

    /**
     * Perform transformations on the result array
     *
     * @param Parameter        $model    Model that defines the structure
     * @param CommandInterface $command  Command that performed the operation
     * @param Response         $response Response received
     *
     * @return array Returns the array of result data
     */
    protected function visitResult(Parameter $model, CommandInterface $command, Response $response)
    {
        $foundVisitors = $result = $knownProps = array();
        $props = $model->getProperties();

        foreach ($props as $schema) {
            if ($location = $schema->getLocation()) {
                // Trigger the before method on the first found visitor of this type
                if (!isset($foundVisitors[$location])) {
                    $foundVisitors[$location] = $this->factory->getResponseVisitor($location);
                    $foundVisitors[$location]->before($command, $result);
                }
            }
        }

        // Visit additional properties when it is an actual schema
        if (($additional = $model->getAdditionalProperties()) instanceof Parameter) {
            $this->visitAdditionalProperties($model, $command, $response, $additional, $result, $foundVisitors);
        }

        // Apply the parameter value with the location visitor
        foreach ($props as $schema) {
            $knownProps[$schema->getName()] = 1;
            if ($location = $schema->getLocation()) {
                $foundVisitors[$location]->visit($command, $response, $schema, $result);
            }
        }

        // Remove any unknown and potentially unsafe top-level properties
        if ($additional === false) {
            $result = array_intersect_key($result, $knownProps);
        }

        // Call the after() method of each found visitor
        foreach ($foundVisitors as $visitor) {
            $visitor->after($command);
        }

        return $result;
    }

    protected function visitAdditionalProperties(
        Parameter $model,
        CommandInterface $command,
        Response $response,
        Parameter $additional,
        &$result,
        array &$foundVisitors
    ) {
        // Only visit when a location is specified
        if ($location = $additional->getLocation()) {
            if (!isset($foundVisitors[$location])) {
                $foundVisitors[$location] = $this->factory->getResponseVisitor($location);
                $foundVisitors[$location]->before($command, $result);
            }
            // Only traverse if an array was parsed from the before() visitors
            if (is_array($result)) {
                // Find each additional property
                foreach (array_keys($result) as $key) {
                    // Check if the model actually knows this property. If so, then it is not additional
                    if (!$model->getProperty($key)) {
                        // Set the name to the key so that we can parse it with each visitor
                        $additional->setName($key);
                        $foundVisitors[$location]->visit($command, $response, $additional, $result);
                    }
                }
                // Reset the additionalProperties name to null
                $additional->setName(null);
            }
        }
    }
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Exception\CommandException;
use Guzzle\Service\Description\OperationInterface;
use Guzzle\Service\ClientInterface;
use Guzzle\Common\ToArrayInterface;

/**
 * A command object that contains parameters that can be modified and accessed like an array and turned into an array
 */
interface CommandInterface extends \ArrayAccess, ToArrayInterface
{
    /**
     * Get the short form name of the command
     *
     * @return string
     */
    public function getName();

    /**
     * Get the API operation information about the command
     *
     * @return OperationInterface
     */
    public function getOperation();

    /**
     * Execute the command and return the result
     *
     * @return mixed Returns the result of {@see CommandInterface::execute}
     * @throws CommandException if a client has not been associated with the command
     */
    public function execute();

    /**
     * Get the client object that will execute the command
     *
     * @return ClientInterface|null
     */
    public function getClient();

    /**
     * Set the client object that will execute the command
     *
     * @param ClientInterface $client The client object that will execute the command
     *
     * @return self
     */
    public function setClient(ClientInterface $client);

    /**
     * Get the request object associated with the command
     *
     * @return RequestInterface
     * @throws CommandException if the command has not been executed
     */
    public function getRequest();

    /**
     * Get the response object associated with the command
     *
     * @return Response
     * @throws CommandException if the command has not been executed
     */
    public function getResponse();

    /**
     * Get the result of the command
     *
     * @return Response By default, commands return a Response object unless overridden in a subclass
     * @throws CommandException if the command has not been executed
     */
    public function getResult();

    /**
     * Set the result of the command
     *
     * @param mixed $result Result to set
     *
     * @return self
     */
    public function setResult($result);

    /**
     * Returns TRUE if the command has been prepared for executing
     *
     * @return bool
     */
    public function isPrepared();

    /**
     * Returns TRUE if the command has been executed
     *
     * @return bool
     */
    public function isExecuted();

    /**
     * Prepare the command for executing and create a request object.
     *
     * @return RequestInterface Returns the generated request
     * @throws CommandException if a client object has not been set previously or in the prepare()
     */
    public function prepare();

    /**
     * Get the object that manages the request headers that will be set on any outbound requests from the command
     *
     * @return Collection
     */
    public function getRequestHeaders();

    /**
     * Specify a callable to execute when the command completes
     *
     * @param mixed $callable Callable to execute when the command completes. The callable must accept a
     *                        {@see CommandInterface} object as the only argument.
     * @return self
     * @throws InvalidArgumentException
     */
    public function setOnComplete($callable);
}
<?php

namespace Guzzle\Service\Command\Factory;

use Guzzle\Inflection\InflectorInterface;
use Guzzle\Inflection\Inflector;
use Guzzle\Service\ClientInterface;

/**
 * Command factory used to create commands referencing concrete command classes
 */
class ConcreteClassFactory implements FactoryInterface
{
    /** @var ClientInterface */
    protected $client;

    /** @var InflectorInterface */
    protected $inflector;

    /**
     * @param ClientInterface    $client    Client that owns the commands
     * @param InflectorInterface $inflector Inflector used to resolve class names
     */
    public function __construct(ClientInterface $client, InflectorInterface $inflector = null)
    {
        $this->client = $client;
        $this->inflector = $inflector ?: Inflector::getDefault();
    }

    public function factory($name, array $args = array())
    {
        // Determine the class to instantiate based on the namespace of the current client and the default directory
        $prefix = $this->client->getConfig('command.prefix');
        if (!$prefix) {
            // The prefix can be specified in a factory method and is cached
            $prefix = implode('\\', array_slice(explode('\\', get_class($this->client)), 0, -1)) . '\\Command\\';
            $this->client->getConfig()->set('command.prefix', $prefix);
        }

        $class = $prefix . str_replace(' ', '\\', ucwords(str_replace('.', ' ', $this->inflector->camel($name))));

        // Create the concrete command if it exists
        if (class_exists($class)) {
            return new $class($args);
        }
    }
}
<?php

namespace Guzzle\Service\Command\Factory;

use Guzzle\Service\Command\CommandInterface;

/**
 * Interface for creating commands by name
 */
interface FactoryInterface
{
    /**
     * Create a command by name
     *
     * @param string $name Command to create
     * @param array  $args Command arguments
     *
     * @return CommandInterface|null
     */
    public function factory($name, array $args = array());
}
<?php

namespace Guzzle\Service\Command\Factory;

use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\ClientInterface;

/**
 * Composite factory used by a client object to create command objects utilizing multiple factories
 */
class CompositeFactory implements \IteratorAggregate, \Countable, FactoryInterface
{
    /** @var array Array of command factories */
    protected $factories;

    /**
     * Get the default chain to use with clients
     *
     * @param ClientInterface $client Client to base the chain on
     *
     * @return self
     */
    public static function getDefaultChain(ClientInterface $client)
    {
        $factories = array();
        if ($description = $client->getDescription()) {
            $factories[] = new ServiceDescriptionFactory($description);
        }
        $factories[] = new ConcreteClassFactory($client);

        return new self($factories);
    }

    /**
     * @param array $factories Array of command factories
     */
    public function __construct(array $factories = array())
    {
        $this->factories = $factories;
    }

    /**
     * Add a command factory to the chain
     *
     * @param FactoryInterface        $factory Factory to add
     * @param string|FactoryInterface $before  Insert the new command factory before a command factory class or object
     *                                         matching a class name.
     * @return CompositeFactory
     */
    public function add(FactoryInterface $factory, $before = null)
    {
        $pos = null;

        if ($before) {
            foreach ($this->factories as $i => $f) {
                if ($before instanceof FactoryInterface) {
                    if ($f === $before) {
                        $pos = $i;
                        break;
                    }
                } elseif (is_string($before)) {
                    if ($f instanceof $before) {
                        $pos = $i;
                        break;
                    }
                }
            }
        }

        if ($pos === null) {
            $this->factories[] = $factory;
        } else {
            array_splice($this->factories, $i, 0, array($factory));
        }

        return $this;
    }

    /**
     * Check if the chain contains a specific command factory
     *
     * @param FactoryInterface|string $factory Factory to check
     *
     * @return bool
     */
    public function has($factory)
    {
        return (bool) $this->find($factory);
    }

    /**
     * Remove a specific command factory from the chain
     *
     * @param string|FactoryInterface $factory Factory to remove by name or instance
     *
     * @return CompositeFactory
     */
    public function remove($factory = null)
    {
        if (!($factory instanceof FactoryInterface)) {
            $factory = $this->find($factory);
        }

        $this->factories = array_values(array_filter($this->factories, function($f) use ($factory) {
            return $f !== $factory;
        }));

        return $this;
    }

    /**
     * Get a command factory by class name
     *
     * @param string|FactoryInterface $factory Command factory class or instance
     *
     * @return null|FactoryInterface
     */
    public function find($factory)
    {
        foreach ($this->factories as $f) {
            if ($factory === $f || (is_string($factory) && $f instanceof $factory)) {
                return $f;
            }
        }
    }

    /**
     * Create a command using the associated command factories
     *
     * @param string $name Name of the command
     * @param array  $args Command arguments
     *
     * @return CommandInterface
     */
    public function factory($name, array $args = array())
    {
        foreach ($this->factories as $factory) {
            $command = $factory->factory($name, $args);
            if ($command) {
                return $command;
            }
        }
    }

    public function count()
    {
        return count($this->factories);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->factories);
    }
}
<?php

namespace Guzzle\Service\Command\Factory;

use Guzzle\Service\Description\ServiceDescriptionInterface;
use Guzzle\Inflection\InflectorInterface;

/**
 * Command factory used to create commands based on service descriptions
 */
class ServiceDescriptionFactory implements FactoryInterface
{
    /** @var ServiceDescriptionInterface */
    protected $description;

    /** @var InflectorInterface */
    protected $inflector;

    /**
     * @param ServiceDescriptionInterface $description Service description
     * @param InflectorInterface          $inflector   Optional inflector to use if the command is not at first found
     */
    public function __construct(ServiceDescriptionInterface $description, InflectorInterface $inflector = null)
    {
        $this->setServiceDescription($description);
        $this->inflector = $inflector;
    }

    /**
     * Change the service description used with the factory
     *
     * @param ServiceDescriptionInterface $description Service description to use
     *
     * @return FactoryInterface
     */
    public function setServiceDescription(ServiceDescriptionInterface $description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Returns the service description
     *
     * @return ServiceDescriptionInterface
     */
    public function getServiceDescription()
    {
        return $this->description;
    }

    public function factory($name, array $args = array())
    {
        $command = $this->description->getOperation($name);

        // If a command wasn't found, then try to uppercase the first letter and try again
        if (!$command) {
            $command = $this->description->getOperation(ucfirst($name));
            // If an inflector was passed, then attempt to get the command using snake_case inflection
            if (!$command && $this->inflector) {
                $command = $this->description->getOperation($this->inflector->snake($name));
            }
        }

        if ($command) {
            $class = $command->getClass();
            return new $class($args, $command, $this->description);
        }
    }
}
<?php

namespace Guzzle\Service\Command\Factory;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\ClientInterface;

/**
 * Command factory used when you need to provide aliases to commands
 */
class AliasFactory implements FactoryInterface
{
    /** @var array Associative array mapping command aliases to the aliased command */
    protected $aliases;

    /** @var ClientInterface Client used to retry using aliases */
    protected $client;

    /**
     * @param ClientInterface $client  Client used to retry with the alias
     * @param array           $aliases Associative array mapping aliases to the alias
     */
    public function __construct(ClientInterface $client, array $aliases)
    {
        $this->client = $client;
        $this->aliases = $aliases;
    }

    public function factory($name, array $args = array())
    {
        if (isset($this->aliases[$name])) {
            try {
                return $this->client->getCommand($this->aliases[$name], $args);
            } catch (InvalidArgumentException $e) {
                return null;
            }
        }
    }
}
<?php

namespace Guzzle\Service\Command\Factory;

/**
 * Command factory used when explicitly mapping strings to command classes
 */
class MapFactory implements FactoryInterface
{
    /** @var array Associative array mapping command names to classes */
    protected $map;

    /** @param array $map Associative array mapping command names to classes */
    public function __construct(array $map)
    {
        $this->map = $map;
    }

    public function factory($name, array $args = array())
    {
        if (isset($this->map[$name])) {
            $class = $this->map[$name];

            return new $class($args);
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to add the reason phrase of a response to a key in the result
 */
class ReasonPhraseVisitor extends AbstractResponseVisitor
{
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        $value[$param->getName()] = $response->getReasonPhrase();
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to parse values out of a response into an associative array
 */
interface ResponseVisitorInterface
{
    /**
     * Called before visiting all parameters. This can be used for seeding the result of a command with default
     * data (e.g. populating with JSON data in the response then adding to the parsed data).
     *
     * @param CommandInterface $command Command being visited
     * @param array            $result  Result value to update if needed (e.g. parsing XML or JSON)
     */
    public function before(CommandInterface $command, array &$result);

    /**
     * Called after visiting all parameters
     *
     * @param CommandInterface $command Command being visited
     */
    public function after(CommandInterface $command);

    /**
     * Called once for each parameter being visited that matches the location type
     *
     * @param CommandInterface $command  Command being visited
     * @param Response         $response Response being visited
     * @param Parameter        $param    Parameter being visited
     * @param mixed            $value    Result associative array value being updated by reference
     * @param mixed            $context  Parsing context
     */
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    );
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;

/**
 * {@inheritdoc}
 * @codeCoverageIgnore
 */
abstract class AbstractResponseVisitor implements ResponseVisitorInterface
{
    public function before(CommandInterface $command, array &$result) {}

    public function after(CommandInterface $command) {}

    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {}
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to add a particular header of a response to a key in the result
 */
class HeaderVisitor extends AbstractResponseVisitor
{
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        if ($param->getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) {
            $this->processPrefixedHeaders($response, $param, $value);
        } else {
            $value[$param->getName()] = $param->filter((string) $response->getHeader($param->getWireName()));
        }
    }

    /**
     * Process a prefixed header array
     *
     * @param Response  $response Response that contains the headers
     * @param Parameter $param    Parameter object
     * @param array     $value    Value response array to modify
     */
    protected function processPrefixedHeaders(Response $response, Parameter $param, &$value)
    {
        // Grab prefixed headers that should be placed into an array with the prefix stripped
        if ($prefix = $param->getSentAs()) {
            $container = $param->getName();
            $len = strlen($prefix);
            // Find all matching headers and place them into the containing element
            foreach ($response->getHeaders()->toArray() as $key => $header) {
                if (stripos($key, $prefix) === 0) {
                    // Account for multi-value headers
                    $value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header;
                }
            }
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to marshal XML response data into a formatted array
 */
class XmlVisitor extends AbstractResponseVisitor
{
    public function before(CommandInterface $command, array &$result)
    {
        // Set the result of the command to the array conversion of the XML body
        $result = json_decode(json_encode($command->getResponse()->xml()), true);
    }

    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        $sentAs = $param->getWireName();
        $name = $param->getName();
        if (isset($value[$sentAs])) {
            $this->recursiveProcess($param, $value[$sentAs]);
            if ($name != $sentAs) {
                $value[$name] = $value[$sentAs];
                unset($value[$sentAs]);
            }
        }
    }

    /**
     * Recursively process a parameter while applying filters
     *
     * @param Parameter $param API parameter being processed
     * @param mixed     $value Value to validate and process. The value may change during this process.
     */
    protected function recursiveProcess(Parameter $param, &$value)
    {
        $type = $param->getType();

        if (!is_array($value)) {
            if ($type == 'array') {
                // Cast to an array if the value was a string, but should be an array
                $this->recursiveProcess($param->getItems(), $value);
                $value = array($value);
            }
        } elseif ($type == 'object') {
            $this->processObject($param, $value);
        } elseif ($type == 'array') {
            $this->processArray($param, $value);
        } elseif ($type == 'string' && gettype($value) == 'array') {
            $value = '';
        }

        if ($value !== null) {
            $value = $param->filter($value);
        }
    }

    /**
     * Process an array
     *
     * @param Parameter $param API parameter being parsed
     * @param mixed     $value Value to process
     */
    protected function processArray(Parameter $param, &$value)
    {
        // Convert the node if it was meant to be an array
        if (!isset($value[0])) {
            // Collections fo nodes are sometimes wrapped in an additional array. For example:
            // <Items><Item><a>1</a></Item><Item><a>2</a></Item></Items> should become:
            // array('Items' => array(array('a' => 1), array('a' => 2))
            // Some nodes are not wrapped. For example: <Foo><a>1</a></Foo><Foo><a>2</a></Foo>
            // should become array('Foo' => array(array('a' => 1), array('a' => 2))
            if ($param->getItems() && isset($value[$param->getItems()->getWireName()])) {
                // Account for the case of a collection wrapping wrapped nodes: Items => Item[]
                $value = $value[$param->getItems()->getWireName()];
                // If the wrapped node only had one value, then make it an array of nodes
                if (!isset($value[0]) || !is_array($value)) {
                    $value = array($value);
                }
            } elseif (!empty($value)) {
                // Account for repeated nodes that must be an array: Foo => Baz, Foo => Baz, but only if the
                // value is set and not empty
                $value = array($value);
            }
        }

        foreach ($value as &$item) {
            $this->recursiveProcess($param->getItems(), $item);
        }
    }

    /**
     * Process an object
     *
     * @param Parameter $param API parameter being parsed
     * @param mixed     $value Value to process
     */
    protected function processObject(Parameter $param, &$value)
    {
        // Ensure that the array is associative and not numerically indexed
        if (!isset($value[0]) && ($properties = $param->getProperties())) {
            $knownProperties = array();
            foreach ($properties as $property) {
                $name = $property->getName();
                $sentAs = $property->getWireName();
                $knownProperties[$name] = 1;
                if ($property->getData('xmlAttribute')) {
                    $this->processXmlAttribute($property, $value);
                } elseif (isset($value[$sentAs])) {
                    $this->recursiveProcess($property, $value[$sentAs]);
                    if ($name != $sentAs) {
                        $value[$name] = $value[$sentAs];
                        unset($value[$sentAs]);
                    }
                }
            }

            // Remove any unknown and potentially unsafe properties
            if ($param->getAdditionalProperties() === false) {
                $value = array_intersect_key($value, $knownProperties);
            }
        }
    }

    /**
     * Process an XML attribute property
     *
     * @param Parameter $property Property to process
     * @param array     $value    Value to process and update
     */
    protected function processXmlAttribute(Parameter $property, array &$value)
    {
        $sentAs = $property->getWireName();
        if (isset($value['@attributes'][$sentAs])) {
            $value[$property->getName()] = $value['@attributes'][$sentAs];
            unset($value['@attributes'][$sentAs]);
            if (empty($value['@attributes'])) {
                unset($value['@attributes']);
            }
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to add the body of a response to a particular key
 */
class BodyVisitor extends AbstractResponseVisitor
{
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        $value[$param->getName()] = $param->filter($response->getBody());
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to marshal JSON response data into a formatted array.
 *
 * Allows top level JSON parameters to be inserted into the result of a command. The top level attributes are grabbed
 * from the response's JSON data using the name value by default. Filters can be applied to parameters as they are
 * traversed. This allows data to be normalized before returning it to users (for example converting timestamps to
 * DateTime objects).
 */
class JsonVisitor extends AbstractResponseVisitor
{
    public function before(CommandInterface $command, array &$result)
    {
        // Ensure that the result of the command is always rooted with the parsed JSON data
        $result = $command->getResponse()->json();
    }

    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        $name = $param->getName();
        $key = $param->getWireName();
        if (isset($value[$key])) {
            $this->recursiveProcess($param, $value[$key]);
            if ($key != $name) {
                $value[$name] = $value[$key];
                unset($value[$key]);
            }
        }
    }

    /**
     * Recursively process a parameter while applying filters
     *
     * @param Parameter $param API parameter being validated
     * @param mixed     $value Value to validate and process. The value may change during this process.
     */
    protected function recursiveProcess(Parameter $param, &$value)
    {
        if ($value === null) {
            return;
        }

        if (is_array($value)) {
            $type = $param->getType();
            if ($type == 'array') {
                foreach ($value as &$item) {
                    $this->recursiveProcess($param->getItems(), $item);
                }
            } elseif ($type == 'object' && !isset($value[0])) {
                // On the above line, we ensure that the array is associative and not numerically indexed
                $knownProperties = array();
                if ($properties = $param->getProperties()) {
                    foreach ($properties as $property) {
                        $name = $property->getName();
                        $key = $property->getWireName();
                        $knownProperties[$name] = 1;
                        if (isset($value[$key])) {
                            $this->recursiveProcess($property, $value[$key]);
                            if ($key != $name) {
                                $value[$name] = $value[$key];
                                unset($value[$key]);
                            }
                        }
                    }
                }

                // Remove any unknown and potentially unsafe properties
                if ($param->getAdditionalProperties() === false) {
                    $value = array_intersect_key($value, $knownProperties);
                } elseif (($additional = $param->getAdditionalProperties()) !== true) {
                    // Validate and filter additional properties
                    foreach ($value as &$v) {
                        $this->recursiveProcess($additional, $v);
                    }
                }
            }
        }

        $value = $param->filter($value);
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Response;

use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to add the status code of a response to a key in the result
 */
class StatusCodeVisitor extends AbstractResponseVisitor
{
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        $value[$param->getName()] = $response->getStatusCode();
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\PostFileInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a parameter to a POST file
 */
class PostFileVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $value = $param->filter($value);
        if ($value instanceof PostFileInterface) {
            $request->addPostFile($value);
        } else {
            $request->addPostFile($param->getWireName(), $value);
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a parameter to a POST field
 */
class PostFieldVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $request->setPostField($param->getWireName(), $this->prepareValue($value, $param));
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;

abstract class AbstractRequestVisitor implements RequestVisitorInterface
{
    /**
     * @codeCoverageIgnore
     */
    public function after(CommandInterface $command, RequestInterface $request) {}

    /**
     * @codeCoverageIgnore
     */
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) {}

    /**
     * Prepare (filter and set desired name for request item) the value for request.
     *
     * @param mixed                                     $value
     * @param \Guzzle\Service\Description\Parameter     $param
     *
     * @return array|mixed
     */
    protected function prepareValue($value, Parameter $param)
    {
        return is_array($value)
            ? $this->resolveRecursively($value, $param)
            : $param->filter($value);
    }

    /**
     * Map nested parameters into the location_key based parameters
     *
     * @param array     $value Value to map
     * @param Parameter $param Parameter that holds information about the current key
     *
     * @return array Returns the mapped array
     */
    protected function resolveRecursively(array $value, Parameter $param)
    {
        foreach ($value as $name => &$v) {
            switch ($param->getType()) {
                case 'object':
                    if ($subParam = $param->getProperty($name)) {
                        $key = $subParam->getWireName();
                        $value[$key] = $this->prepareValue($v, $subParam);
                        if ($name != $key) {
                            unset($value[$name]);
                        }
                    } elseif ($param->getAdditionalProperties() instanceof Parameter) {
                        $v = $this->prepareValue($v, $param->getAdditionalProperties());
                    }
                    break;
                case 'array':
                    if ($items = $param->getItems()) {
                        $v = $this->prepareValue($v, $items);
                    }
                    break;
            }
        }

        return $param->filter($value);
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to change the location in which a response body is saved
 */
class ResponseBodyVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $request->setResponseBody($value);
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a parameter to a request's query string
 */
class QueryVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $request->getQuery()->set($param->getWireName(), $this->prepareValue($value, $param));
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a parameter to a header value
 */
class HeaderVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $value = $param->filter($value);
        if ($param->getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) {
            $this->addPrefixedHeaders($request, $param, $value);
        } else {
            $request->setHeader($param->getWireName(), $value);
        }
    }

    /**
     * Add a prefixed array of headers to the request
     *
     * @param RequestInterface $request Request to update
     * @param Parameter        $param   Parameter object
     * @param array            $value   Header array to add
     *
     * @throws InvalidArgumentException
     */
    protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException('An array of mapped headers expected, but received a single value');
        }
        $prefix = $param->getSentAs();
        foreach ($value as $headerName => $headerValue) {
            $request->setHeader($prefix . $headerName, $headerValue);
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;

/**
 * Location visitor used to add values to different locations in a request with different behaviors as needed
 */
interface RequestVisitorInterface
{
    /**
     * Called after visiting all parameters
     *
     * @param CommandInterface $command Command being visited
     * @param RequestInterface $request Request being visited
     */
    public function after(CommandInterface $command, RequestInterface $request);

    /**
     * Called once for each parameter being visited that matches the location type
     *
     * @param CommandInterface $command Command being visited
     * @param RequestInterface $request Request being visited
     * @param Parameter        $param   Parameter being visited
     * @param mixed            $value   Value to set
     */
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value);
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Description\Parameter;

/**
 * Location visitor used to serialize XML bodies
 */
class XmlVisitor extends AbstractRequestVisitor
{
    /** @var \SplObjectStorage Data object for persisting XML data */
    protected $data;

    /** @var bool Content-Type header added when XML is found */
    protected $contentType = 'application/xml';

    public function __construct()
    {
        $this->data = new \SplObjectStorage();
    }

    /**
     * Change the content-type header that is added when XML is found
     *
     * @param string $header Header to set when XML is found
     *
     * @return self
     */
    public function setContentTypeHeader($header)
    {
        $this->contentType = $header;

        return $this;
    }

    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $xml = isset($this->data[$command])
            ? $this->data[$command]
            : $this->createRootElement($param->getParent());
        $this->addXml($xml, $param, $value);

        $this->data[$command] = $xml;
    }

    public function after(CommandInterface $command, RequestInterface $request)
    {
        $xml = null;

        // If data was found that needs to be serialized, then do so
        if (isset($this->data[$command])) {
            $xml = $this->finishDocument($this->data[$command]);
            unset($this->data[$command]);
        } else {
            // Check if XML should always be sent for the command
            $operation = $command->getOperation();
            if ($operation->getData('xmlAllowEmpty')) {
                $xmlWriter = $this->createRootElement($operation);
                $xml = $this->finishDocument($xmlWriter);
            }
        }

        if ($xml) {
            // Don't overwrite the Content-Type if one is set
            if ($this->contentType && !$request->hasHeader('Content-Type')) {
                $request->setHeader('Content-Type', $this->contentType);
            }
            $request->setBody($xml);
        }
    }

    /**
     * Create the root XML element to use with a request
     *
     * @param Operation $operation Operation object
     *
     * @return \XMLWriter
     */
    protected function createRootElement(Operation $operation)
    {
        static $defaultRoot = array('name' => 'Request');
        // If no root element was specified, then just wrap the XML in 'Request'
        $root = $operation->getData('xmlRoot') ?: $defaultRoot;
        // Allow the XML declaration to be customized with xmlEncoding
        $encoding = $operation->getData('xmlEncoding');

        $xmlWriter = $this->startDocument($encoding);

        $xmlWriter->startElement($root['name']);
        // Create the wrapping element with no namespaces if no namespaces were present
        if (!empty($root['namespaces'])) {
            // Create the wrapping element with an array of one or more namespaces
            foreach ((array) $root['namespaces'] as $prefix => $uri) {
                $nsLabel = 'xmlns';
                if (!is_numeric($prefix)) {
                    $nsLabel .= ':'.$prefix;
                }
                $xmlWriter->writeAttribute($nsLabel, $uri);
            }
        }
        return $xmlWriter;
    }

    /**
     * Recursively build the XML body
     *
     * @param \XMLWriter $xmlWriter XML to modify
     * @param Parameter  $param     API Parameter
     * @param mixed      $value     Value to add
     */
    protected function addXml(\XMLWriter $xmlWriter, Parameter $param, $value)
    {
        if ($value === null) {
            return;
        }

        $value = $param->filter($value);
        $type = $param->getType();
        $name = $param->getWireName();
        $prefix = null;
        $namespace = $param->getData('xmlNamespace');
        if (false !== strpos($name, ':')) {
            list($prefix, $name) = explode(':', $name, 2);
        }

        if ($type == 'object' || $type == 'array') {
            if (!$param->getData('xmlFlattened')) {
                $xmlWriter->startElementNS(null, $name, $namespace);
            }
            if ($param->getType() == 'array') {
                $this->addXmlArray($xmlWriter, $param, $value);
            } elseif ($param->getType() == 'object') {
                $this->addXmlObject($xmlWriter, $param, $value);
            }
            if (!$param->getData('xmlFlattened')) {
                $xmlWriter->endElement();
            }
            return;
        }
        if ($param->getData('xmlAttribute')) {
            $this->writeAttribute($xmlWriter, $prefix, $name, $namespace, $value);
        } else {
            $this->writeElement($xmlWriter, $prefix, $name, $namespace, $value);
        }
    }

    /**
     * Write an attribute with namespace if used
     *
     * @param  \XMLWriter $xmlWriter XMLWriter instance
     * @param  string     $prefix    Namespace prefix if any
     * @param  string     $name      Attribute name
     * @param  string     $namespace The uri of the namespace
     * @param  string     $value     The attribute content
     */
    protected function writeAttribute($xmlWriter, $prefix, $name, $namespace, $value)
    {
        if (empty($namespace)) {
            $xmlWriter->writeAttribute($name, $value);
        } else {
            $xmlWriter->writeAttributeNS($prefix, $name, $namespace, $value);
        }
    }

    /**
     * Write an element with namespace if used
     *
     * @param  \XMLWriter $xmlWriter XML writer resource
     * @param  string     $prefix    Namespace prefix if any
     * @param  string     $name      Element name
     * @param  string     $namespace The uri of the namespace
     * @param  string     $value     The element content
     */
    protected function writeElement(\XMLWriter $xmlWriter, $prefix, $name, $namespace, $value)
    {
        $xmlWriter->startElementNS($prefix, $name, $namespace);
        if (strpbrk($value, '<>&')) {
            $xmlWriter->writeCData($value);
        } else {
            $xmlWriter->writeRaw($value);
        }
        $xmlWriter->endElement();
    }

    /**
     * Create a new xml writer and start a document
     *
     * @param  string $encoding document encoding
     *
     * @return \XMLWriter the writer resource
     */
    protected function startDocument($encoding)
    {
        $xmlWriter = new \XMLWriter();
        $xmlWriter->openMemory();
        $xmlWriter->startDocument('1.0', $encoding);

        return $xmlWriter;
    }

    /**
     * End the document and return the output
     *
     * @param \XMLWriter $xmlWriter
     *
     * @return \string the writer resource
     */
    protected function finishDocument($xmlWriter)
    {
        $xmlWriter->endDocument();

        return $xmlWriter->outputMemory();
    }

    /**
     * Add an array to the XML
     */
    protected function addXmlArray(\XMLWriter $xmlWriter, Parameter $param, &$value)
    {
        if ($items = $param->getItems()) {
            foreach ($value as $v) {
                $this->addXml($xmlWriter, $items, $v);
            }
        }
    }

    /**
     * Add an object to the XML
     */
    protected function addXmlObject(\XMLWriter $xmlWriter, Parameter $param, &$value)
    {
        $noAttributes = array();
        // add values which have attributes
        foreach ($value as $name => $v) {
            if ($property = $param->getProperty($name)) {
                if ($property->getData('xmlAttribute')) {
                    $this->addXml($xmlWriter, $property, $v);
                } else {
                    $noAttributes[] = array('value' => $v, 'property' => $property);
                }
            }
        }
        // now add values with no attributes
        foreach ($noAttributes as $element) {
            $this->addXml($xmlWriter, $element['property'], $element['value']);
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a body to a request
 *
 * This visitor can use a data parameter of 'expect' to control the Expect header. Set the expect data parameter to
 * false to disable the expect header, or set the value to an integer so that the expect 100-continue header is only
 * added if the Content-Length of the entity body is greater than the value.
 */
class BodyVisitor extends AbstractRequestVisitor
{
    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $value = $param->filter($value);
        $entityBody = EntityBody::factory($value);
        $request->setBody($entityBody);
        $this->addExpectHeader($request, $entityBody, $param->getData('expect_header'));
        // Add the Content-Encoding header if one is set on the EntityBody
        if ($encoding = $entityBody->getContentEncoding()) {
            $request->setHeader('Content-Encoding', $encoding);
        }
    }

    /**
     * Add the appropriate expect header to a request
     *
     * @param EntityEnclosingRequestInterface $request Request to update
     * @param EntityBodyInterface             $body    Entity body of the request
     * @param string|int                      $expect  Expect header setting
     */
    protected function addExpectHeader(EntityEnclosingRequestInterface $request, EntityBodyInterface $body, $expect)
    {
        // Allow the `expect` data parameter to be set to remove the Expect header from the request
        if ($expect === false) {
            $request->removeHeader('Expect');
        } elseif ($expect !== true) {
            // Default to using a MB as the point in which to start using the expect header
            $expect = $expect ?: 1048576;
            // If the expect_header value is numeric then only add if the size is greater than the cutoff
            if (is_numeric($expect) && $body->getSize()) {
                if ($body->getSize() < $expect) {
                    $request->removeHeader('Expect');
                } else {
                    $request->setHeader('Expect', '100-Continue');
                }
            }
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor\Request;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Description\Parameter;

/**
 * Visitor used to apply a parameter to an array that will be serialized as a top level key-value pair in a JSON body
 */
class JsonVisitor extends AbstractRequestVisitor
{
    /** @var bool Whether or not to add a Content-Type header when JSON is found */
    protected $jsonContentType = 'application/json';

    /** @var \SplObjectStorage Data object for persisting JSON data */
    protected $data;

    public function __construct()
    {
        $this->data = new \SplObjectStorage();
    }

    /**
     * Set the Content-Type header to add to the request if JSON is added to the body. This visitor does not add a
     * Content-Type header unless you specify one here.
     *
     * @param string $header Header to set when JSON is added (e.g. application/json)
     *
     * @return self
     */
    public function setContentTypeHeader($header = 'application/json')
    {
        $this->jsonContentType = $header;

        return $this;
    }

    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        if (isset($this->data[$command])) {
            $json = $this->data[$command];
        } else {
            $json = array();
        }
        $json[$param->getWireName()] = $this->prepareValue($value, $param);
        $this->data[$command] = $json;
    }

    public function after(CommandInterface $command, RequestInterface $request)
    {
        if (isset($this->data[$command])) {
            // Don't overwrite the Content-Type if one is set
            if ($this->jsonContentType && !$request->hasHeader('Content-Type')) {
                $request->setHeader('Content-Type', $this->jsonContentType);
            }

            $request->setBody(json_encode($this->data[$command]));
            unset($this->data[$command]);
        }
    }
}
<?php

namespace Guzzle\Service\Command\LocationVisitor;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\LocationVisitor\Request\RequestVisitorInterface;
use Guzzle\Service\Command\LocationVisitor\Response\ResponseVisitorInterface;

/**
 * Flyweight factory used to instantiate request and response visitors
 */
class VisitorFlyweight
{
    /** @var self Singleton instance of self */
    protected static $instance;

    /** @var array Default array of mappings of location names to classes */
    protected static $defaultMappings = array(
        'request.body'          => 'Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor',
        'request.header'        => 'Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor',
        'request.json'          => 'Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor',
        'request.postField'     => 'Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor',
        'request.postFile'      => 'Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor',
        'request.query'         => 'Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor',
        'request.response_body' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor',
        'request.responseBody'  => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor',
        'request.xml'           => 'Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor',
        'response.body'         => 'Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor',
        'response.header'       => 'Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor',
        'response.json'         => 'Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor',
        'response.reasonPhrase' => 'Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor',
        'response.statusCode'   => 'Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor',
        'response.xml'          => 'Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor'
    );

    /** @var array Array of mappings of location names to classes */
    protected $mappings;

    /** @var array Cache of instantiated visitors */
    protected $cache = array();

    /**
     * @return self
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * @param array $mappings Array mapping request.name and response.name to location visitor classes. Leave null to
     *                        use the default values.
     */
    public function __construct(array $mappings = null)
    {
        $this->mappings = $mappings === null ? self::$defaultMappings : $mappings;
    }

    /**
     * Get an instance of a request visitor by location name
     *
     * @param string $visitor Visitor name
     *
     * @return RequestVisitorInterface
     */
    public function getRequestVisitor($visitor)
    {
        return $this->getKey('request.' . $visitor);
    }

    /**
     * Get an instance of a response visitor by location name
     *
     * @param string $visitor Visitor name
     *
     * @return ResponseVisitorInterface
     */
    public function getResponseVisitor($visitor)
    {
        return $this->getKey('response.' . $visitor);
    }

    /**
     * Add a response visitor to the factory by name
     *
     * @param string                  $name    Name of the visitor
     * @param RequestVisitorInterface $visitor Visitor to add
     *
     * @return self
     */
    public function addRequestVisitor($name, RequestVisitorInterface $visitor)
    {
        $this->cache['request.' . $name] = $visitor;

        return $this;
    }

    /**
     * Add a response visitor to the factory by name
     *
     * @param string                   $name    Name of the visitor
     * @param ResponseVisitorInterface $visitor Visitor to add
     *
     * @return self
     */
    public function addResponseVisitor($name, ResponseVisitorInterface $visitor)
    {
        $this->cache['response.' . $name] = $visitor;

        return $this;
    }

    /**
     * Get a visitor by key value name
     *
     * @param string $key Key name to retrieve
     *
     * @return mixed
     * @throws InvalidArgumentException
     */
    private function getKey($key)
    {
        if (!isset($this->cache[$key])) {
            if (!isset($this->mappings[$key])) {
                list($type, $name) = explode('.', $key);
                throw new InvalidArgumentException("No {$type} visitor has been mapped for {$name}");
            }
            $this->cache[$key] = new $this->mappings[$key];
        }

        return $this->cache[$key];
    }
}
<?php

namespace Guzzle\Service\Command;

use Guzzle\Common\Event;

/**
 * Event class emitted with the operation.parse_class event
 */
class CreateResponseClassEvent extends Event
{
    /**
     * Set the result of the object creation
     *
     * @param mixed $result Result value to set
     */
    public function setResult($result)
    {
        $this['result'] = $result;
        $this->stopPropagation();
    }

    /**
     * Get the created object
     *
     * @return mixed
     */
    public function getResult()
    {
        return $this['result'];
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Service\Command\CommandInterface;

/**
 * Factory for creating {@see ResourceIteratorInterface} objects
 */
interface ResourceIteratorFactoryInterface
{
    /**
     * Create a resource iterator
     *
     * @param CommandInterface $command Command to create an iterator for
     * @param array                 $options Iterator options that are exposed as data.
     *
     * @return ResourceIteratorInterface
     */
    public function build(CommandInterface $command, array $options = array());

    /**
     * Check if the factory can create an iterator
     *
     * @param CommandInterface $command Command to create an iterator for
     *
     * @return bool
     */
    public function canBuild(CommandInterface $command);
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\Collection;
use Guzzle\Service\Description\Parameter;

/**
 * Default model created when commands create service description model responses
 */
class Model extends Collection
{
    /** @var Parameter Structure of the model */
    protected $structure;

    /**
     * @param array     $data      Data contained by the model
     * @param Parameter $structure The structure of the model
     */
    public function __construct(array $data = array(), Parameter $structure = null)
    {
        $this->data = $data;
        $this->structure = $structure;
    }

    /**
     * Get the structure of the model
     *
     * @return Parameter
     */
    public function getStructure()
    {
        return $this->structure ?: new Parameter();
    }

    /**
     * Provides debug information about the model object
     *
     * @return string
     */
    public function __toString()
    {
        $output = 'Debug output of ';
        if ($this->structure) {
            $output .= $this->structure->getName() . ' ';
        }
        $output .= 'model';
        $output = str_repeat('=', strlen($output)) . "\n" . $output . "\n" . str_repeat('=', strlen($output)) . "\n\n";
        $output .= "Model data\n-----------\n\n";
        $output .= "This data can be retrieved from the model object using the get() method of the model "
            . "(e.g. \$model->get(\$key)) or accessing the model like an associative array (e.g. \$model['key']).\n\n";
        $lines = array_slice(explode("\n", trim(print_r($this->toArray(), true))), 2, -1);
        $output .=  implode("\n", $lines);

        if ($this->structure) {
            $output .= "\n\nModel structure\n---------------\n\n";
            $output .= "The following JSON document defines how the model was parsed from an HTTP response into the "
                . "associative array structure you see above.\n\n";
            $output .= '  ' . json_encode($this->structure->toArray()) . "\n\n";
        }

        return $output . "\n";
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Service\Command\CommandInterface;

abstract class ResourceIterator extends AbstractHasDispatcher implements ResourceIteratorInterface
{
    /** @var CommandInterface Command used to send requests */
    protected $command;

    /** @var CommandInterface First sent command */
    protected $originalCommand;

    /** @var array Currently loaded resources */
    protected $resources;

    /** @var int Total number of resources that have been retrieved */
    protected $retrievedCount = 0;

    /** @var int Total number of resources that have been iterated */
    protected $iteratedCount = 0;

    /** @var string NextToken/Marker for a subsequent request */
    protected $nextToken = false;

    /** @var int Maximum number of resources to fetch per request */
    protected $pageSize;

    /** @var int Maximum number of resources to retrieve in total */
    protected $limit;

    /** @var int Number of requests sent */
    protected $requestCount = 0;

    /** @var array Initial data passed to the constructor */
    protected $data = array();

    /** @var bool Whether or not the current value is known to be invalid */
    protected $invalid;

    public static function getAllEvents()
    {
        return array(
            // About to issue another command to get more results
            'resource_iterator.before_send',
            // Issued another command to get more results
            'resource_iterator.after_send'
        );
    }

    /**
     * @param CommandInterface $command Initial command used for iteration
     * @param array            $data    Associative array of additional parameters. You may specify any number of custom
     *     options for an iterator. Among these options, you may also specify the following values:
     *     - limit: Attempt to limit the maximum number of resources to this amount
     *     - page_size: Attempt to retrieve this number of resources per request
     */
    public function __construct(CommandInterface $command, array $data = array())
    {
        // Clone the command to keep track of the originating command for rewind
        $this->originalCommand = $command;

        // Parse options from the array of options
        $this->data = $data;
        $this->limit = array_key_exists('limit', $data) ? $data['limit'] : 0;
        $this->pageSize = array_key_exists('page_size', $data) ? $data['page_size'] : false;
    }

    /**
     * Get all of the resources as an array (Warning: this could issue a large number of requests)
     *
     * @return array
     */
    public function toArray()
    {
        return iterator_to_array($this, false);
    }

    public function setLimit($limit)
    {
        $this->limit = $limit;
        $this->resetState();

        return $this;
    }

    public function setPageSize($pageSize)
    {
        $this->pageSize = $pageSize;
        $this->resetState();

        return $this;
    }

    /**
     * Get an option from the iterator
     *
     * @param string $key Key of the option to retrieve
     *
     * @return mixed|null Returns NULL if not set or the value if set
     */
    public function get($key)
    {
        return array_key_exists($key, $this->data) ? $this->data[$key] : null;
    }

    /**
     * Set an option on the iterator
     *
     * @param string $key   Key of the option to set
     * @param mixed  $value Value to set for the option
     *
     * @return ResourceIterator
     */
    public function set($key, $value)
    {
        $this->data[$key] = $value;

        return $this;
    }

    public function current()
    {
        return $this->resources ? current($this->resources) : false;
    }

    public function key()
    {
        return max(0, $this->iteratedCount - 1);
    }

    public function count()
    {
        return $this->retrievedCount;
    }

    /**
     * Get the total number of requests sent
     *
     * @return int
     */
    public function getRequestCount()
    {
        return $this->requestCount;
    }

    /**
     * Rewind the Iterator to the first element and send the original command
     */
    public function rewind()
    {
        // Use the original command
        $this->command = clone $this->originalCommand;
        $this->resetState();
        $this->next();
    }

    public function valid()
    {
        return !$this->invalid && (!$this->resources || $this->current() || $this->nextToken)
            && (!$this->limit || $this->iteratedCount < $this->limit + 1);
    }

    public function next()
    {
        $this->iteratedCount++;

        // Check if a new set of resources needs to be retrieved
        $sendRequest = false;
        if (!$this->resources) {
            $sendRequest = true;
        } else {
            // iterate over the internal array
            $current = next($this->resources);
            $sendRequest = $current === false && $this->nextToken && (!$this->limit || $this->iteratedCount < $this->limit + 1);
        }

        if ($sendRequest) {

            $this->dispatch('resource_iterator.before_send', array(
                'iterator'  => $this,
                'resources' => $this->resources
            ));

            // Get a new command object from the original command
            $this->command = clone $this->originalCommand;
            // Send a request and retrieve the newly loaded resources
            $this->resources = $this->sendRequest();
            $this->requestCount++;

            // If no resources were found, then the last request was not needed
            // and iteration must stop
            if (empty($this->resources)) {
                $this->invalid = true;
            } else {
                // Add to the number of retrieved resources
                $this->retrievedCount += count($this->resources);
                // Ensure that we rewind to the beginning of the array
                reset($this->resources);
            }

            $this->dispatch('resource_iterator.after_send', array(
                'iterator'  => $this,
                'resources' => $this->resources
            ));
        }
    }

    /**
     * Retrieve the NextToken that can be used in other iterators.
     *
     * @return string Returns a NextToken
     */
    public function getNextToken()
    {
        return $this->nextToken;
    }

    /**
     * Returns the value that should be specified for the page size for a request that will maintain any hard limits,
     * but still honor the specified pageSize if the number of items retrieved + pageSize < hard limit
     *
     * @return int Returns the page size of the next request.
     */
    protected function calculatePageSize()
    {
        if ($this->limit && $this->iteratedCount + $this->pageSize > $this->limit) {
            return 1 + ($this->limit - $this->iteratedCount);
        }

        return (int) $this->pageSize;
    }

    /**
     * Reset the internal state of the iterator without triggering a rewind()
     */
    protected function resetState()
    {
        $this->iteratedCount = 0;
        $this->retrievedCount = 0;
        $this->nextToken = false;
        $this->resources = null;
        $this->invalid = false;
    }

    /**
     * Send a request to retrieve the next page of results. Hook for subclasses to implement.
     *
     * @return array Returns the newly loaded resources
     */
    abstract protected function sendRequest();
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Inflection\InflectorInterface;
use Guzzle\Inflection\Inflector;
use Guzzle\Service\Command\CommandInterface;

/**
 * Factory for creating {@see ResourceIteratorInterface} objects using a convention of storing iterator classes under a
 * root namespace using the name of a {@see CommandInterface} object as a convention for determining the name of an
 * iterator class. The command name is converted to CamelCase and Iterator is appended (e.g. abc_foo => AbcFoo).
 */
class ResourceIteratorClassFactory extends AbstractResourceIteratorFactory
{
    /** @var array List of namespaces used to look for classes */
    protected $namespaces;

    /** @var InflectorInterface Inflector used to determine class names */
    protected $inflector;

    /**
     * @param string|array       $namespaces List of namespaces for iterator objects
     * @param InflectorInterface $inflector  Inflector used to resolve class names
     */
    public function __construct($namespaces = array(), InflectorInterface $inflector = null)
    {
        $this->namespaces = (array) $namespaces;
        $this->inflector = $inflector ?: Inflector::getDefault();
    }

    /**
     * Registers a namespace to check for Iterators
     *
     * @param string $namespace Namespace which contains Iterator classes
     *
     * @return self
     */
    public function registerNamespace($namespace)
    {
        array_unshift($this->namespaces, $namespace);

        return $this;
    }

    protected function getClassName(CommandInterface $command)
    {
        $iteratorName = $this->inflector->camel($command->getName()) . 'Iterator';

        // Determine the name of the class to load
        foreach ($this->namespaces as $namespace) {
            $potentialClassName = $namespace . '\\' . $iteratorName;
            if (class_exists($potentialClassName)) {
                return $potentialClassName;
            }
        }

        return false;
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\CommandInterface;

/**
 * Factory that utilizes multiple factories for creating iterators
 */
class CompositeResourceIteratorFactory implements ResourceIteratorFactoryInterface
{
    /** @var array Array of factories */
    protected $factories;

    /** @param array $factories Array of factories used to instantiate iterators */
    public function __construct(array $factories)
    {
        $this->factories = $factories;
    }

    public function build(CommandInterface $command, array $options = array())
    {
        if (!($factory = $this->getFactory($command))) {
            throw new InvalidArgumentException('Iterator was not found for ' . $command->getName());
        }

        return $factory->build($command, $options);
    }

    public function canBuild(CommandInterface $command)
    {
        return $this->getFactory($command) !== false;
    }

    /**
     * Add a factory to the composite factory
     *
     * @param ResourceIteratorFactoryInterface $factory Factory to add
     *
     * @return self
     */
    public function addFactory(ResourceIteratorFactoryInterface $factory)
    {
        $this->factories[] = $factory;

        return $this;
    }

    /**
     * Get the factory that matches the command object
     *
     * @param CommandInterface $command Command retrieving the iterator for
     *
     * @return ResourceIteratorFactoryInterface|bool
     */
    protected function getFactory(CommandInterface $command)
    {
        foreach ($this->factories as $factory) {
            if ($factory->canBuild($command)) {
                return $factory;
            }
        }

        return false;
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Batch\BatchBuilder;
use Guzzle\Batch\BatchSizeDivisor;
use Guzzle\Batch\BatchClosureTransfer;
use Guzzle\Common\Version;

/**
 * Apply a callback to the contents of a {@see ResourceIteratorInterface}
 * @deprecated Will be removed in a future version and is no longer maintained. Use the Batch\ abstractions instead.
 * @codeCoverageIgnore
 */
class ResourceIteratorApplyBatched extends AbstractHasDispatcher
{
    /** @var callable|array */
    protected $callback;

    /** @var ResourceIteratorInterface */
    protected $iterator;

    /** @var integer Total number of sent batches */
    protected $batches = 0;

    /** @var int Total number of iterated resources */
    protected $iterated = 0;

    public static function getAllEvents()
    {
        return array(
            // About to send a batch of requests to the callback
            'iterator_batch.before_batch',
            // Finished sending a batch of requests to the callback
            'iterator_batch.after_batch',
            // Created the batch object
            'iterator_batch.created_batch'
        );
    }

    /**
     * @param ResourceIteratorInterface $iterator Resource iterator to apply a callback to
     * @param array|callable            $callback Callback method accepting the resource iterator
     *                                            and an array of the iterator's current resources
     */
    public function __construct(ResourceIteratorInterface $iterator, $callback)
    {
        $this->iterator = $iterator;
        $this->callback = $callback;
        Version::warn(__CLASS__ . ' is deprecated');
    }

    /**
     * Apply the callback to the contents of the resource iterator
     *
     * @param int $perBatch The number of records to group per batch transfer
     *
     * @return int Returns the number of iterated resources
     */
    public function apply($perBatch = 50)
    {
        $this->iterated = $this->batches = $batches = 0;
        $that = $this;
        $it = $this->iterator;
        $callback = $this->callback;

        $batch = BatchBuilder::factory()
            ->createBatchesWith(new BatchSizeDivisor($perBatch))
            ->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) {
                $batches++;
                $that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch));
                call_user_func_array($callback, array($it, $batch));
                $that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch));
            }))
            ->autoFlushAt($perBatch)
            ->build();

        $this->dispatch('iterator_batch.created_batch', array('batch' => $batch));

        foreach ($this->iterator as $resource) {
            $this->iterated++;
            $batch->add($resource);
        }

        $batch->flush();
        $this->batches = $batches;

        return $this->iterated;
    }

    /**
     * Get the total number of batches sent
     *
     * @return int
     */
    public function getBatchCount()
    {
        return $this->batches;
    }

    /**
     * Get the total number of iterated resources
     *
     * @return int
     */
    public function getIteratedCount()
    {
        return $this->iterated;
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\CommandInterface;

/**
 * Abstract resource iterator factory implementation
 */
abstract class AbstractResourceIteratorFactory implements ResourceIteratorFactoryInterface
{
    public function build(CommandInterface $command, array $options = array())
    {
        if (!$this->canBuild($command)) {
            throw new InvalidArgumentException('Iterator was not found for ' . $command->getName());
        }

        $className = $this->getClassName($command);

        return new $className($command, $options);
    }

    public function canBuild(CommandInterface $command)
    {
        return (bool) $this->getClassName($command);
    }

    /**
     * Get the name of the class to instantiate for the command
     *
     * @param CommandInterface $command Command that is associated with the iterator
     *
     * @return string
     */
    abstract protected function getClassName(CommandInterface $command);
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Service\Command\CommandInterface;

/**
 * Resource iterator factory used when explicitly mapping strings to iterator classes
 */
class MapResourceIteratorFactory extends AbstractResourceIteratorFactory
{
    /** @var array Associative array mapping iterator names to class names */
    protected $map;

    /** @param array $map Associative array mapping iterator names to class names */
    public function __construct(array $map)
    {
        $this->map = $map;
    }

    public function getClassName(CommandInterface $command)
    {
        $className = $command->getName();

        if (isset($this->map[$className])) {
            return $this->map[$className];
        } elseif (isset($this->map['*'])) {
            // If a wildcard was added, then always use that
            return $this->map['*'];
        }

        return null;
    }
}
<?php

namespace Guzzle\Service\Resource;

use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\ToArrayInterface;

/**
 * Iterates over a paginated resource using subsequent requests in order to retrieve the entire matching result set
 */
interface ResourceIteratorInterface extends ToArrayInterface, HasDispatcherInterface, \Iterator, \Countable
{
    /**
     * Retrieve the NextToken that can be used in other iterators.
     *
     * @return string Returns a NextToken
     */
    public function getNextToken();

    /**
     * Attempt to limit the total number of resources returned by the iterator.
     *
     * You may still receive more items than you specify. Set to 0 to specify no limit.
     *
     * @param int $limit Limit amount
     *
     * @return ResourceIteratorInterface
     */
    public function setLimit($limit);

    /**
     * Attempt to limit the total number of resources retrieved per request by  the iterator.
     *
     * The iterator may return more than you specify in the page size argument depending on the service and underlying
     * command implementation.  Set to 0 to specify no page size limitation.
     *
     * @param int $pageSize Limit amount
     *
     * @return ResourceIteratorInterface
     */
    public function setPageSize($pageSize);

    /**
     * Get a data option from the iterator
     *
     * @param string $key Key of the option to retrieve
     *
     * @return mixed|null Returns NULL if not set or the value if set
     */
    public function get($key);

    /**
     * Set a data option on the iterator
     *
     * @param string $key   Key of the option to set
     * @param mixed  $value Value to set for the option
     *
     * @return ResourceIteratorInterface
     */
    public function set($key, $value);
}
<?php

namespace Guzzle\Service\Builder;

use Guzzle\Service\Exception\ServiceNotFoundException;

/**
 * Service builder used to store and build clients or arbitrary data. Client configuration data can be supplied to tell
 * the service builder how to create and cache {@see \Guzzle\Service\ClientInterface} objects. Arbitrary data can be
 * supplied and accessed from a service builder. Arbitrary data and other clients can be referenced by name in client
 * configuration arrays to make them input for building other clients (e.g. "{key}").
 */
interface ServiceBuilderInterface
{
    /**
     * Get a ClientInterface object or arbitrary data from the service builder
     *
     * @param string     $name      Name of the registered service or data to retrieve
     * @param bool|array $throwAway Only pertains to retrieving client objects built using a configuration array.
     *                              Set to TRUE to not store the client for later retrieval from the ServiceBuilder.
     *                              If an array is specified, that data will overwrite the configured params of the
     *                              client if the client implements {@see \Guzzle\Common\FromConfigInterface} and will
     *                              not store the client for later retrieval.
     *
     * @return \Guzzle\Service\ClientInterface|mixed
     * @throws ServiceNotFoundException when a client or data cannot be found by the given name
     */
    public function get($name, $throwAway = false);

    /**
     * Register a service or arbitrary data by name with the service builder
     *
     * @param string $key     Name of the client or data to register
     * @param mixed  $service Client configuration array or arbitrary data to register. The client configuration array
     *                        must include a 'class' (string) and 'params' (array) key.
     *
     * @return ServiceBuilderInterface
     */
    public function set($key, $service);
}
<?php

namespace Guzzle\Service\Builder;

use Guzzle\Service\AbstractConfigLoader;
use Guzzle\Service\Exception\ServiceNotFoundException;

/**
 * Service builder config loader
 */
class ServiceBuilderLoader extends AbstractConfigLoader
{
    protected function build($config, array $options)
    {
        // A service builder class can be specified in the class field
        $class = !empty($config['class']) ? $config['class'] : __NAMESPACE__ . '\\ServiceBuilder';

        // Account for old style configs that do not have a services array
        $services = isset($config['services']) ? $config['services'] : $config;

        // Validate the configuration and handle extensions
        foreach ($services as $name => &$service) {

            $service['params'] = isset($service['params']) ? $service['params'] : array();

            // Check if this client builder extends another client
            if (!empty($service['extends'])) {

                // Make sure that the service it's extending has been defined
                if (!isset($services[$service['extends']])) {
                    throw new ServiceNotFoundException(
                        "{$name} is trying to extend a non-existent service: {$service['extends']}"
                    );
                }

                $extended = &$services[$service['extends']];

                // Use the correct class attribute
                if (empty($service['class'])) {
                    $service['class'] = isset($extended['class']) ? $extended['class'] : '';
                }
                if ($extendsParams = isset($extended['params']) ? $extended['params'] : false) {
                    $service['params'] = $service['params'] + $extendsParams;
                }
            }

            // Overwrite default values with global parameter values
            if (!empty($options)) {
                $service['params'] = $options + $service['params'];
            }

            $service['class'] = isset($service['class']) ? $service['class'] : '';
        }

        return new $class($services);
    }

    protected function mergeData(array $a, array $b)
    {
        $result = $b + $a;

        // Merge services using a recursive union of arrays
        if (isset($a['services']) && $b['services']) {

            // Get a union of the services of the two arrays
            $result['services'] = $b['services'] + $a['services'];

            // Merge each service in using a union of the two arrays
            foreach ($result['services'] as $name => &$service) {

                // By default, services completely override a previously defined service unless it extends itself
                if (isset($a['services'][$name]['extends'])
                    && isset($b['services'][$name]['extends'])
                    && $b['services'][$name]['extends'] == $name
                ) {
                    $service += $a['services'][$name];
                    // Use the `extends` attribute of the parent
                    $service['extends'] = $a['services'][$name]['extends'];
                    // Merge parameters using a union if both have parameters
                    if (isset($a['services'][$name]['params'])) {
                        $service['params'] += $a['services'][$name]['params'];
                    }
                }
            }
        }

        return $result;
    }
}
<?php

namespace Guzzle\Service\Builder;

use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Service\ClientInterface;
use Guzzle\Service\Exception\ServiceBuilderException;
use Guzzle\Service\Exception\ServiceNotFoundException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * {@inheritdoc}
 *
 * Clients and data can be set, retrieved, and removed by accessing the service builder like an associative array.
 */
class ServiceBuilder extends AbstractHasDispatcher implements ServiceBuilderInterface, \ArrayAccess, \Serializable
{
    /** @var array Service builder configuration data */
    protected $builderConfig = array();

    /** @var array Instantiated client objects */
    protected $clients = array();

    /** @var ServiceBuilderLoader Cached instance of the service builder loader */
    protected static $cachedFactory;

    /** @var array Plugins to attach to each client created by the service builder */
    protected $plugins = array();

    /**
     * Create a new ServiceBuilder using configuration data sourced from an
     * array, .js|.json or .php file.
     *
     * @param array|string $config           The full path to an .json|.js or .php file, or an associative array
     * @param array        $globalParameters Array of global parameters to pass to every service as it is instantiated.
     *
     * @return ServiceBuilderInterface
     * @throws ServiceBuilderException if a file cannot be opened
     * @throws ServiceNotFoundException when trying to extend a missing client
     */
    public static function factory($config = null, array $globalParameters = array())
    {
        // @codeCoverageIgnoreStart
        if (!static::$cachedFactory) {
            static::$cachedFactory = new ServiceBuilderLoader();
        }
        // @codeCoverageIgnoreEnd

        return self::$cachedFactory->load($config, $globalParameters);
    }

    /**
     * @param array $serviceBuilderConfig Service configuration settings:
     *     - name: Name of the service
     *     - class: Client class to instantiate using a factory method
     *     - params: array of key value pair configuration settings for the builder
     */
    public function __construct(array $serviceBuilderConfig = array())
    {
        $this->builderConfig = $serviceBuilderConfig;
    }

    public static function getAllEvents()
    {
        return array('service_builder.create_client');
    }

    public function unserialize($serialized)
    {
        $this->builderConfig = json_decode($serialized, true);
    }

    public function serialize()
    {
        return json_encode($this->builderConfig);
    }

    /**
     * Attach a plugin to every client created by the builder
     *
     * @param EventSubscriberInterface $plugin Plugin to attach to each client
     *
     * @return self
     */
    public function addGlobalPlugin(EventSubscriberInterface $plugin)
    {
        $this->plugins[] = $plugin;

        return $this;
    }

    /**
     * Get data from the service builder without triggering the building of a service
     *
     * @param string $name Name of the service to retrieve
     *
     * @return array|null
     */
    public function getData($name)
    {
        return isset($this->builderConfig[$name]) ? $this->builderConfig[$name] : null;
    }

    public function get($name, $throwAway = false)
    {
        if (!isset($this->builderConfig[$name])) {

            // Check to see if arbitrary data is being referenced
            if (isset($this->clients[$name])) {
                return $this->clients[$name];
            }

            // Check aliases and return a match if found
            foreach ($this->builderConfig as $actualName => $config) {
                if (isset($config['alias']) && $config['alias'] == $name) {
                    return $this->get($actualName, $throwAway);
                }
            }
            throw new ServiceNotFoundException('No service is registered as ' . $name);
        }

        if (!$throwAway && isset($this->clients[$name])) {
            return $this->clients[$name];
        }

        $builder =& $this->builderConfig[$name];

        // Convert references to the actual client
        foreach ($builder['params'] as &$v) {
            if (is_string($v) && substr($v, 0, 1) == '{' && substr($v, -1) == '}') {
                $v = $this->get(trim($v, '{} '));
            }
        }

        // Get the configured parameters and merge in any parameters provided for throw-away clients
        $config = $builder['params'];
        if (is_array($throwAway)) {
            $config = $throwAway + $config;
        }

        $client = $builder['class']::factory($config);

        if (!$throwAway) {
            $this->clients[$name] = $client;
        }

        if ($client instanceof ClientInterface) {
            foreach ($this->plugins as $plugin) {
                $client->addSubscriber($plugin);
            }
            // Dispatch an event letting listeners know a client was created
            $this->dispatch('service_builder.create_client', array('client' => $client));
        }

        return $client;
    }

    public function set($key, $service)
    {
        if (is_array($service) && isset($service['class']) && isset($service['params'])) {
            $this->builderConfig[$key] = $service;
        } else {
            $this->clients[$key] = $service;
        }

        return $this;
    }

    public function offsetSet($offset, $value)
    {
        $this->set($offset, $value);
    }

    public function offsetUnset($offset)
    {
        unset($this->builderConfig[$offset]);
        unset($this->clients[$offset]);
    }

    public function offsetExists($offset)
    {
        return isset($this->builderConfig[$offset]) || isset($this->clients[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->get($offset);
    }
}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

class ResponseClassException extends RuntimeException
{
}
<?php

namespace Guzzle\Service\Exception;

class ServiceNotFoundException extends ServiceBuilderException {}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

class CommandException extends RuntimeException {}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

class ValidationException extends RuntimeException
{
    protected $errors = array();

    /**
     * Set the validation error messages
     *
     * @param array $errors Array of validation errors
     */
    public function setErrors(array $errors)
    {
        $this->errors = $errors;
    }

    /**
     * Get any validation errors
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }
}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

class ServiceBuilderException extends RuntimeException {}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

class DescriptionBuilderException extends RuntimeException {}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Service\Command\CommandInterface;

/**
 * Exception thrown when transferring commands in parallel
 */
class CommandTransferException extends MultiTransferException
{
    protected $successfulCommands = array();
    protected $failedCommands = array();

    /**
     * Creates a new CommandTransferException from a MultiTransferException
     *
     * @param MultiTransferException $e Exception to base a new exception on
     *
     * @return self
     */
    public static function fromMultiTransferException(MultiTransferException $e)
    {
        $ce = new self($e->getMessage(), $e->getCode(), $e->getPrevious());
        $ce->setSuccessfulRequests($e->getSuccessfulRequests());

        $alreadyAddedExceptions = array();
        foreach ($e->getFailedRequests() as $request) {
            if ($re = $e->getExceptionForFailedRequest($request)) {
                $alreadyAddedExceptions[] = $re;
                $ce->addFailedRequestWithException($request, $re);
            } else {
                $ce->addFailedRequest($request);
            }
        }

        // Add any exceptions that did not map to a request
        if (count($alreadyAddedExceptions) < count($e)) {
            foreach ($e as $ex) {
                if (!in_array($ex, $alreadyAddedExceptions)) {
                    $ce->add($ex);
                }
            }
        }

        return $ce;
    }

    /**
     * Get all of the commands in the transfer
     *
     * @return array
     */
    public function getAllCommands()
    {
        return array_merge($this->successfulCommands, $this->failedCommands);
    }

    /**
     * Add to the array of successful commands
     *
     * @param CommandInterface $command Successful command
     *
     * @return self
     */
    public function addSuccessfulCommand(CommandInterface $command)
    {
        $this->successfulCommands[] = $command;

        return $this;
    }

    /**
     * Add to the array of failed commands
     *
     * @param CommandInterface $command Failed command
     *
     * @return self
     */
    public function addFailedCommand(CommandInterface $command)
    {
        $this->failedCommands[] = $command;

        return $this;
    }

    /**
     * Get an array of successful commands
     *
     * @return array
     */
    public function getSuccessfulCommands()
    {
        return $this->successfulCommands;
    }

    /**
     * Get an array of failed commands
     *
     * @return array
     */
    public function getFailedCommands()
    {
        return $this->failedCommands;
    }

    /**
     * Get the Exception that caused the given $command to fail
     *
     * @param CommandInterface $command Failed command
     *
     * @return \Exception|null
     */
    public function getExceptionForFailedCommand(CommandInterface $command)
    {
        return $this->getExceptionForFailedRequest($command->getRequest());
    }
}
<?php

namespace Guzzle\Service\Exception;

use Guzzle\Common\Exception\RuntimeException;

/**
 * Command transfer exception when commands do not all use the same client
 */
class InconsistentClientTransferException extends RuntimeException
{
    /**
     * @var array Commands with an invalid client
     */
    private $invalidCommands = array();

    /**
     * @param array $commands Invalid commands
     */
    public function __construct(array $commands)
    {
        $this->invalidCommands = $commands;
        parent::__construct(
            'Encountered commands in a batch transfer that use inconsistent clients. The batching ' .
            'strategy you use with a command transfer must divide command batches by client.'
        );
    }

    /**
     * Get the invalid commands
     *
     * @return array
     */
    public function getCommands()
    {
        return $this->invalidCommands;
    }
}
{
    "name": "guzzle/service",
    "description": "Guzzle service component for abstracting RESTful web services",
    "homepage": "http://guzzlephp.org/",
    "keywords": ["web service", "webservice", "REST", "guzzle"],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Dowling",
            "email": "mtdowling@gmail.com",
            "homepage": "https://github.com/mtdowling"
        }
    ],
    "require": {
        "php": ">=5.3.2",
        "guzzle/cache": "self.version",
        "guzzle/http": "self.version",
        "guzzle/inflection": "self.version"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Service": "" }
    },
    "target-dir": "Guzzle/Service",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
<?php

namespace Guzzle\Service;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;

/**
 * Abstract config loader
 */
abstract class AbstractConfigLoader implements ConfigLoaderInterface
{
    /** @var array Array of aliases for actual filenames */
    protected $aliases = array();

    /** @var array Hash of previously loaded filenames */
    protected $loadedFiles = array();

    /** @var array JSON error code mappings */
    protected static $jsonErrors = array(
        JSON_ERROR_NONE => 'JSON_ERROR_NONE - No errors',
        JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
        JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
        JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
        JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
        JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
    );

    public function load($config, array $options = array())
    {
        // Reset the array of loaded files because this is a new config
        $this->loadedFiles = array();

        if (is_string($config)) {
            $config = $this->loadFile($config);
        } elseif (!is_array($config)) {
            throw new InvalidArgumentException('Unknown type passed to configuration loader: ' . gettype($config));
        } else {
            $this->mergeIncludes($config);
        }

        return $this->build($config, $options);
    }

    /**
     * Add an include alias to the loader
     *
     * @param string $filename Filename to alias (e.g. _foo)
     * @param string $alias    Actual file to use (e.g. /path/to/foo.json)
     *
     * @return self
     */
    public function addAlias($filename, $alias)
    {
        $this->aliases[$filename] = $alias;

        return $this;
    }

    /**
     * Remove an alias from the loader
     *
     * @param string $alias Alias to remove
     *
     * @return self
     */
    public function removeAlias($alias)
    {
        unset($this->aliases[$alias]);

        return $this;
    }

    /**
     * Perform the parsing of a config file and create the end result
     *
     * @param array $config  Configuration data
     * @param array $options Options to use when building
     *
     * @return mixed
     */
    protected abstract function build($config, array $options);

    /**
     * Load a configuration file (can load JSON or PHP files that return an array when included)
     *
     * @param string $filename File to load
     *
     * @return array
     * @throws InvalidArgumentException
     * @throws RuntimeException when the JSON cannot be parsed
     */
    protected function loadFile($filename)
    {
        if (isset($this->aliases[$filename])) {
            $filename = $this->aliases[$filename];
        }

        switch (pathinfo($filename, PATHINFO_EXTENSION)) {
            case 'js':
            case 'json':
                $level = error_reporting(0);
                $json = file_get_contents($filename);
                error_reporting($level);

                if ($json === false) {
                    $err = error_get_last();
                    throw new InvalidArgumentException("Unable to open {$filename}: " . $err['message']);
                }

                $config = json_decode($json, true);
                // Throw an exception if there was an error loading the file
                if ($error = json_last_error()) {
                    $message = isset(self::$jsonErrors[$error]) ? self::$jsonErrors[$error] : 'Unknown error';
                    throw new RuntimeException("Error loading JSON data from {$filename}: ({$error}) - {$message}");
                }
                break;
            case 'php':
                if (!is_readable($filename)) {
                    throw new InvalidArgumentException("Unable to open {$filename} for reading");
                }
                $config = require $filename;
                if (!is_array($config)) {
                    throw new InvalidArgumentException('PHP files must return an array of configuration data');
                }
                break;
            default:
                throw new InvalidArgumentException('Unknown file extension: ' . $filename);
        }

        // Keep track of this file being loaded to prevent infinite recursion
        $this->loadedFiles[$filename] = true;

        // Merge include files into the configuration array
        $this->mergeIncludes($config, dirname($filename));

        return $config;
    }

    /**
     * Merges in all include files
     *
     * @param array  $config   Config data that contains includes
     * @param string $basePath Base path to use when a relative path is encountered
     *
     * @return array Returns the merged and included data
     */
    protected function mergeIncludes(&$config, $basePath = null)
    {
        if (!empty($config['includes'])) {
            foreach ($config['includes'] as &$path) {
                // Account for relative paths
                if ($path[0] != DIRECTORY_SEPARATOR && !isset($this->aliases[$path]) && $basePath) {
                    $path = "{$basePath}/{$path}";
                }
                // Don't load the same files more than once
                if (!isset($this->loadedFiles[$path])) {
                    $this->loadedFiles[$path] = true;
                    $config = $this->mergeData($this->loadFile($path), $config);
                }
            }
        }
    }

    /**
     * Default implementation for merging two arrays of data (uses array_merge_recursive)
     *
     * @param array $a Original data
     * @param array $b Data to merge into the original and overwrite existing values
     *
     * @return array
     */
    protected function mergeData(array $a, array $b)
    {
        return array_merge_recursive($a, $b);
    }
}
<?php

namespace Guzzle\Service;

use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\BadMethodCallException;
use Guzzle\Common\Version;
use Guzzle\Inflection\InflectorInterface;
use Guzzle\Inflection\Inflector;
use Guzzle\Http\Client as HttpClient;
use Guzzle\Http\Exception\MultiTransferException;
use Guzzle\Service\Exception\CommandTransferException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Command\Factory\CompositeFactory;
use Guzzle\Service\Command\Factory\FactoryInterface as CommandFactoryInterface;
use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Service\Resource\ResourceIteratorFactoryInterface;
use Guzzle\Service\Description\ServiceDescriptionInterface;

/**
 * Client object for executing commands on a web service.
 */
class Client extends HttpClient implements ClientInterface
{
    const COMMAND_PARAMS = 'command.params';

    /** @var ServiceDescriptionInterface Description of the service and possible commands */
    protected $serviceDescription;

    /** @var CommandFactoryInterface */
    protected $commandFactory;

    /** @var ResourceIteratorFactoryInterface */
    protected $resourceIteratorFactory;

    /** @var InflectorInterface Inflector associated with the service/client */
    protected $inflector;

    /**
     * Basic factory method to create a new client. Extend this method in subclasses to build more complex clients.
     *
     * @param array|Collection $config Configuration data
     *
     * @return Client
     */
    public static function factory($config = array())
    {
        return new static(isset($config['base_url']) ? $config['base_url'] : null, $config);
    }

    public static function getAllEvents()
    {
        return array_merge(HttpClient::getAllEvents(), array(
            'client.command.create',
            'command.before_prepare',
            'command.after_prepare',
            'command.before_send',
            'command.after_send',
            'command.parse_response'
        ));
    }

    /**
     * Magic method used to retrieve a command
     *
     * @param string $method Name of the command object to instantiate
     * @param array  $args   Arguments to pass to the command
     *
     * @return mixed Returns the result of the command
     * @throws BadMethodCallException when a command is not found
     */
    public function __call($method, $args)
    {
        return $this->getCommand($method, isset($args[0]) ? $args[0] : array())->getResult();
    }

    public function getCommand($name, array $args = array())
    {
        // Add global client options to the command
        if ($options = $this->getConfig(self::COMMAND_PARAMS)) {
            $args += $options;
        }

        if (!($command = $this->getCommandFactory()->factory($name, $args))) {
            throw new InvalidArgumentException("Command was not found matching {$name}");
        }

        $command->setClient($this);
        $this->dispatch('client.command.create', array('client' => $this, 'command' => $command));

        return $command;
    }

    /**
     * Set the command factory used to create commands by name
     *
     * @param CommandFactoryInterface $factory Command factory
     *
     * @return self
     */
    public function setCommandFactory(CommandFactoryInterface $factory)
    {
        $this->commandFactory = $factory;

        return $this;
    }

    /**
     * Set the resource iterator factory associated with the client
     *
     * @param ResourceIteratorFactoryInterface $factory Resource iterator factory
     *
     * @return self
     */
    public function setResourceIteratorFactory(ResourceIteratorFactoryInterface $factory)
    {
        $this->resourceIteratorFactory = $factory;

        return $this;
    }

    public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array())
    {
        if (!($command instanceof CommandInterface)) {
            $command = $this->getCommand($command, $commandOptions ?: array());
        }

        return $this->getResourceIteratorFactory()->build($command, $iteratorOptions);
    }

    public function execute($command)
    {
        if ($command instanceof CommandInterface) {
            $this->send($this->prepareCommand($command));
            $this->dispatch('command.after_send', array('command' => $command));
            return $command->getResult();
        } elseif (is_array($command) || $command instanceof \Traversable) {
            return $this->executeMultiple($command);
        } else {
            throw new InvalidArgumentException('Command must be a command or array of commands');
        }
    }

    public function setDescription(ServiceDescriptionInterface $service)
    {
        $this->serviceDescription = $service;

        if ($this->getCommandFactory() && $this->getCommandFactory() instanceof CompositeFactory) {
            $this->commandFactory->add(new Command\Factory\ServiceDescriptionFactory($service));
        }

        // If a baseUrl was set on the description, then update the client
        if ($baseUrl = $service->getBaseUrl()) {
            $this->setBaseUrl($baseUrl);
        }

        return $this;
    }

    public function getDescription()
    {
        return $this->serviceDescription;
    }

    /**
     * Set the inflector used with the client
     *
     * @param InflectorInterface $inflector Inflection object
     *
     * @return self
     */
    public function setInflector(InflectorInterface $inflector)
    {
        $this->inflector = $inflector;

        return $this;
    }

    /**
     * Get the inflector used with the client
     *
     * @return self
     */
    public function getInflector()
    {
        if (!$this->inflector) {
            $this->inflector = Inflector::getDefault();
        }

        return $this->inflector;
    }

    /**
     * Prepare a command for sending and get the RequestInterface object created by the command
     *
     * @param CommandInterface $command Command to prepare
     *
     * @return RequestInterface
     */
    protected function prepareCommand(CommandInterface $command)
    {
        // Set the client and prepare the command
        $request = $command->setClient($this)->prepare();
        // Set the state to new if the command was previously executed
        $request->setState(RequestInterface::STATE_NEW);
        $this->dispatch('command.before_send', array('command' => $command));

        return $request;
    }

    /**
     * Execute multiple commands in parallel
     *
     * @param array|Traversable $commands Array of CommandInterface objects to execute
     *
     * @return array Returns an array of the executed commands
     * @throws Exception\CommandTransferException
     */
    protected function executeMultiple($commands)
    {
        $requests = array();
        $commandRequests = new \SplObjectStorage();

        foreach ($commands as $command) {
            $request = $this->prepareCommand($command);
            $commandRequests[$request] = $command;
            $requests[] = $request;
        }

        try {
            $this->send($requests);
            foreach ($commands as $command) {
                $this->dispatch('command.after_send', array('command' => $command));
            }
            return $commands;
        } catch (MultiTransferException $failureException) {
            // Throw a CommandTransferException using the successful and failed commands
            $e = CommandTransferException::fromMultiTransferException($failureException);

            // Remove failed requests from the successful requests array and add to the failures array
            foreach ($failureException->getFailedRequests() as $request) {
                if (isset($commandRequests[$request])) {
                    $e->addFailedCommand($commandRequests[$request]);
                    unset($commandRequests[$request]);
                }
            }

            // Always emit the command after_send events for successful commands
            foreach ($commandRequests as $success) {
                $e->addSuccessfulCommand($commandRequests[$success]);
                $this->dispatch('command.after_send', array('command' => $commandRequests[$success]));
            }

            throw $e;
        }
    }

    protected function getResourceIteratorFactory()
    {
        if (!$this->resourceIteratorFactory) {
            // Build the default resource iterator factory if one is not set
            $clientClass = get_class($this);
            $prefix = substr($clientClass, 0, strrpos($clientClass, '\\'));
            $this->resourceIteratorFactory = new ResourceIteratorClassFactory(array(
                "{$prefix}\\Iterator",
                "{$prefix}\\Model"
            ));
        }

        return $this->resourceIteratorFactory;
    }

    /**
     * Get the command factory associated with the client
     *
     * @return CommandFactoryInterface
     */
    protected function getCommandFactory()
    {
        if (!$this->commandFactory) {
            $this->commandFactory = CompositeFactory::getDefaultChain($this);
        }

        return $this->commandFactory;
    }

    /**
     * @deprecated
     * @codeCoverageIgnore
     */
    public function enableMagicMethods($isEnabled)
    {
        Version::warn(__METHOD__ . ' is deprecated');
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce;

class Bce
{
    const SDK_VERSION = '0.9.19';
    const DEFAULT_SERVICE_DOMAIN = 'baidubce.com';
    const URL_PREFIX = '/v1';
    const DEFAULT_ENCODING = 'UTF-8';

    /**
     * @return mixed The default bce configuration.
     */
    public static function getDefaultConfig()
    {
        return array(
            BceClientConfigOptions::PROTOCOL => 'http',
            BceClientConfigOptions::REGION => 'bj',
            BceClientConfigOptions::CONNECTION_TIMEOUT_IN_MILLIS => 50 * 1000,
            BceClientConfigOptions::SOCKET_TIMEOUT_IN_MILLIS => 0, //wait infinitely
            BceClientConfigOptions::SEND_BUF_SIZE => 1024 * 1024,
            BceClientConfigOptions::RECV_BUF_SIZE => 10 * 1024 * 1024,
        );
    }
}



/* vim: set ts=4 sw=4 sts=4 tw=120: */
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace baidubce\util;

class MimeTypes
{
    static $map;
    /**
     * Guess mime-type from file name extension. Return default mime-type if guess failed.
     *
     * @param string $fileName
     *
     * @return string
     */
    static function guessMimeType($fileName)
    {
        self::$map = include(__DIR__ . "/mime.types.php");
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        return isset(self::$map[$ext]) ? self::$map[$ext] : 'application/octet-stream';
    }
} 
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace baidubce\util;

class HashUtils
{
    /**
     * @param resource $fp The opened file
     * @param number $offset The offset.
     * @param number $length Maximum number of characters to copy from
     *   $fp into the hashing context.
     * @param boolean $raw_output When TRUE, returns the digest in raw
     *   binary format with a length of 16
     *
     * @return string
     */
    public static function md5FromStream(
        $fp,
        $offset = 0,
        $length = -1
    ) {
        $pos = ftell($fp);
        $ctx = hash_init('md5');
        fseek($fp, $offset, SEEK_SET);
        hash_update_stream($ctx, $fp, $length);
        if ($pos !== false) {
            fseek($fp, $pos, SEEK_SET);
        }
        return hash_final($ctx, true);
    }
} 
<?php
// Auto generated by GenerateMimeTypes.php, DO NOT EDIT IT.
return array(
    "ez" => "application/andrew-inset",
    "aw" => "application/applixware",
    "atom" => "application/atom+xml",
    "atomcat" => "application/atomcat+xml",
    "atomsvc" => "application/atomsvc+xml",
    "ccxml" => "application/ccxml+xml",
    "cdmia" => "application/cdmi-capability",
    "cdmic" => "application/cdmi-container",
    "cdmid" => "application/cdmi-domain",
    "cdmio" => "application/cdmi-object",
    "cdmiq" => "application/cdmi-queue",
    "cu" => "application/cu-seeme",
    "davmount" => "application/davmount+xml",
    "dbk" => "application/docbook+xml",
    "dssc" => "application/dssc+der",
    "xdssc" => "application/dssc+xml",
    "ecma" => "application/ecmascript",
    "emma" => "application/emma+xml",
    "epub" => "application/epub+zip",
    "exi" => "application/exi",
    "pfr" => "application/font-tdpfr",
    "gml" => "application/gml+xml",
    "gpx" => "application/gpx+xml",
    "gxf" => "application/gxf",
    "stk" => "application/hyperstudio",
    "ink" => "application/inkml+xml",
    "inkml" => "application/inkml+xml",
    "ipfix" => "application/ipfix",
    "jar" => "application/java-archive",
    "ser" => "application/java-serialized-object",
    "class" => "application/java-vm",
    "js" => "application/javascript",
    "json" => "application/json",
    "jsonml" => "application/jsonml+json",
    "lostxml" => "application/lost+xml",
    "hqx" => "application/mac-binhex40",
    "cpt" => "application/mac-compactpro",
    "mads" => "application/mads+xml",
    "mrc" => "application/marc",
    "mrcx" => "application/marcxml+xml",
    "ma" => "application/mathematica",
    "nb" => "application/mathematica",
    "mb" => "application/mathematica",
    "mathml" => "application/mathml+xml",
    "mbox" => "application/mbox",
    "mscml" => "application/mediaservercontrol+xml",
    "metalink" => "application/metalink+xml",
    "meta4" => "application/metalink4+xml",
    "mets" => "application/mets+xml",
    "mods" => "application/mods+xml",
    "m21" => "application/mp21",
    "mp21" => "application/mp21",
    "mp4s" => "application/mp4",
    "doc" => "application/msword",
    "dot" => "application/msword",
    "mxf" => "application/mxf",
    "bin" => "application/octet-stream",
    "dms" => "application/octet-stream",
    "lrf" => "application/octet-stream",
    "mar" => "application/octet-stream",
    "so" => "application/octet-stream",
    "dist" => "application/octet-stream",
    "distz" => "application/octet-stream",
    "pkg" => "application/octet-stream",
    "bpk" => "application/octet-stream",
    "dump" => "application/octet-stream",
    "elc" => "application/octet-stream",
    "deploy" => "application/octet-stream",
    "oda" => "application/oda",
    "opf" => "application/oebps-package+xml",
    "ogx" => "application/ogg",
    "omdoc" => "application/omdoc+xml",
    "onetoc" => "application/onenote",
    "onetoc2" => "application/onenote",
    "onetmp" => "application/onenote",
    "onepkg" => "application/onenote",
    "oxps" => "application/oxps",
    "xer" => "application/patch-ops-error+xml",
    "pdf" => "application/pdf",
    "pgp" => "application/pgp-encrypted",
    "asc" => "application/pgp-signature",
    "sig" => "application/pgp-signature",
    "prf" => "application/pics-rules",
    "p10" => "application/pkcs10",
    "p7m" => "application/pkcs7-mime",
    "p7c" => "application/pkcs7-mime",
    "p7s" => "application/pkcs7-signature",
    "p8" => "application/pkcs8",
    "ac" => "application/pkix-attr-cert",
    "cer" => "application/pkix-cert",
    "crl" => "application/pkix-crl",
    "pkipath" => "application/pkix-pkipath",
    "pki" => "application/pkixcmp",
    "pls" => "application/pls+xml",
    "ai" => "application/postscript",
    "eps" => "application/postscript",
    "ps" => "application/postscript",
    "cww" => "application/prs.cww",
    "pskcxml" => "application/pskc+xml",
    "rdf" => "application/rdf+xml",
    "rif" => "application/reginfo+xml",
    "rnc" => "application/relax-ng-compact-syntax",
    "rl" => "application/resource-lists+xml",
    "rld" => "application/resource-lists-diff+xml",
    "rs" => "application/rls-Services+xml",
    "gbr" => "application/rpki-ghostbusters",
    "mft" => "application/rpki-manifest",
    "roa" => "application/rpki-roa",
    "rsd" => "application/rsd+xml",
    "rss" => "application/rss+xml",
    "rtf" => "application/rtf",
    "sbml" => "application/sbml+xml",
    "scq" => "application/scvp-cv-request",
    "scs" => "application/scvp-cv-response",
    "spq" => "application/scvp-vp-request",
    "spp" => "application/scvp-vp-response",
    "sdp" => "application/sdp",
    "setpay" => "application/set-payment-initiation",
    "setreg" => "application/set-registration-initiation",
    "shf" => "application/shf+xml",
    "smi" => "application/smil+xml",
    "smil" => "application/smil+xml",
    "rq" => "application/sparql-query",
    "srx" => "application/sparql-results+xml",
    "gram" => "application/srgs",
    "grxml" => "application/srgs+xml",
    "sru" => "application/sru+xml",
    "ssdl" => "application/ssdl+xml",
    "ssml" => "application/ssml+xml",
    "tei" => "application/tei+xml",
    "teicorpus" => "application/tei+xml",
    "tfi" => "application/thraud+xml",
    "tsd" => "application/timestamped-data",
    "plb" => "application/vnd.3gpp.pic-bw-large",
    "psb" => "application/vnd.3gpp.pic-bw-small",
    "pvb" => "application/vnd.3gpp.pic-bw-var",
    "tcap" => "application/vnd.3gpp2.tcap",
    "pwn" => "application/vnd.3m.post-it-notes",
    "aso" => "application/vnd.accpac.simply.aso",
    "imp" => "application/vnd.accpac.simply.imp",
    "acu" => "application/vnd.acucobol",
    "atc" => "application/vnd.acucorp",
    "acutc" => "application/vnd.acucorp",
    "air" => "application/vnd.adobe.air-application-installer-package+zip",
    "fcdt" => "application/vnd.adobe.formscentral.fcdt",
    "fxp" => "application/vnd.adobe.fxp",
    "fxpl" => "application/vnd.adobe.fxp",
    "xdp" => "application/vnd.adobe.xdp+xml",
    "xfdf" => "application/vnd.adobe.xfdf",
    "ahead" => "application/vnd.ahead.space",
    "azf" => "application/vnd.airzip.filesecure.azf",
    "azs" => "application/vnd.airzip.filesecure.azs",
    "azw" => "application/vnd.amazon.ebook",
    "acc" => "application/vnd.americandynamics.acc",
    "ami" => "application/vnd.amiga.ami",
    "apk" => "application/vnd.android.package-archive",
    "cii" => "application/vnd.anser-web-certificate-issue-initiation",
    "fti" => "application/vnd.anser-web-funds-transfer-initiation",
    "atx" => "application/vnd.antix.game-component",
    "mpkg" => "application/vnd.apple.installer+xml",
    "m3u8" => "application/vnd.apple.mpegurl",
    "swi" => "application/vnd.aristanetworks.swi",
    "iota" => "application/vnd.astraea-software.iota",
    "aep" => "application/vnd.audiograph",
    "mpm" => "application/vnd.blueice.multipass",
    "bmi" => "application/vnd.bmi",
    "rep" => "application/vnd.businessobjects",
    "cdxml" => "application/vnd.chemdraw+xml",
    "mmd" => "application/vnd.chipnuts.karaoke-mmd",
    "cdy" => "application/vnd.cinderella",
    "cla" => "application/vnd.claymore",
    "rp9" => "application/vnd.cloanto.rp9",
    "c4g" => "application/vnd.clonk.c4group",
    "c4d" => "application/vnd.clonk.c4group",
    "c4f" => "application/vnd.clonk.c4group",
    "c4p" => "application/vnd.clonk.c4group",
    "c4u" => "application/vnd.clonk.c4group",
    "c11amc" => "application/vnd.cluetrust.cartomobile-config",
    "c11amz" => "application/vnd.cluetrust.cartomobile-config-pkg",
    "csp" => "application/vnd.commonspace",
    "cdbcmsg" => "application/vnd.contact.cmsg",
    "cmc" => "application/vnd.cosmocaller",
    "clkx" => "application/vnd.crick.clicker",
    "clkk" => "application/vnd.crick.clicker.keyboard",
    "clkp" => "application/vnd.crick.clicker.palette",
    "clkt" => "application/vnd.crick.clicker.template",
    "clkw" => "application/vnd.crick.clicker.wordbank",
    "wbs" => "application/vnd.criticaltools.wbs+xml",
    "pml" => "application/vnd.ctc-posml",
    "ppd" => "application/vnd.cups-ppd",
    "car" => "application/vnd.curl.car",
    "pcurl" => "application/vnd.curl.pcurl",
    "dart" => "application/vnd.dart",
    "rdz" => "application/vnd.data-vision.rdz",
    "uvf" => "application/vnd.dece.data",
    "uvvf" => "application/vnd.dece.data",
    "uvd" => "application/vnd.dece.data",
    "uvvd" => "application/vnd.dece.data",
    "uvt" => "application/vnd.dece.ttml+xml",
    "uvvt" => "application/vnd.dece.ttml+xml",
    "uvx" => "application/vnd.dece.unspecified",
    "uvvx" => "application/vnd.dece.unspecified",
    "uvz" => "application/vnd.dece.zip",
    "uvvz" => "application/vnd.dece.zip",
    "fe_launch" => "application/vnd.denovo.fcselayout-link",
    "dna" => "application/vnd.dna",
    "mlp" => "application/vnd.dolby.mlp",
    "dpg" => "application/vnd.dpgraph",
    "dfac" => "application/vnd.dreamfactory",
    "kpxx" => "application/vnd.ds-keypoint",
    "ait" => "application/vnd.dvb.ait",
    "svc" => "application/vnd.dvb.service",
    "geo" => "application/vnd.dynageo",
    "mag" => "application/vnd.ecowin.chart",
    "nml" => "application/vnd.enliven",
    "esf" => "application/vnd.epson.esf",
    "msf" => "application/vnd.epson.msf",
    "qam" => "application/vnd.epson.quickanime",
    "slt" => "application/vnd.epson.salt",
    "ssf" => "application/vnd.epson.ssf",
    "es3" => "application/vnd.eszigno3+xml",
    "et3" => "application/vnd.eszigno3+xml",
    "ez2" => "application/vnd.ezpix-album",
    "ez3" => "application/vnd.ezpix-package",
    "fdf" => "application/vnd.fdf",
    "mseed" => "application/vnd.fdsn.mseed",
    "seed" => "application/vnd.fdsn.seed",
    "dataless" => "application/vnd.fdsn.seed",
    "gph" => "application/vnd.flographit",
    "ftc" => "application/vnd.fluxtime.clip",
    "fm" => "application/vnd.framemaker",
    "frame" => "application/vnd.framemaker",
    "maker" => "application/vnd.framemaker",
    "book" => "application/vnd.framemaker",
    "fnc" => "application/vnd.frogans.fnc",
    "ltf" => "application/vnd.frogans.ltf",
    "fsc" => "application/vnd.fsc.weblaunch",
    "oas" => "application/vnd.fujitsu.oasys",
    "oa2" => "application/vnd.fujitsu.oasys2",
    "oa3" => "application/vnd.fujitsu.oasys3",
    "fg5" => "application/vnd.fujitsu.oasysgp",
    "bh2" => "application/vnd.fujitsu.oasysprs",
    "ddd" => "application/vnd.fujixerox.ddd",
    "xdw" => "application/vnd.fujixerox.docuworks",
    "xbd" => "application/vnd.fujixerox.docuworks.binder",
    "fzs" => "application/vnd.fuzzysheet",
    "txd" => "application/vnd.genomatix.tuxedo",
    "ggb" => "application/vnd.geogebra.file",
    "ggt" => "application/vnd.geogebra.tool",
    "gex" => "application/vnd.geometry-explorer",
    "gre" => "application/vnd.geometry-explorer",
    "gxt" => "application/vnd.geonext",
    "g2w" => "application/vnd.geoplan",
    "g3w" => "application/vnd.geospace",
    "gmx" => "application/vnd.gmx",
    "kml" => "application/vnd.google-earth.kml+xml",
    "kmz" => "application/vnd.google-earth.kmz",
    "gqf" => "application/vnd.grafeq",
    "gqs" => "application/vnd.grafeq",
    "gac" => "application/vnd.groove-account",
    "ghf" => "application/vnd.groove-help",
    "gim" => "application/vnd.groove-identity-message",
    "grv" => "application/vnd.groove-injector",
    "gtm" => "application/vnd.groove-tool-message",
    "tpl" => "application/vnd.groove-tool-template",
    "vcg" => "application/vnd.groove-vcard",
    "hal" => "application/vnd.hal+xml",
    "zmm" => "application/vnd.handheld-entertainment+xml",
    "hbci" => "application/vnd.hbci",
    "les" => "application/vnd.hhe.lesson-player",
    "hpgl" => "application/vnd.hp-hpgl",
    "hpid" => "application/vnd.hp-hpid",
    "hps" => "application/vnd.hp-hps",
    "jlt" => "application/vnd.hp-jlyt",
    "pcl" => "application/vnd.hp-pcl",
    "pclxl" => "application/vnd.hp-pclxl",
    "sfd-hdstx" => "application/vnd.hydrostatix.sof-data",
    "mpy" => "application/vnd.ibm.minipay",
    "afp" => "application/vnd.ibm.modcap",
    "listafp" => "application/vnd.ibm.modcap",
    "list3820" => "application/vnd.ibm.modcap",
    "irm" => "application/vnd.ibm.rights-management",
    "sc" => "application/vnd.ibm.secure-container",
    "icc" => "application/vnd.iccprofile",
    "icm" => "application/vnd.iccprofile",
    "igl" => "application/vnd.igloader",
    "ivp" => "application/vnd.immervision-ivp",
    "ivu" => "application/vnd.immervision-ivu",
    "igm" => "application/vnd.insors.igm",
    "xpw" => "application/vnd.intercon.formnet",
    "xpx" => "application/vnd.intercon.formnet",
    "i2g" => "application/vnd.intergeo",
    "qbo" => "application/vnd.intu.qbo",
    "qfx" => "application/vnd.intu.qfx",
    "rcprofile" => "application/vnd.ipunplugged.rcprofile",
    "irp" => "application/vnd.irepository.package+xml",
    "xpr" => "application/vnd.is-xpr",
    "fcs" => "application/vnd.isac.fcs",
    "jam" => "application/vnd.jam",
    "rms" => "application/vnd.jcp.javame.midlet-rms",
    "jisp" => "application/vnd.jisp",
    "joda" => "application/vnd.joost.joda-archive",
    "ktz" => "application/vnd.kahootz",
    "ktr" => "application/vnd.kahootz",
    "karbon" => "application/vnd.kde.karbon",
    "chrt" => "application/vnd.kde.kchart",
    "kfo" => "application/vnd.kde.kformula",
    "flw" => "application/vnd.kde.kivio",
    "kon" => "application/vnd.kde.kontour",
    "kpr" => "application/vnd.kde.kpresenter",
    "kpt" => "application/vnd.kde.kpresenter",
    "ksp" => "application/vnd.kde.kspread",
    "kwd" => "application/vnd.kde.kword",
    "kwt" => "application/vnd.kde.kword",
    "htke" => "application/vnd.kenameaapp",
    "kia" => "application/vnd.kidspiration",
    "kne" => "application/vnd.kinar",
    "knp" => "application/vnd.kinar",
    "skp" => "application/vnd.koan",
    "skd" => "application/vnd.koan",
    "skt" => "application/vnd.koan",
    "skm" => "application/vnd.koan",
    "sse" => "application/vnd.kodak-descriptor",
    "lasxml" => "application/vnd.las.las+xml",
    "lbd" => "application/vnd.llamagraphics.life-balance.desktop",
    "lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml",
    "123" => "application/vnd.lotus-1-2-3",
    "apr" => "application/vnd.lotus-approach",
    "pre" => "application/vnd.lotus-freelance",
    "nsf" => "application/vnd.lotus-notes",
    "org" => "application/vnd.lotus-organizer",
    "scm" => "application/vnd.lotus-screencam",
    "lwp" => "application/vnd.lotus-wordpro",
    "portpkg" => "application/vnd.macports.portpkg",
    "mcd" => "application/vnd.mcd",
    "mc1" => "application/vnd.medcalcdata",
    "cdkey" => "application/vnd.mediastation.cdkey",
    "mwf" => "application/vnd.mfer",
    "mfm" => "application/vnd.mfmp",
    "flo" => "application/vnd.micrografx.flo",
    "igx" => "application/vnd.micrografx.igx",
    "mif" => "application/vnd.mif",
    "daf" => "application/vnd.mobius.daf",
    "dis" => "application/vnd.mobius.dis",
    "mbk" => "application/vnd.mobius.mbk",
    "mqy" => "application/vnd.mobius.mqy",
    "msl" => "application/vnd.mobius.msl",
    "plc" => "application/vnd.mobius.plc",
    "txf" => "application/vnd.mobius.txf",
    "mpn" => "application/vnd.mophun.application",
    "mpc" => "application/vnd.mophun.certificate",
    "xul" => "application/vnd.mozilla.xul+xml",
    "cil" => "application/vnd.ms-artgalry",
    "cab" => "application/vnd.ms-cab-compressed",
    "xls" => "application/vnd.ms-excel",
    "xlm" => "application/vnd.ms-excel",
    "xla" => "application/vnd.ms-excel",
    "xlc" => "application/vnd.ms-excel",
    "xlt" => "application/vnd.ms-excel",
    "xlw" => "application/vnd.ms-excel",
    "xlam" => "application/vnd.ms-excel.addin.macroenabled.12",
    "xlsb" => "application/vnd.ms-excel.sheet.binary.macroenabled.12",
    "xlsm" => "application/vnd.ms-excel.sheet.macroenabled.12",
    "xltm" => "application/vnd.ms-excel.template.macroenabled.12",
    "eot" => "application/vnd.ms-fontobject",
    "chm" => "application/vnd.ms-htmlhelp",
    "ims" => "application/vnd.ms-ims",
    "lrm" => "application/vnd.ms-lrm",
    "thmx" => "application/vnd.ms-officetheme",
    "cat" => "application/vnd.ms-pki.seccat",
    "stl" => "application/vnd.ms-pki.stl",
    "ppt" => "application/vnd.ms-powerpoint",
    "pps" => "application/vnd.ms-powerpoint",
    "pot" => "application/vnd.ms-powerpoint",
    "ppam" => "application/vnd.ms-powerpoint.addin.macroenabled.12",
    "pptm" => "application/vnd.ms-powerpoint.presentation.macroenabled.12",
    "sldm" => "application/vnd.ms-powerpoint.slide.macroenabled.12",
    "ppsm" => "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
    "potm" => "application/vnd.ms-powerpoint.template.macroenabled.12",
    "mpp" => "application/vnd.ms-project",
    "mpt" => "application/vnd.ms-project",
    "docm" => "application/vnd.ms-word.document.macroenabled.12",
    "dotm" => "application/vnd.ms-word.template.macroenabled.12",
    "wps" => "application/vnd.ms-works",
    "wks" => "application/vnd.ms-works",
    "wcm" => "application/vnd.ms-works",
    "wdb" => "application/vnd.ms-works",
    "wpl" => "application/vnd.ms-wpl",
    "xps" => "application/vnd.ms-xpsdocument",
    "mseq" => "application/vnd.mseq",
    "mus" => "application/vnd.musician",
    "msty" => "application/vnd.muvee.style",
    "taglet" => "application/vnd.mynfc",
    "nlu" => "application/vnd.neurolanguage.nlu",
    "ntf" => "application/vnd.nitf",
    "nitf" => "application/vnd.nitf",
    "nnd" => "application/vnd.noblenet-directory",
    "nns" => "application/vnd.noblenet-sealer",
    "nnw" => "application/vnd.noblenet-web",
    "ngdat" => "application/vnd.nokia.n-gage.data",
    "n-gage" => "application/vnd.nokia.n-gage.symbian.install",
    "rpst" => "application/vnd.nokia.radio-preset",
    "rpss" => "application/vnd.nokia.radio-presets",
    "edm" => "application/vnd.novadigm.edm",
    "edx" => "application/vnd.novadigm.edx",
    "ext" => "application/vnd.novadigm.ext",
    "odc" => "application/vnd.oasis.opendocument.chart",
    "otc" => "application/vnd.oasis.opendocument.chart-template",
    "odb" => "application/vnd.oasis.opendocument.database",
    "odf" => "application/vnd.oasis.opendocument.formula",
    "odft" => "application/vnd.oasis.opendocument.formula-template",
    "odg" => "application/vnd.oasis.opendocument.graphics",
    "otg" => "application/vnd.oasis.opendocument.graphics-template",
    "odi" => "application/vnd.oasis.opendocument.image",
    "oti" => "application/vnd.oasis.opendocument.image-template",
    "odp" => "application/vnd.oasis.opendocument.presentation",
    "otp" => "application/vnd.oasis.opendocument.presentation-template",
    "ods" => "application/vnd.oasis.opendocument.spreadsheet",
    "ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
    "odt" => "application/vnd.oasis.opendocument.text",
    "odm" => "application/vnd.oasis.opendocument.text-master",
    "ott" => "application/vnd.oasis.opendocument.text-template",
    "oth" => "application/vnd.oasis.opendocument.text-web",
    "xo" => "application/vnd.olpc-sugar",
    "dd2" => "application/vnd.oma.dd2+xml",
    "oxt" => "application/vnd.openofficeorg.extension",
    "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "sldx" => "application/vnd.openxmlformats-officedocument.presentationml.slide",
    "ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
    "potx" => "application/vnd.openxmlformats-officedocument.presentationml.template",
    "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
    "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
    "mgp" => "application/vnd.osgeo.mapguide.package",
    "dp" => "application/vnd.osgi.dp",
    "esa" => "application/vnd.osgi.subsystem",
    "pdb" => "application/vnd.palm",
    "pqa" => "application/vnd.palm",
    "oprc" => "application/vnd.palm",
    "paw" => "application/vnd.pawaafile",
    "str" => "application/vnd.pg.format",
    "ei6" => "application/vnd.pg.osasli",
    "efif" => "application/vnd.picsel",
    "wg" => "application/vnd.pmi.widget",
    "plf" => "application/vnd.pocketlearn",
    "pbd" => "application/vnd.powerbuilder6",
    "box" => "application/vnd.previewsystems.box",
    "mgz" => "application/vnd.proteus.magazine",
    "qps" => "application/vnd.publishare-delta-tree",
    "ptid" => "application/vnd.pvi.ptid1",
    "qxd" => "application/vnd.quark.quarkxpress",
    "qxt" => "application/vnd.quark.quarkxpress",
    "qwd" => "application/vnd.quark.quarkxpress",
    "qwt" => "application/vnd.quark.quarkxpress",
    "qxl" => "application/vnd.quark.quarkxpress",
    "qxb" => "application/vnd.quark.quarkxpress",
    "bed" => "application/vnd.realvnc.bed",
    "mxl" => "application/vnd.recordare.musicxml",
    "musicxml" => "application/vnd.recordare.musicxml+xml",
    "cryptonote" => "application/vnd.rig.cryptonote",
    "cod" => "application/vnd.rim.cod",
    "rm" => "application/vnd.rn-realmedia",
    "rmvb" => "application/vnd.rn-realmedia-vbr",
    "link66" => "application/vnd.route66.link66+xml",
    "st" => "application/vnd.sailingtracker.track",
    "see" => "application/vnd.seemail",
    "sema" => "application/vnd.sema",
    "semd" => "application/vnd.semd",
    "semf" => "application/vnd.semf",
    "ifm" => "application/vnd.shana.informed.formdata",
    "itp" => "application/vnd.shana.informed.formtemplate",
    "iif" => "application/vnd.shana.informed.interchange",
    "ipk" => "application/vnd.shana.informed.package",
    "twd" => "application/vnd.simtech-mindmapper",
    "twds" => "application/vnd.simtech-mindmapper",
    "mmf" => "application/vnd.smaf",
    "teacher" => "application/vnd.smart.teacher",
    "sdkm" => "application/vnd.solent.sdkm+xml",
    "sdkd" => "application/vnd.solent.sdkm+xml",
    "dxp" => "application/vnd.spotfire.dxp",
    "sfs" => "application/vnd.spotfire.sfs",
    "sdc" => "application/vnd.stardivision.calc",
    "sda" => "application/vnd.stardivision.draw",
    "sdd" => "application/vnd.stardivision.impress",
    "smf" => "application/vnd.stardivision.math",
    "sdw" => "application/vnd.stardivision.writer",
    "vor" => "application/vnd.stardivision.writer",
    "sgl" => "application/vnd.stardivision.writer-global",
    "smzip" => "application/vnd.stepmania.package",
    "sm" => "application/vnd.stepmania.stepchart",
    "sxc" => "application/vnd.sun.xml.calc",
    "stc" => "application/vnd.sun.xml.calc.template",
    "sxd" => "application/vnd.sun.xml.draw",
    "std" => "application/vnd.sun.xml.draw.template",
    "sxi" => "application/vnd.sun.xml.impress",
    "sti" => "application/vnd.sun.xml.impress.template",
    "sxm" => "application/vnd.sun.xml.math",
    "sxw" => "application/vnd.sun.xml.writer",
    "sxg" => "application/vnd.sun.xml.writer.global",
    "stw" => "application/vnd.sun.xml.writer.template",
    "sus" => "application/vnd.sus-calendar",
    "susp" => "application/vnd.sus-calendar",
    "svd" => "application/vnd.svd",
    "sis" => "application/vnd.symbian.install",
    "sisx" => "application/vnd.symbian.install",
    "xsm" => "application/vnd.syncml+xml",
    "bdm" => "application/vnd.syncml.dm+wbxml",
    "xdm" => "application/vnd.syncml.dm+xml",
    "tao" => "application/vnd.tao.intent-module-archive",
    "pcap" => "application/vnd.tcpdump.pcap",
    "cap" => "application/vnd.tcpdump.pcap",
    "dmp" => "application/vnd.tcpdump.pcap",
    "tmo" => "application/vnd.tmobile-livetv",
    "tpt" => "application/vnd.trid.tpt",
    "mxs" => "application/vnd.triscape.mxs",
    "tra" => "application/vnd.trueapp",
    "ufd" => "application/vnd.ufdl",
    "ufdl" => "application/vnd.ufdl",
    "utz" => "application/vnd.uiq.theme",
    "umj" => "application/vnd.umajin",
    "unityweb" => "application/vnd.unity",
    "uoml" => "application/vnd.uoml+xml",
    "vcx" => "application/vnd.vcx",
    "vsd" => "application/vnd.visio",
    "vst" => "application/vnd.visio",
    "vss" => "application/vnd.visio",
    "vsw" => "application/vnd.visio",
    "vis" => "application/vnd.visionary",
    "vsf" => "application/vnd.vsf",
    "wbxml" => "application/vnd.wap.wbxml",
    "wmlc" => "application/vnd.wap.wmlc",
    "wmlsc" => "application/vnd.wap.wmlscriptc",
    "wtb" => "application/vnd.webturbo",
    "nbp" => "application/vnd.wolfram.player",
    "wpd" => "application/vnd.wordperfect",
    "wqd" => "application/vnd.wqd",
    "stf" => "application/vnd.wt.stf",
    "xar" => "application/vnd.xara",
    "xfdl" => "application/vnd.xfdl",
    "hvd" => "application/vnd.yamaha.hv-dic",
    "hvs" => "application/vnd.yamaha.hv-script",
    "hvp" => "application/vnd.yamaha.hv-voice",
    "osf" => "application/vnd.yamaha.openscoreformat",
    "osfpvg" => "application/vnd.yamaha.openscoreformat.osfpvg+xml",
    "saf" => "application/vnd.yamaha.smaf-audio",
    "spf" => "application/vnd.yamaha.smaf-phrase",
    "cmp" => "application/vnd.yellowriver-custom-menu",
    "zir" => "application/vnd.zul",
    "zirz" => "application/vnd.zul",
    "zaz" => "application/vnd.zzazz.deck+xml",
    "vxml" => "application/voicexml+xml",
    "wgt" => "application/widget",
    "hlp" => "application/winhlp",
    "wsdl" => "application/wsdl+xml",
    "wspolicy" => "application/wspolicy+xml",
    "7z" => "application/x-7z-compressed",
    "abw" => "application/x-abiword",
    "ace" => "application/x-ace-compressed",
    "dmg" => "application/x-apple-diskimage",
    "aab" => "application/x-authorware-bin",
    "x32" => "application/x-authorware-bin",
    "u32" => "application/x-authorware-bin",
    "vox" => "application/x-authorware-bin",
    "aam" => "application/x-authorware-map",
    "aas" => "application/x-authorware-seg",
    "bcpio" => "application/x-bcpio",
    "torrent" => "application/x-bittorrent",
    "blb" => "application/x-blorb",
    "blorb" => "application/x-blorb",
    "bz" => "application/x-bzip",
    "bz2" => "application/x-bzip2",
    "boz" => "application/x-bzip2",
    "cbr" => "application/x-cbr",
    "cba" => "application/x-cbr",
    "cbt" => "application/x-cbr",
    "cbz" => "application/x-cbr",
    "cb7" => "application/x-cbr",
    "vcd" => "application/x-cdlink",
    "cfs" => "application/x-cfs-compressed",
    "chat" => "application/x-chat",
    "pgn" => "application/x-chess-pgn",
    "nsc" => "application/x-conference",
    "cpio" => "application/x-cpio",
    "csh" => "application/x-csh",
    "deb" => "application/x-debian-package",
    "udeb" => "application/x-debian-package",
    "dgc" => "application/x-dgc-compressed",
    "dir" => "application/x-director",
    "dcr" => "application/x-director",
    "dxr" => "application/x-director",
    "cst" => "application/x-director",
    "cct" => "application/x-director",
    "cxt" => "application/x-director",
    "w3d" => "application/x-director",
    "fgd" => "application/x-director",
    "swa" => "application/x-director",
    "wad" => "application/x-doom",
    "ncx" => "application/x-dtbncx+xml",
    "dtb" => "application/x-dtbook+xml",
    "res" => "application/x-dtbresource+xml",
    "dvi" => "application/x-dvi",
    "evy" => "application/x-envoy",
    "eva" => "application/x-eva",
    "bdf" => "application/x-font-bdf",
    "gsf" => "application/x-font-ghostscript",
    "psf" => "application/x-font-linux-psf",
    "otf" => "application/x-font-otf",
    "pcf" => "application/x-font-pcf",
    "snf" => "application/x-font-snf",
    "ttf" => "application/x-font-ttf",
    "ttc" => "application/x-font-ttf",
    "pfa" => "application/x-font-type1",
    "pfb" => "application/x-font-type1",
    "pfm" => "application/x-font-type1",
    "afm" => "application/x-font-type1",
    "woff" => "application/x-font-woff",
    "arc" => "application/x-freearc",
    "spl" => "application/x-futuresplash",
    "gca" => "application/x-gca-compressed",
    "ulx" => "application/x-glulx",
    "gnumeric" => "application/x-gnumeric",
    "gramps" => "application/x-gramps-xml",
    "gtar" => "application/x-gtar",
    "tbz" => "application/x-gtar",
    "tgz" => "application/x-gtar",
    "tar.gz" => "application/x-gtar",
    "tbz2" => "application/x-gtar",
    "tar.bz2" => "application/x-gtar",
    "bz2" => "application/x-bzip2",
    "gz" => "application/x-gzip",
    "hdf" => "application/x-hdf",
    "install" => "application/x-install-instructions",
    "iso" => "application/x-iso9660-image",
    "jnlp" => "application/x-java-jnlp-file",
    "latex" => "application/x-latex",
    "lzh" => "application/x-lzh-compressed",
    "lha" => "application/x-lzh-compressed",
    "mie" => "application/x-mie",
    "prc" => "application/x-mobipocket-ebook",
    "mobi" => "application/x-mobipocket-ebook",
    "application" => "application/x-ms-application",
    "lnk" => "application/x-ms-shortcut",
    "wmd" => "application/x-ms-wmd",
    "wmz" => "application/x-ms-wmz",
    "xbap" => "application/x-ms-xbap",
    "mdb" => "application/x-msaccess",
    "obd" => "application/x-msbinder",
    "crd" => "application/x-mscardfile",
    "clp" => "application/x-msclip",
    "exe" => "application/x-msdownload",
    "dll" => "application/x-msdownload",
    "com" => "application/x-msdownload",
    "bat" => "application/x-msdownload",
    "msi" => "application/x-msdownload",
    "mvb" => "application/x-msmediaview",
    "m13" => "application/x-msmediaview",
    "m14" => "application/x-msmediaview",
    "wmf" => "application/x-msmetafile",
    "wmz" => "application/x-msmetafile",
    "emf" => "application/x-msmetafile",
    "emz" => "application/x-msmetafile",
    "mny" => "application/x-msmoney",
    "pub" => "application/x-mspublisher",
    "scd" => "application/x-msschedule",
    "trm" => "application/x-msterminal",
    "wri" => "application/x-mswrite",
    "nc" => "application/x-netcdf",
    "cdf" => "application/x-netcdf",
    "nzb" => "application/x-nzb",
    "p12" => "application/x-pkcs12",
    "pfx" => "application/x-pkcs12",
    "p7b" => "application/x-pkcs7-certificates",
    "spc" => "application/x-pkcs7-certificates",
    "p7r" => "application/x-pkcs7-certreqresp",
    "rar" => "application/x-rar-compressed",
    "ris" => "application/x-research-info-systems",
    "sh" => "application/x-sh",
    "shar" => "application/x-shar",
    "swf" => "application/x-shockwave-flash",
    "xap" => "application/x-silverlight-app",
    "sql" => "application/x-sql",
    "sit" => "application/x-stuffit",
    "sitx" => "application/x-stuffitx",
    "srt" => "application/x-subrip",
    "sv4cpio" => "application/x-sv4cpio",
    "sv4crc" => "application/x-sv4crc",
    "t3" => "application/x-t3vm-image",
    "gam" => "application/x-tads",
    "tar" => "application/x-tar",
    "tcl" => "application/x-tcl",
    "tex" => "application/x-tex",
    "tfm" => "application/x-tex-tfm",
    "texinfo" => "application/x-texinfo",
    "texi" => "application/x-texinfo",
    "obj" => "application/x-tgif",
    "ustar" => "application/x-ustar",
    "src" => "application/x-wais-source",
    "der" => "application/x-x509-ca-cert",
    "crt" => "application/x-x509-ca-cert",
    "fig" => "application/x-xfig",
    "xlf" => "application/x-xliff+xml",
    "xpi" => "application/x-xpinstall",
    "xz" => "application/x-xz",
    "z1" => "application/x-zmachine",
    "z2" => "application/x-zmachine",
    "z3" => "application/x-zmachine",
    "z4" => "application/x-zmachine",
    "z5" => "application/x-zmachine",
    "z6" => "application/x-zmachine",
    "z7" => "application/x-zmachine",
    "z8" => "application/x-zmachine",
    "xaml" => "application/xaml+xml",
    "xdf" => "application/xcap-diff+xml",
    "xenc" => "application/xenc+xml",
    "xhtml" => "application/xhtml+xml",
    "xht" => "application/xhtml+xml",
    "xml" => "application/xml",
    "xsl" => "application/xml",
    "dtd" => "application/xml-dtd",
    "xop" => "application/xop+xml",
    "xpl" => "application/xproc+xml",
    "xslt" => "application/xslt+xml",
    "xspf" => "application/xspf+xml",
    "mxml" => "application/xv+xml",
    "xhvml" => "application/xv+xml",
    "xvml" => "application/xv+xml",
    "xvm" => "application/xv+xml",
    "yang" => "application/yang",
    "yin" => "application/yin+xml",
    "zip" => "application/zip",
    "adp" => "audio/adpcm",
    "au" => "audio/basic",
    "snd" => "audio/basic",
    "mid" => "audio/midi",
    "midi" => "audio/midi",
    "kar" => "audio/midi",
    "rmi" => "audio/midi",
    "mp4a" => "audio/mp4",
    "mpga" => "audio/mpeg",
    "mp2" => "audio/mpeg",
    "mp2a" => "audio/mpeg",
    "mp3" => "audio/mpeg",
    "m2a" => "audio/mpeg",
    "m3a" => "audio/mpeg",
    "oga" => "audio/ogg",
    "ogg" => "audio/ogg",
    "spx" => "audio/ogg",
    "s3m" => "audio/s3m",
    "sil" => "audio/silk",
    "uva" => "audio/vnd.dece.audio",
    "uvva" => "audio/vnd.dece.audio",
    "eol" => "audio/vnd.digital-winds",
    "dra" => "audio/vnd.dra",
    "dts" => "audio/vnd.dts",
    "dtshd" => "audio/vnd.dts.hd",
    "lvp" => "audio/vnd.lucent.voice",
    "pya" => "audio/vnd.ms-playready.media.pya",
    "ecelp4800" => "audio/vnd.nuera.ecelp4800",
    "ecelp7470" => "audio/vnd.nuera.ecelp7470",
    "ecelp9600" => "audio/vnd.nuera.ecelp9600",
    "rip" => "audio/vnd.rip",
    "weba" => "audio/webm",
    "aac" => "audio/x-aac",
    "aif" => "audio/x-aiff",
    "aiff" => "audio/x-aiff",
    "aifc" => "audio/x-aiff",
    "caf" => "audio/x-caf",
    "flac" => "audio/x-flac",
    "mka" => "audio/x-matroska",
    "m3u" => "audio/x-mpegurl",
    "wax" => "audio/x-ms-wax",
    "wma" => "audio/x-ms-wma",
    "ram" => "audio/x-pn-realaudio",
    "ra" => "audio/x-pn-realaudio",
    "rmp" => "audio/x-pn-realaudio-plugin",
    "wav" => "audio/x-wav",
    "xm" => "audio/xm",
    "cdx" => "chemical/x-cdx",
    "cif" => "chemical/x-cif",
    "cmdf" => "chemical/x-cmdf",
    "cml" => "chemical/x-cml",
    "csml" => "chemical/x-csml",
    "xyz" => "chemical/x-xyz",
    "bmp" => "image/bmp",
    "cgm" => "image/cgm",
    "g3" => "image/g3fax",
    "gif" => "image/gif",
    "ief" => "image/ief",
    "jpeg" => "image/jpeg",
    "jpg" => "image/jpeg",
    "jpe" => "image/jpeg",
    "ktx" => "image/ktx",
    "png" => "image/png",
    "btif" => "image/prs.btif",
    "sgi" => "image/sgi",
    "svg" => "image/svg+xml",
    "svgz" => "image/svg+xml",
    "tiff" => "image/tiff",
    "tif" => "image/tiff",
    "psd" => "image/vnd.adobe.photoshop",
    "uvi" => "image/vnd.dece.graphic",
    "uvvi" => "image/vnd.dece.graphic",
    "uvg" => "image/vnd.dece.graphic",
    "uvvg" => "image/vnd.dece.graphic",
    "sub" => "image/vnd.dvb.subtitle",
    "djvu" => "image/vnd.djvu",
    "djv" => "image/vnd.djvu",
    "dwg" => "image/vnd.dwg",
    "dxf" => "image/vnd.dxf",
    "fbs" => "image/vnd.fastbidsheet",
    "fpx" => "image/vnd.fpx",
    "fst" => "image/vnd.fst",
    "mmr" => "image/vnd.fujixerox.edmics-mmr",
    "rlc" => "image/vnd.fujixerox.edmics-rlc",
    "mdi" => "image/vnd.ms-modi",
    "wdp" => "image/vnd.ms-photo",
    "npx" => "image/vnd.net-fpx",
    "wbmp" => "image/vnd.wap.wbmp",
    "xif" => "image/vnd.xiff",
    "webp" => "image/webp",
    "3ds" => "image/x-3ds",
    "ras" => "image/x-cmu-raster",
    "cmx" => "image/x-cmx",
    "fh" => "image/x-freehand",
    "fhc" => "image/x-freehand",
    "fh4" => "image/x-freehand",
    "fh5" => "image/x-freehand",
    "fh7" => "image/x-freehand",
    "ico" => "image/x-icon",
    "sid" => "image/x-mrsid-image",
    "pcx" => "image/x-pcx",
    "pic" => "image/x-pict",
    "pct" => "image/x-pict",
    "pnm" => "image/x-portable-anymap",
    "pbm" => "image/x-portable-bitmap",
    "pgm" => "image/x-portable-graymap",
    "ppm" => "image/x-portable-pixmap",
    "rgb" => "image/x-rgb",
    "tga" => "image/x-tga",
    "xbm" => "image/x-xbitmap",
    "xpm" => "image/x-xpixmap",
    "xwd" => "image/x-xwindowdump",
    "eml" => "message/rfc822",
    "mime" => "message/rfc822",
    "igs" => "model/iges",
    "iges" => "model/iges",
    "msh" => "model/mesh",
    "mesh" => "model/mesh",
    "silo" => "model/mesh",
    "dae" => "model/vnd.collada+xml",
    "dwf" => "model/vnd.dwf",
    "gdl" => "model/vnd.gdl",
    "gtw" => "model/vnd.gtw",
    "mts" => "model/vnd.mts",
    "vtu" => "model/vnd.vtu",
    "wrl" => "model/vrml",
    "vrml" => "model/vrml",
    "x3db" => "model/x3d+binary",
    "x3dbz" => "model/x3d+binary",
    "x3dv" => "model/x3d+vrml",
    "x3dvz" => "model/x3d+vrml",
    "x3d" => "model/x3d+xml",
    "x3dz" => "model/x3d+xml",
    "appcache" => "text/cache-manifest",
    "ics" => "text/calendar",
    "ifb" => "text/calendar",
    "css" => "text/css",
    "csv" => "text/csv",
    "html" => "text/html",
    "htm" => "text/html",
    "n3" => "text/n3",
    "txt" => "text/plain",
    "text" => "text/plain",
    "conf" => "text/plain",
    "def" => "text/plain",
    "list" => "text/plain",
    "Log" => "text/plain",
    "in" => "text/plain",
    "dsc" => "text/prs.lines.tag",
    "rtx" => "text/richtext",
    "sgml" => "text/sgml",
    "sgm" => "text/sgml",
    "tsv" => "text/tab-separated-values",
    "t" => "text/troff",
    "tr" => "text/troff",
    "roff" => "text/troff",
    "man" => "text/troff",
    "me" => "text/troff",
    "ms" => "text/troff",
    "ttl" => "text/turtle",
    "uri" => "text/uri-list",
    "uris" => "text/uri-list",
    "urls" => "text/uri-list",
    "vcard" => "text/vcard",
    "curl" => "text/vnd.curl",
    "dcurl" => "text/vnd.curl.dcurl",
    "scurl" => "text/vnd.curl.scurl",
    "mcurl" => "text/vnd.curl.mcurl",
    "sub" => "text/vnd.dvb.subtitle",
    "fly" => "text/vnd.fly",
    "flx" => "text/vnd.fmi.flexstor",
    "gv" => "text/vnd.graphviz",
    "3dml" => "text/vnd.in3d.3dml",
    "spot" => "text/vnd.in3d.spot",
    "jad" => "text/vnd.sun.j2me.app-descriptor",
    "wml" => "text/vnd.wap.wml",
    "wmls" => "text/vnd.wap.wmlscript",
    "s" => "text/x-asm",
    "asm" => "text/x-asm",
    "c" => "text/x-c",
    "cc" => "text/x-c",
    "cxx" => "text/x-c",
    "cpp" => "text/x-c",
    "h" => "text/x-c",
    "hh" => "text/x-c",
    "dic" => "text/x-c",
    "f" => "text/x-fortran",
    "for" => "text/x-fortran",
    "f77" => "text/x-fortran",
    "f90" => "text/x-fortran",
    "java" => "text/x-java-source",
    "opml" => "text/x-opml",
    "p" => "text/x-pascal",
    "pas" => "text/x-pascal",
    "nfo" => "text/x-nfo",
    "etx" => "text/x-setext",
    "sfv" => "text/x-sfv",
    "uu" => "text/x-uuencode",
    "vcs" => "text/x-vcalendar",
    "vcf" => "text/x-vcard",
    "3gp" => "video/3gpp",
    "3g2" => "video/3gpp2",
    "h261" => "video/h261",
    "h263" => "video/h263",
    "h264" => "video/h264",
    "jpgv" => "video/jpeg",
    "jpm" => "video/jpm",
    "jpgm" => "video/jpm",
    "mj2" => "video/mj2",
    "mjp2" => "video/mj2",
    "mp4" => "video/mp4",
    "mp4v" => "video/mp4",
    "mpg4" => "video/mp4",
    "mpeg" => "video/mpeg",
    "mpg" => "video/mpeg",
    "mpe" => "video/mpeg",
    "m1v" => "video/mpeg",
    "m2v" => "video/mpeg",
    "ogv" => "video/ogg",
    "qt" => "video/quicktime",
    "mov" => "video/quicktime",
    "uvh" => "video/vnd.dece.hd",
    "uvvh" => "video/vnd.dece.hd",
    "uvm" => "video/vnd.dece.mobile",
    "uvvm" => "video/vnd.dece.mobile",
    "uvp" => "video/vnd.dece.pd",
    "uvvp" => "video/vnd.dece.pd",
    "uvs" => "video/vnd.dece.sd",
    "uvvs" => "video/vnd.dece.sd",
    "uvv" => "video/vnd.dece.video",
    "uvvv" => "video/vnd.dece.video",
    "dvb" => "video/vnd.dvb.file",
    "fvt" => "video/vnd.fvt",
    "mxu" => "video/vnd.mpegurl",
    "m4u" => "video/vnd.mpegurl",
    "pyv" => "video/vnd.ms-playready.media.pyv",
    "uvu" => "video/vnd.uvvu.mp4",
    "uvvu" => "video/vnd.uvvu.mp4",
    "viv" => "video/vnd.vivo",
    "webm" => "video/webm",
    "f4v" => "video/x-f4v",
    "fli" => "video/x-fli",
    "flv" => "video/x-flv",
    "m4v" => "video/x-m4v",
    "mkv" => "video/x-matroska",
    "mk3d" => "video/x-matroska",
    "mks" => "video/x-matroska",
    "mng" => "video/x-mng",
    "asf" => "video/x-ms-asf",
    "asx" => "video/x-ms-asf",
    "vob" => "video/x-ms-vob",
    "wm" => "video/x-ms-wm",
    "wmv" => "video/x-ms-wmv",
    "wmx" => "video/x-ms-wmx",
    "wvx" => "video/x-ms-wvx",
    "avi" => "video/x-msvideo",
    "movie" => "video/x-sgi-movie",
    "smv" => "video/x-smv",
    "ice" => "x-conference/x-cooltalk",
);
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Util;

/**
 * Utilities for parsing and formatting dates.
 *
 * <p>
 * Note that this class doesn't use static methods because of the
 * synchronization issues with SimpleDateFormat. This lets synchronization be
 * done on a per-object level, instead of on a per-class level.
 */
class DateUtils
{
    /**
     * Alternate ISO 8601 format without fractional seconds
     */
    const ALTERNATE_ISO8601_DATE_FORMAT = "Y-m-d\TH:i:s\Z";

    /**
     * @var \DateTimeZone The UTC timezone object.
     */
    public static $UTC_TIMEZONE;

    /**
     * Initialize $UTC_TIMEZONE
     */
    public static function  __init()
    {
        DateUtils::$UTC_TIMEZONE = new \DateTimeZone("UTC");
    }

    /**
     * Parses the specified date string as an ISO 8601 date and returns the Date
     * object.
     *
     * @param $dateString string The date string to parse.
     * @return \DateTime The parsed Date object.
     * @throws \Exception If the date string could not be parsed.
     */
    public static function parseAlternateIso8601Date($dateString)
    {
        return \DateTime::createFromFormat(
            DateUtils::ALTERNATE_ISO8601_DATE_FORMAT,
            $dateString,
            DateUtils::$UTC_TIMEZONE
        );
    }

    /**
     * Formats the specified date as an ISO 8601 string.
     *
     * @param $datetime \DateTime The date to format.
     * @return string The ISO 8601 string representing the specified date.
     */
    public static function formatAlternateIso8601Date($datetime)
    {
        return $datetime->format(DateUtils::ALTERNATE_ISO8601_DATE_FORMAT);
    }

    /**
     * Parses the specified date string as an RFC 822 date and returns the Date object.
     *
     * @param $dateString string The date string to parse.
     * @return \DateTime The parsed Date object.
     * @throws \Exception If the date string could not be parsed.
     */
    public static function parseRfc822Date($dateString)
    {
        return \DateTime::createFromFormat(
            \DateTime::RFC822,
            $dateString,
            DateUtils::$UTC_TIMEZONE
        );
    }

    /**
     * Formats the specified date as an RFC 822 string.
     *
     * @param $datetime \DateTime The date to format.
     * @return string The RFC 822 string representing the specified date.
     */
    public static function formatRfc822Date($datetime)
    {
        return $datetime->format(\DateTime::RFC822);
    }
}

DateUtils::__init();<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

$url = 'Http://svn.apache.org/viewvc/httpd/httpd/branches/2.2.x/docs/conf/mime.types?revision=1576707';
$raw = file_get_contents($url);
$lines = explode("\n", trim($raw));
printf("<?php\n");
printf("// Auto generated by GenerateMimeTypes.php, DO NOT EDIT IT.\n");
printf("return array(\n");
foreach ($lines as $idx => $line) {
    if (strpos($line, '#') === 0) {
        continue;
    }

    $chunks = preg_split("/\s+/", $line);
    if (count($chunks) >= 2) {
        $length = count($chunks);
        for ($i = 1; $i < $length; $i++) {
            printf("    \"%s\" => \"%s\",\n", $chunks[$i], $chunks[0]);
        }
    }
}
printf(");\n");





/* vim: set ts=4 sw=4 sts=4 tw=120: */
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Util;

use BaiduBce\Http\HttpHeaders;
use BaiduBce\BceClientConfigOptions;

class HttpUtils
{
    private static $PERCENT_ENCODED_STRINGS;

    public static function __init()
    {
        HttpUtils::$PERCENT_ENCODED_STRINGS = array();
        for ($i = 0; $i < 256; ++$i) {
            HttpUtils::$PERCENT_ENCODED_STRINGS[$i] = sprintf("%%%02X", $i);
        }
        foreach (range('a', 'z') as $ch) {
            HttpUtils::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
        }

        foreach (range('A', 'Z') as $ch) {
            HttpUtils::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
        }

        foreach (range('0', '9') as $ch) {
            HttpUtils::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
        }
        HttpUtils::$PERCENT_ENCODED_STRINGS[ord('-')] = '-';
        HttpUtils::$PERCENT_ENCODED_STRINGS[ord('.')] = '.';
        HttpUtils::$PERCENT_ENCODED_STRINGS[ord('_')] = '_';
        HttpUtils::$PERCENT_ENCODED_STRINGS[ord('~')] = '~';
    }

    public static function parseEndpointFromConfig(array $config)
    {
        $endpoint = $config[BceClientConfigOptions::ENDPOINT];

        // no scheme in endpoint, use protocol in config
        if (!strpos($endpoint, "://")) {
            $config_protocol = strtolower(trim($config[BceClientConfigOptions::PROTOCOL]));
            if ($config_protocol !== 'http' && $config_protocol !== 'https') {
                throw new \InvalidArgumentException(
                    "Invalid protocol $config_protocol."
                );
            }
            $endpoint = $config_protocol . "://" . $endpoint;
        }

        $parsed_endpoint = parse_url($endpoint);

        $scheme = strtolower($parsed_endpoint['scheme']);
        if ($scheme !== 'http' && $scheme !== 'https') {
            throw new \InvalidArgumentException(
                "Invalid endpoint $endpoint, unsupported scheme $scheme."
            );
        }
        $protocol = $scheme;

        $host = $parsed_endpoint['host'];
        if (isset($parsed_endpoint['port'])) {
            $port = (int) $parsed_endpoint['port'];
        } else {
            if ($protocol == 'http') {
                $port = 80;
            } else {
                $port = 443;
            }
        }
        if (($protocol === 'http' && $port === 80)
            || ($protocol === 'https' && $port === 443)) {
            $hostHeader = $host;
        } else {
            $hostHeader = "$host:$port";
        }
        return array("$protocol://$hostHeader", $hostHeader);
    }


    /**
     * Normalize a string for use in url path. The algorithm is:
     * <p>
     *
     * <ol>
     *   <li>Normalize the string</li>
     *   <li>replace all "%2F" with "/"</li>
     *   <li>replace all "//" with "/%2F"</li>
     * </ol>
     *
     * <p>
     * Bos object key can contain arbitrary characters, which may result double
     * slash in the url path. Apache Http client will replace "//" in the path
     * with a single '/', which makes the object key incorrect. Thus we replace
     * "//" with "/%2F" here.
     *
     * @param $path string the path string to normalize.
     * @return string the normalized path string.
     * @see #normalize(string)
     */
    public static function urlEncodeExceptSlash($path)
    {
        return str_replace("%2F", "/", HttpUtils::urlEncode($path));
    }

    /**
     * Normalize a string for use in BCE web service APIs. The normalization
     * algorithm is:
     * <p>
     * <ol>
     *   <li>Convert the string into a UTF-8 byte array.</li>
     *   <li>Encode all octets into percent-encoding, except all URI unreserved
     * characters per the RFC 3986.</li>
     * </ol>
     *
     * <p>
     * All letters used in the percent-encoding are in uppercase.
     *
     * @param $value string the string to normalize.
     * @return string the normalized string.
     */
    public static function urlEncode($value)
    {
        $result = '';
        for ($i = 0; $i < strlen($value); ++$i) {
            $result .= HttpUtils::$PERCENT_ENCODED_STRINGS[ord($value[$i])];
        }
        return $result;
    }

    /**
     * @param $parameters array
     * @param $forSignature bool
     * @return string
     */
    public static function getCanonicalQueryString(array $parameters, $forSignature)
    {
        if (count($parameters) == 0) {
            return '';
        }

        $parameterStrings = array();
        foreach ($parameters as $k => $v) {
            if ($forSignature
                    && strcasecmp(HttpHeaders::AUTHORIZATION, $k) == 0) {
                continue;
            }
            if (!isset($k)) {
                throw new \InvalidArgumentException(
                    "parameter key should not be null"
                );
            }
            if (isset($v)) {
                $parameterStrings[] = HttpUtils::urlEncode($k)
                    . '=' . HttpUtils::urlEncode((string) $v);
            } else {
                if ($forSignature) {
                    $parameterStrings[] = HttpUtils::urlEncode($k) . '=';
                } else {
                    $parameterStrings[] = HttpUtils::urlEncode($k);
                }
            }
        }
        sort($parameterStrings);

        return implode('&', $parameterStrings);
    }

    /**
     * Append the given path to the given baseUri.
     *
     * <p>
     * This method will encode the given path but not the given baseUri.
     *
     */
    public static function appendUri()
    {
        $path = array();
        foreach (func_get_args() as $arg) {
            if ($arg !== null) {
                $path[] = $arg;
            }
        }

        if (count($path) > 1) {
            $last = count($path) - 1;
            $path[0] = rtrim($path[0], '/');
            $path[$last] = ltrim($path[$last], '/');
            for ($i = 1; $i < $last; ++$i) {
                $path[$i] = trim($path[$i], '/');
            }
        }
        return implode("/", $path);
    }
}

HttpUtils::__init();
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Util;


class StringUtils {
    /**
     * @param string $str
     * @param string $prefix
     * @return string
     */
    public static function startsWith($str, $prefix) {
        return substr($str, 0, strlen($prefix)) == $prefix;
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Auth;

class SignOptions
{
    const EXPIRATION_IN_SECONDS = 'expirationInSeconds';

    const HEADERS_TO_SIGN = 'headersToSign';

    const TIMESTAMP = 'timestamp';

    const DEFAULT_EXPIRATION_IN_SECONDS = 1800;

    const MIN_EXPIRATION_IN_SECONDS = 300;

    const MAX_EXPIRATION_IN_SECONDS = 129600;
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Auth;

interface SignerInterface
{
    /**
     * Sign the given request with the given set of credentials and returns the
     * signed authorization string.
     *
     * @param $credentials array the credentials to sign the request with.
     * @param $httpMethod string
     * @param $path string
     * @param $headers array
     * @param $params array
     * @param $options array the options for signing.
     * @return string The signed authorization string.
     */
     public function sign(
        array $credentials,
        $httpMethod,
        $path,
        $headers,
        $params,
        $options = array()
    );
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Auth;

use BaiduBce\Http\HttpHeaders;
use BaiduBce\Util\DateUtils;
use BaiduBce\Util\HttpUtils;

/**
 * The V1 implementation of Signer with the BCE signing protocol.
 */
class BceV1Signer implements SignerInterface
{

    const BCE_AUTH_VERSION = "bce-auth-v1";

    // Default headers to sign with the BCE signing protocol.
    private static $defaultHeadersToSign;

    public static function  __init()
    {
        BceV1Signer::$defaultHeadersToSign = array(
            strtolower(HttpHeaders::HOST),
            strtolower(HttpHeaders::CONTENT_LENGTH),
            strtolower(HttpHeaders::CONTENT_TYPE),
            strtolower(HttpHeaders::CONTENT_MD5),
        );
    }

    /**
     * Sign the given request with the given set of credentials. Modifies the passed-in request to apply the signature.
     *
     * @param $credentials array the credentials to sign the request with.
     * @param $httpMethod string
     * @param $path string
     * @param $headers array
     * @param $params array
     * @param $options  array   the options for signing.
     * @return string The signed authorization string.
     */
    public function sign(
        array $credentials,
        $httpMethod,
        $path,
        $headers,
        $params,
        $options = array()
    ) {
        if (!isset($options[SignOptions::EXPIRATION_IN_SECONDS])) {
            $expirationInSeconds = SignOptions::DEFAULT_EXPIRATION_IN_SECONDS;
        } else {
            $expirationInSeconds = $options[SignOptions::EXPIRATION_IN_SECONDS];
        }

        // to compatible with ak/sk or accessKeyId/secretAccessKey
        if(isset($credentials['ak'])){
            $accessKeyId = $credentials['ak'];
        }
        if(isset($credentials['sk'])){
            $secretAccessKey = $credentials['sk'];
        }
        if(isset($credentials['accessKeyId'])){
            $accessKeyId = $credentials['accessKeyId'];
        }
        if(isset($credentials['secretAccessKey'])){
            $secretAccessKey = $credentials['secretAccessKey'];
        }

        if (isset($options[SignOptions::TIMESTAMP])) {
            $timestamp = $options[SignOptions::TIMESTAMP];
        } else {
            $timestamp = new \DateTime();
        }
        $timestamp->setTimezone(DateUtils::$UTC_TIMEZONE);

        $authString = BceV1Signer::BCE_AUTH_VERSION . '/' . $accessKeyId . '/'
            . DateUtils::formatAlternateIso8601Date(
                $timestamp
            ) . '/' . $expirationInSeconds;

        $signingKey = hash_hmac('sha256', $authString, $secretAccessKey);

        // Formatting the URL with signing protocol.
        $canonicalURI = BceV1Signer::getCanonicalURIPath($path);
        // Formatting the query string with signing protocol.
        $canonicalQueryString = HttpUtils::getCanonicalQueryString(
            $params,
            true
        );

        // Sorted the headers should be signed from the request.
        $headersToSignOption = null;
        if (isset($options[SignOptions::HEADERS_TO_SIGN])) {
            $headersToSignOption = $options[SignOptions::HEADERS_TO_SIGN];
        }
        $headersToSign = BceV1Signer::getHeadersToSign($headers, $headersToSignOption);
        // Formatting the headers from the request based on signing protocol.
        $canonicalHeader = BceV1Signer::getCanonicalHeaders($headersToSign);
        $headersToSign = array_keys($headersToSign);
        sort($headersToSign);
        $signedHeaders = '';
        if ($headersToSignOption !== null) {
            $signedHeaders = strtolower(
                trim(implode(";", $headersToSign))
            );
        }

        $canonicalRequest = "$httpMethod\n$canonicalURI\n"
            . "$canonicalQueryString\n$canonicalHeader";

        // Signing the canonical request using key with sha-256 algorithm.
        $signature = hash_hmac('sha256', $canonicalRequest, $signingKey);

        $authorizationHeader = "$authString/$signedHeaders/$signature";

        return $authorizationHeader;
    }

    /**
     * @param $path string
     * @return string
     */
    private static function getCanonicalURIPath($path)
    {
        if (empty($path)) {
            return '/';
        } else {
            if ($path[0] == '/') {
                return HttpUtils::urlEncodeExceptSlash($path);
            } else {
                return '/' . HttpUtils::urlEncodeExceptSlash($path);
            }
        }
    }

    /**
     * @param $headers array
     * @return string
     */
    private static function getCanonicalHeaders($headers)
    {
        if (count($headers) == 0) {
            return '';
        }

        $headerStrings = array();
        foreach ($headers as $k => $v) {
            if ($k === null) {
                continue;
            }
            if ($v === null) {
                $v = '';
            }
            $headerStrings[] = rawurlencode(
                    strtolower(trim($k))
                ) . ':' . rawurlencode(trim($v));
        }
        sort($headerStrings);

        return implode("\n", $headerStrings);
    }

    /**
     * @param $headers array
     * @param $headersToSign array
     * @return array
     */
    private static function getHeadersToSign($headers, $headersToSign)
    {
        $ret = array();
        if ($headersToSign !== null) {
            $tmp = array();
            foreach ($headersToSign as $header) {
                $tmp[] = strtolower(trim($header));
            }
            $headersToSign = $tmp;
        }
        foreach ($headers as $k => $v) {
            if (trim((string) $v) !== '') {
                if ($headersToSign !== null) {
                    if (in_array(strtolower(trim($k)), $headersToSign)) {
                        $ret[$k] = $v;
                    }
                } else {
                    if (BceV1Signer::isDefaultHeaderToSign(
                        $k,
                        $headersToSign
                    )
                    ) {
                        $ret[$k] = $v;
                    }
                }
            }
        }
        return $ret;
    }

    /**
     * @param $header string
     * @return bool
     */
    private static function isDefaultHeaderToSign($header)
    {
        $header = strtolower(trim($header));
        if (in_array($header, BceV1Signer::$defaultHeadersToSign)) {
            return true;
        }
        $prefix = substr($header, 0, strlen(HttpHeaders::BCE_PREFIX));
        if ($prefix === HttpHeaders::BCE_PREFIX) {
            return true;
        } else {
            return false;
        }
    }
}

BceV1Signer::__init();
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce;


class BceHttpResponse
{

}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Http;

class HttpContentTypes
{
    const JSON = 'application/json; charset=utf-8';
    const OCTET_STREAM = 'application/octet-stream';
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the 'License'); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Http;

/**
 * This module defines string constants for HTTP headers
 */
class HttpHeaders
{
    // Standard HTTP Headers

    const AUTHORIZATION = 'Authorization';
    const CONTENT_DISPOSITION = 'Content-Disposition';
    const CONTENT_ENCODING = 'Content-Encoding';
    const CONTENT_LENGTH = 'Content-Length';
    const CONTENT_MD5 = 'Content-MD5';
    const CONTENT_RANGE = 'Content-Range';
    const CONTENT_TYPE = 'Content-Type';
    const DATE = 'Date';
    const ETAG = 'ETag';
    const EXPIRES = 'Expires';
    const EXPECT = 'Expect';
    const TRANSFER_ENCODING = 'Transfer-Encoding';
    const HOST = 'Host';
    const LAST_MODIFIED = 'Last-Modified';
    const RANGE = 'Range';
    const SERVER = 'Server';
    const USER_AGENT = 'User-Agent';
    const PRAGMA = 'Pragma';
    const CACHE_CONTROL = 'Cache-Control';
    const LOCATION = 'Location';

    // BCE Common HTTP Headers
    const BCE_PREFIX = 'x-bce-';
    
    const BCE_ACL = 'x-bce-acl';
    const BCE_RESTORE_DAYS = 'x-bce-restore-days';
    const BCE_RESTORE_TIER = 'x-bce-restore-tier';

    const BCE_ACL_GRANT_READ = 'x-bce-grant-read';
    const BCE_ACL_GRANT_FULL_CONTROL = 'x-bce-grant-full-control';

    const BCE_SERVER_SIDE_ENCRYPTION = 'x-bce-server-side-encryption';

    const BCE_CONTENT_SHA256 = 'x-bce-content-sha256';
    const BCE_CONTENT_CRC32 = 'x-bce-content-crc32';
    const BCE_COPY_METADATA_DIRECTIVE = 'x-bce-metadata-directive';
    const BCE_COPY_SOURCE = 'x-bce-copy-source';
    const BCE_COPY_RANGE  = 'x-bce-copy-source-range';
    const BCE_COPY_SOURCE_IF_MATCH = 'x-bce-copy-source-if-match';
    const BCE_COPY_SOURCE_IF_NONE_MATCH = 'x-bce-copy-source-if-none-match';
    const BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE = 'x-bce-copy-source-if-unmodified-since';
    const BCE_COPY_SOURCE_IF_MODIFIED_SINCE = 'x-bce-copy-source-if-modified-since';
    const BCE_DATE = 'x-bce-date';
    const BCE_USER_METADATA_PREFIX = 'x-bce-meta-';
    const BCE_REQUEST_ID = 'x-bce-request-id';
    const BCE_STORAGE_CLASS = 'x-bce-storage-class';
    const BCE_SESSION_TOKEN = 'x-bce-security-token';

    // BOS HTTP Headers
    const BOS_DEBUG_ID = 'x-bce-Bos-debug-id';
    const NEXT_APPEND_OFFSET = 'x-bce-next-append-offset';
    const BCE_OBJECT_TYPE = 'x-bce-object-type';
    const BCE_KEEP_TIME = 'x-bce-keep-last-modified';

    const BCE_FETCH_MODE = 'x-bce-fetch-mode';
    const BCE_FETCH_SOURCE = 'x-bce-fetch-source';
    const BCE_PROCESS = "x-bce-process";

    const BCE_SYMLINK_TARGET = "X-Bce-Symlink-Target";
    const BCE_FORBID_OVERWRITE = "x-bce-forbid-overwrite";
    

}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Http;

use BaiduBce\Auth\SignerInterface;
use BaiduBce\Bce;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Exception\BceServiceException;
use BaiduBce\Log\LogFactory;
use BaiduBce\Util\HttpUtils;
use BaiduBce\Util\DateUtils;

use Guzzle\Http\Client;
use Guzzle\Log\MessageFormatter;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Http\EntityBody;
use Guzzle\Http\ReadLimitEntityBody;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Standard Http request of BCE.
 */
class BceHttpClient
{
    /**
     * @var Client
     */
    private $guzzleClient;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct()
    {
        $this->guzzleClient = new Client();
        $this->logger = LogFactory::getLogger(get_class($this));
        if (!($this->logger instanceof NullLogger)) {
            $logPlugin = new LogPlugin(
                new GuzzleLogAdapter(),
                MessageFormatter::DEFAULT_FORMAT
            );
            $this->guzzleClient->addSubscriber($logPlugin);
        }
    }

    /**
     * @param mixed $body The request body.
     * @return number
     */
    private function guessContentLength($body)
    {
        if (is_null($body)) {
            return 0;
        } else {
            if (is_string($body)) {
                return strlen($body);
            } else {
                if (is_resource($body)) {
                    $stat = fstat($body);
                    return $stat['size'];
                } else {
                    if (is_object($body) && method_exists($body, 'getSize')) {
                        return $body->getSize();
                    }
                }
            }
        }
        throw new \InvalidArgumentException(
            sprintf('No %s is specified.', HttpHeaders::CONTENT_LENGTH)
        );
    }


    /**
     * Send request to BCE.
     *
     * @param array $config
     * @param string $httpMethod The Http request method, uppercase.
     * @param string $path The resource path.
     * @param string|resource $body The Http request body.
     * @param array $headers The extra Http request headers.
     * @param array $params The extra Http url query strings.
     * @param SignerInterface $signer This function will generate authorization header.
     * @param resource|string $outputStream Write the Http response to this stream.
     *
     * @return \Guzzle\Http\Message\Response body and http_headers
     *
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function sendRequest(
        array $config,
        $httpMethod,
        $path,
        $body,
        array $headers,
        array $params,
        SignerInterface $signer,
        $outputStream = null,
        $options = array()
    ) {
        $headers[HttpHeaders::USER_AGENT] =
            sprintf(
                'bce-sdk-php/%s/%s/%s',
                Bce::SDK_VERSION,
                php_uname(),
                phpversion()
            );
        if (!isset($headers[HttpHeaders::BCE_DATE])) {
            $now = new \DateTime();
            $now->setTimezone(DateUtils::$UTC_TIMEZONE);
            $headers[HttpHeaders::BCE_DATE] =
                DateUtils::formatAlternateIso8601Date($now);
        }
        list($hostUrl, $hostHeader) =
            HttpUtils::parseEndpointFromConfig($config);
        $headers[HttpHeaders::HOST] = $hostHeader;
        $url = $hostUrl . HttpUtils::urlEncodeExceptSlash($path);
        $queryString = HttpUtils::getCanonicalQueryString($params, false);
        if ($queryString !== '') {
            $url .= "?$queryString";
        }

        if (!isset($headers[HttpHeaders::CONTENT_LENGTH])) {
            $headers[HttpHeaders::CONTENT_LENGTH] =
                $this->guessContentLength($body);
        }
        $entityBody = null;
        if ($headers[HttpHeaders::CONTENT_LENGTH] == 0) {
            //if passing a stream and content length is 0, guzzle will remove
            //"Content-Length:0" from header, to work around this, we have to 
            //set body to a empty string
            $entityBody = "";
        } else if (is_resource($body)) {
            $offset = ftell($body);
            $original = EntityBody::factory($body);
            $entityBody = new ReadLimitEntityBody($original, $headers[HttpHeaders::CONTENT_LENGTH], $offset);
        } else {
            $entityBody = $body;
        }

        $credentials = $config[BceClientConfigOptions::CREDENTIALS];
        // if the request is send through the STS certification
        if(array_key_exists(BceClientConfigOptions::SESSION_TOKEN, $credentials)) {
            $headers[HttpHeaders::BCE_SESSION_TOKEN] = $credentials[BceClientConfigOptions::SESSION_TOKEN];
        }
        $headers[HttpHeaders::AUTHORIZATION] = $signer->sign(
            $credentials,
            $httpMethod,
            $path,
            $headers,
            $params,
            $options
        );

        if (LogFactory::isDebugEnabled()) {
            $this->logger->debug('HTTP method: ' . $httpMethod);
            $this->logger->debug('HTTP url: ' . $url);
            $this->logger->debug('HTTP headers: ' . print_r($headers, true));
        }

        $guzzleRequestOptions = array('exceptions' => false);
        if (isset(
            $config[BceClientConfigOptions::CONNECTION_TIMEOUT_IN_MILLIS])
        ) {
            $guzzleRequestOptions['connect_timeout'] =
                $config[BceClientConfigOptions::CONNECTION_TIMEOUT_IN_MILLIS]
                    / 1000.0;
        }
        if (isset(
            $config[BceClientConfigOptions::SOCKET_TIMEOUT_IN_MILLIS])
        ) {
            $guzzleRequestOptions['timeout'] =
                $config[BceClientConfigOptions::SOCKET_TIMEOUT_IN_MILLIS]
                    / 1000.0;
        }
        $guzzleRequest =
            $this->guzzleClient->createRequest(
                $httpMethod,
                $url,
                $headers,
                $entityBody,
                $guzzleRequestOptions
            );
        if ($outputStream !== null) {
            $guzzleRequest->setResponseBody($outputStream);
        }

        // Send request
        try {
            $guzzleResponse = $this->guzzleClient->send($guzzleRequest);
        } catch (Throwable  $e) {
                    $this->logger->warning(
                        'Fail to parse error response body: '
                        . $e->getMessage());
        }

        //statusCode < 200
        if ($guzzleResponse->isInformational()) {
            throw new BceClientException('Can not handle 1xx Http status code');
        }
        //for chunked http response, http status code can not be trust
        //error code in http body also mean a failed http response
        if ($guzzleResponse->getTransferEncoding() === 'chunked') {
            if ($guzzleResponse->isContentType('json')) {
                $responseBody = $guzzleResponse->json();
                if (isset($responseBody['code']) && $responseBody['code'] === 'InternalError') {
                  $guzzleResponse->setStatus(500);
                }
            }
        }
        //Successful means 2XX or 304
        if (!$guzzleResponse->isSuccessful()) {
            $requestId = $guzzleResponse->getHeader(HttpHeaders::BCE_REQUEST_ID);
            $message = $guzzleResponse->getReasonPhrase();
            $code = null;
            if ($guzzleResponse->isContentType('json')) {
                try {
                    $responseBody = $guzzleResponse->json();
                    if (isset($responseBody['message'])) {
                        $message = $responseBody['message'];
                    }
                    if (isset($responseBody['code'])) {
                        $code = $responseBody['code'];
                    }
                } catch (\Exception $e) {
                    // ignore this error
                    $this->logger->warning(
                        'Fail to parse error response body: '
                        . $e->getMessage()
                    );
                }
            }
            throw new BceServiceException(
                $requestId,
                $code,
                $message,
                $guzzleResponse->getStatusCode()
            );
        }
        if ($outputStream === null) {
            $body = $guzzleResponse->getBody(true);
        } else {
            $body = null;
            // detach the stream so that it will not be closed when the response
            // is garbage collected.
            $guzzleResponse->getBody()->detachStream();
        }
        return array(
            'headers' => $this->parseHeaders($guzzleResponse),
            'body' => $body
        );
    }

    /**
     * @param \Guzzle\Http\Message\Response $guzzleResponse
     * @return array
     */
    private function parseHeaders($guzzleResponse)
    {
        $responseHeaders = array();
        foreach ($guzzleResponse->getHeaders() as $header) {
            $value = $header->toArray();
            $responseHeaders[$header->getName()] = $value[0];
        }
        return $responseHeaders;
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Http;

use BaiduBce\Log\LogFactory;
use Guzzle\Log\AbstractLogAdapter;
use Psr\Log\LogLevel;

class GuzzleLogAdapter extends AbstractLogAdapter
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Constructs a new GuzzleLogAdapter instance.
     */
    public function __construct()
    {
        $this->logger = LogFactory::getLogger('HTTP');
    }

    /**
     * Logs the message.
     *
     * @param string $message the log message
     * @param int $priority the log level
     * @param array $extras extra arguments
     */
    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        // All guzzle logs should be DEBUG, regardless of its own priority.
        if (LogFactory::isDebugEnabled()) {
            // To avoid memory exhausted, truncate request or response longer than 1024 bytes.
            if(strlen($extras['request']) > 1024){
                $extras['request'] = substr($extras['request'], 0, 1024);
            }
            if(strlen($extras['response']) > 1024){
                $extras['response'] = substr($extras['response'], 0, 1024);
            }
            $this->logger->log(LogLevel::DEBUG, $message, $extras);
        }
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Http;

class HttpMethod
{
    const GET = 'GET';
    const PUT = 'PUT';
    const POST = 'POST';
    const DELETE = 'DELETE';
    const HEAD = 'HEAD';
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce;

class BceClientConfigOptions
{
    const CONNECTION_TIMEOUT_IN_MILLIS = 'connectionTimeoutInMillis';
    const SOCKET_TIMEOUT_IN_MILLIS = 'socketTimeoutInMillis';
    const PROTOCOL = 'protocol';
    const REGION = 'region';
    const ENDPOINT = 'endpoint';
    const CUSTOM = 'custom';
    const CREDENTIALS = 'credentials';
    const RETRY_POLICY = 'retryPolicy';
    const SEND_BUF_SIZE = 'sendBufSize';
    const RECV_BUF_SIZE = 'recvBufSize';
    const SESSION_TOKEN = 'sessionToken';
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Log;

use Psr\Log\NullLogger;

/**
 * A LogFactory that returns a NullLogger.
 */
class NullLogFactory implements LogFactoryInterface
{
    /**
     * Always returns a NullLogger.
     *
     * @param string $name the name of logger
     * @return Psr\Log\NullLogger a NullLogger
     */
    public function getLogger($name)
    {
        return new NullLogger();
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Log;

use Psr\Log\LoggerInterface;


/**
 * The global LogFactory for the SDK.
 */
class LogFactory
{
    /**
     * @var LogFactoryInterface the LogFactory instance
     */
    private static $instance;

    private static $logLevel;

    private static $logLevelMapping;

    public static function __init()
    {
        LogFactory::$instance = new NullLogFactory();
        LogFactory::$logLevelMapping = array(
            'emergency' => 0,
            'alert' => 1,
            'critical' => 2,
            'error' => 3,
            'warning' => 4,
            'notice' => 5,
            'info' => 6,
            'debug' => 7
        );
        LogFactory::$logLevel = 6;
    }

    /**
     * @param LogFactoryInterface $logFactory the logFactory interface.
     * @throws \InvalidArgumentException if $logFactory is null.
     */
    public static function setInstance(LogFactoryInterface $logFactory)
    {
        if ($logFactory === null) {
            throw new \InvalidArgumentException(
                '$logFactory should not be null.'
            );
        }
        LogFactory::$instance = $logFactory;
    }


    /**
     * @param string $logLevel the log level. The value can be 'emergency',
     *     'alert', 'critical', 'error', 'warning', 'notice', 'info', or
     *     'debug'.
     * @throws \InvalidArgumentException if no such a log level is defined.
     */
    public static function setLogLevel($logLevel)
    {
        if (isset(LogFactory::$logLevelMapping[$logLevel])) {
            LogFactory::$logLevel = LogFactory::$logLevelMapping[$logLevel];
        } else {
            throw new \InvalidArgumentException(
                "Unrecognized log level $logLevel"
            );
        }
    }

    /**
     * @return boolean true if the debug log level is enabled.
     */
    public static function isDebugEnabled()
    {
        return LogFactory::$logLevel >= 7;
    }

    /**
     * @param $name string the name of logger
     * @return LoggerInterface the Logger instance
     */
    public static function getLogger($name)
    {
        return LogFactory::$instance->getLogger($name);
    }
}

LogFactory::__init();
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Log;

use Monolog\Handler\HandlerInterface;
use Monolog\Logger;


/**
 * A LogFactory for Monolog.
 */
class MonoLogFactory implements LogFactoryInterface
{
    /**
     * @var array
     */
    private $handlers;

    /**
     * Constructs a new MonoLogFactory instance.
     *
     * @param array $handlers log handlers
     */
    public function __construct(array $handlers = null)
    {
        $this->handlers = $handlers;
    }

    /**
     * Returns \Monolog\Logger.
     *
     * @param string $name the name of logger
     * @return \Monolog\Logger a monolog logger instance
     */
    public function getLogger($name)
    {
        $logger = new Logger($name);
        if ($this->handlers !== null) {
            foreach ($this->handlers as $handler) {
                $logger->pushHandler($handler);
            }
        }
        return $logger;
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Log;

use Psr\Log\LoggerInterface;

interface LogFactoryInterface
{
    /**
     * @param $name string
     * @return LoggerInterface
     */
    public function getLogger($name);
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce;

use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosOptions;
use BaiduBce\Util\StringUtils;

class BceBaseClient
{
    private $serviceId;
    private $regionSupported;
    protected $config;

    /**
     * @param mixed $config the client configuration. The constructor makes a
     * copy of this parameter so that it is safe to change the configuration
     * after then.
     * @param string $serviceId The service id, such as Bos, ses, sms and so
     * on.
     * @param boolean $regionSupported true if this client supports region.
     */
    public function __construct($config, $serviceId, $regionSupported = true)
    {
        $this->config = array_merge(array(), Bce::getDefaultConfig(), $config);
        $this->serviceId = $serviceId;
        $this->regionSupported = $regionSupported;
        if (!isset($this->config[BceClientConfigOptions::ENDPOINT])) {
            $this->config[BceClientConfigOptions::ENDPOINT] =
                $this->computeEndpoint();
        }
    }

    /**
     * @param string $jsonString
     * @return \stdClass
     * @throws BceClientException
     */
    protected static function parseJsonResult($jsonString)
    {
        $result = null;
        if (strcmp($jsonString, "") == 0) {
            return new \stdClass();
        }

        $result = json_decode($jsonString);
        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new BceClientException(
                'Invalid json in response body: ' . json_last_error_msg()
            );
        }

        if ($result === null) {
            $result = new \stdClass();
        }
        return $result;
    }

    /**
     * @param array $headers
     */
    protected static function convertHttpHeadersToMetadata(array $headers)
    {
        $metadata = array();
        if (isset($headers[HttpHeaders::CONTENT_TYPE])) {
            $metadata[BosOptions::CONTENT_TYPE] =
                $headers[HttpHeaders::CONTENT_TYPE];
        }
        if (isset($headers[HttpHeaders::CONTENT_LENGTH])) {
            $metadata[BosOptions::CONTENT_LENGTH] =
                (int) $headers[HttpHeaders::CONTENT_LENGTH];
        }
        if (isset($headers[HttpHeaders::CONTENT_MD5])) {
            $metadata[BosOptions::CONTENT_MD5] =
                $headers[HttpHeaders::CONTENT_MD5];
        }
        if (isset($headers[HttpHeaders::DATE])) {
            $metadata[BosOptions::DATE] =
                \DateTime::createFromFormat(
                    \DateTime::RFC2822,
                    $headers[HttpHeaders::DATE]
                );
        }
        if (isset($headers[HttpHeaders::ETAG])) {
            $metadata[BosOptions::ETAG] =
                trim($headers[HttpHeaders::ETAG], '"');
        }
        if (isset($headers[HttpHeaders::LAST_MODIFIED])) {
            $metadata[BosOptions::LAST_MODIFIED] =
                \DateTime::createFromFormat(
                    \DateTime::RFC2822,
                    $headers[HttpHeaders::LAST_MODIFIED]
                );
        }
        if (isset($headers[HttpHeaders::BCE_STORAGE_CLASS])) {
            $metadata[BosOptions::STORAGE_CLASS] =
              trim($headers[HttpHeaders::BCE_STORAGE_CLASS], '"');
        }
        if (isset($headers[HttpHeaders::NEXT_APPEND_OFFSET])) {
            $metadata[BosOptions::NEXT_APPEND_OFFSET] = 
                $headers[HttpHeaders::NEXT_APPEND_OFFSET];
        }
        if (isset($headers[HttpHeaders::BCE_OBJECT_TYPE])) {
            $metadata[BosOptions::BCE_OBJECT_TYPE] = 
                $headers[HttpHeaders::BCE_OBJECT_TYPE];
        }
        if (isset($headers[HttpHeaders::BCE_CONTENT_CRC32])) {
            $metadata[BosOptions::CONTENT_CRC32] =
                (int)$headers[HttpHeaders::BCE_CONTENT_CRC32];
        }
        if (isset($headers[HttpHeaders::CONTENT_DISPOSITION])) {
            $metadata[BosOptions::CONTENT_DISPOSITION] =
                $headers[HttpHeaders::CONTENT_DISPOSITION];
        }
        if (isset($headers[HttpHeaders::EXPIRES])) {
            $metadata[BosOptions::EXPIRES] =
                $headers[HttpHeaders::EXPIRES];
        }
        if (isset($headers[HttpHeaders::CACHE_CONTROL])) {
            $metadata[BosOptions::CACHE_CONTROL] =
                $headers[HttpHeaders::CACHE_CONTROL];
        }
        if (isset($headers[HttpHeaders::LOCATION])) {
            $metadata[BosOptions::LOCATION] =
                $headers[HttpHeaders::LOCATION];
        }
        if (isset($headers[HttpHeaders::BCE_SYMLINK_TARGET])) {
            $metadata[BosOptions::BCE_SYMLINK_TARGET] =
                $headers[HttpHeaders::BCE_SYMLINK_TARGET];
        }
        return $metadata;
    }

    /** return the elements which array_slice(func_get_args(), 1) contains from options
     * throw exception when there are unexpected options.
     * @param array $options
     * @return array $result
     */
    protected function parseOptions(array $options) {
        return $this->doParseOptions(
            $options,
            array_slice(func_get_args(), 1),
            false
        );
    }

    /** return the elements which array_slice(func_get_args(), 1) contains from options
     * @param array $options
     * @return array $result
     */
    protected function parseOptionsIgnoreExtra(array $options) {
        return $this->doParseOptions(
            $options,
            array_slice(func_get_args(), 1),
            true
        );
    }

    private function doParseOptions(
        array $options,
        array $args,
        $allowExtraOptions
    ) {
        $result = array();
        foreach ($args as $arg) {
            if (isset($options[$arg])) {
                $result[] = $options[$arg];
                unset($options[$arg]);
            } else {
                $result[] = null;
            }
        }
        if (!$allowExtraOptions && count($options) > 0) {
            throw new \InvalidArgumentException(
                'Unexpected options:' . implode(',', array_keys($options))
                . ' Acceptable options are:' . implode(',', $args)
            );
        }
        return $result;
    }

    /**
     * compute endpoint based on the configuration and service id
     * @return string The endpoint
     */
    private function computeEndpoint()
    {
        $protocol = $this->config[BceClientConfigOptions::PROTOCOL];
        if ($this->regionSupported) {
            return sprintf(
                '%s://%s.%s.%s',
                $protocol,
                $this->serviceId,
                $this->config[BceClientConfigOptions::REGION],
                Bce::DEFAULT_SERVICE_DOMAIN
            );
        } else {
            return sprintf(
                '%s://%s.%s',
                $protocol,
                $this->serviceId,
                Bce::DEFAULT_SERVICE_DOMAIN
            );
        }
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Exception;


class BceBaseException extends \Exception
{
    /**
     * Constructs a new BceBaseException instance.
     *
     * @param string $message the exception message
     */
    function __construct($message)
    {
        parent::__construct($message);
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Exception;

class BceServiceException extends BceBaseException
{
    /**
     * @var int
     */
    private $statusCode;

    /**
     * @var string
     */
    private $requestId;

    /**
     * @var int
     */
    private $errorCode;

    /**
     * Constructs a new BceServiceException instance.
     *
     * @param string $requestId the request id
     * @param string $errorCode the error code
     * @param string $errorMessage the error message
     * @param string $statusCode the status code
     */
    function __construct(
        $requestId,
        $errorCode,
        $errorMessage,
        $statusCode
    ) {
        $this->requestId = $requestId;
        $this->errorCode = $errorCode;
        $this->statusCode = $statusCode;
        if (is_array($errorMessage)) {
            $errorMessage = json_encode($errorMessage);
        }
        parent::__construct(
            "$errorMessage [requestId:$requestId "
            . "status:$statusCode code:$errorCode]"
        );
    }

    /**
     * @return string
     */
    public function getRequestId()
    {
        return $this->requestId;
    }

    /**
     * @return int
     */
    public function getErrorCode()
    {
        return $this->errorCode;
    }

    /**
     * @return int
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Exception;

class BceClientException extends BceBaseException
{
    /**
     * Constructs a new BceClientException instance.
     *
     * @param string $message the exception message
     */
    function __construct($message)
    {
        parent::__construct($message);
    }
} <?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Dcc;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;

/**
 * This module provides a client class for DCC.
 */
class DccClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The BccClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'dcc');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Return a list of dedicatedHosts owned by the authenticated user.
     *
     * @param string $zoneName
     *          the name of available zone.
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating DccClient instance.
     *
     * @return mixed
     */
    public function listDedicatedHosts($zoneName=null, $marker=null, $maxKeys=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        if ($zoneName !== null) {
            $params['zoneName'] = $zoneName;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/dedicatedHost'
        );
    }

    /**
     * Get the detail information of specified dedicatedHost.
     *
     * @param string $hostId
     *          The id of dedicatedHost
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating DccClient instance.
     *
     * @return mixed
     */
    public function getDedicatedHost($hostId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($hostId)) {
            throw new \InvalidArgumentException(
                'request $hostId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/dedicatedHost/' . $hostId
        );
    }


    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Blb;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\Blb\model\BackendServer;

/**
 * This module provides a client class for BLB.
 */
class BlbClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The BlbClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'blb');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an nat with the specified options.
     *
     * @param string $name
     *          name of nat
     *
     * @param string $vpcId
     *          id of vpc which nat created in
     *
     * @param string $subnetId
     *          id of subnet which blb created in
     *
     * @param string $desc
     *          description of blb
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createBlb($vpcId = null, $subnetId = null, $name = null, $desc = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if ($vpcId !== null) {
            $body['vpcId'] = $vpcId;
        }
        if ($subnetId !== null) {
            $body['subnetId'] = $subnetId;
        }
        if ($name !== null) {
            $body['name'] = $name;
        }
        if ($desc !== null) {
            $body['desc'] = $desc;
        }
        $body['end'] = '';
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb'
        );
    }

    /**
     * get a list of blb owned by the authenticated user and specified conditions.
     *
     * @param string $address
     *          address of blb in vpc. The optional parameter
     *
     * @param string $blbId
     *          id of blb instance. The optional parameter
     *
     * @param string $name
     *          name of nat instance. The optional parameter
     *
     * @param string $bccId
     *          id of bcc instance which is bound to blb instance. The optional parameter
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listBlbs($address = null, $name = null, $blbId = null, $bccId = null, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($address !== null) {
            $params['address'] = $address;
        }
        if ($blbId !== null) {
            $params['blbId'] = $blbId;
        }
        if ($name !== null) {
            $params['name'] = $name;
        }
        if ($bccId !== null) {
            $params['bccId'] = $bccId;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb'
        );
    }

    /**
     * update single blb
     *
     * @param string $blbId
     *          id of blb instance
     *
     * @param string $name
     *          name of blb instance to be updated
     *
     * @param string $desc
     *          description of blb instance to be updated
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateBlb($blbId, $name = null, $desc = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if ($name !== null) {
            $body['name'] = $name;
        }
        if ($desc !== null) {
            $body['desc'] = $desc;
        }
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId
        );
    }

    /**
     * delete the blb
     * Only the Postpaid instance or Prepaid which is expired can be released.
     *
     * @param string $blbId
     *          id of blb instance to be released
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function deleteBlb($blbId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId
        );
    }

    /**
     * Create a tcp listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createTcpListener($blbId, $listenerPort, $backendPort, $scheduler, $healthCheckTimeoutInSecond = 3, $healthCheckInterval = 3, $unhealthyThreshold = 3, $healthyThreshold = 3, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['listenerPort'] = $listenerPort;
        $body['backendPort'] = $backendPort;
        $body['scheduler'] = $scheduler;
        $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        $body['healthCheckInterval'] = $healthCheckInterval;
        $body['unhealthyThreshold'] = $unhealthyThreshold;
        $body['healthyThreshold'] = $healthyThreshold;
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/TCPlistener'
        );
    }

    /**
     * Create a udp listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param string $healthCheckString
     *          string to send for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createUdpListener($blbId, $listenerPort, $backendPort, $scheduler, $healthCheckString, $healthCheckTimeoutInSecond = 3, $healthCheckInterval = 3, $unhealthyThreshold = 3, $healthyThreshold = 3, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['listenerPort'] = $listenerPort;
        $body['backendPort'] = $backendPort;
        $body['scheduler'] = $scheduler;
        $body['healthCheckString'] = $healthCheckString;
        $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        $body['healthCheckInterval'] = $healthCheckInterval;
        $body['unhealthyThreshold'] = $unhealthyThreshold;
        $body['healthyThreshold'] = $healthyThreshold;
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/UDPlistener'
        );
    }

    /**
     * Create a http listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param boolean $keepSession
     *          switch for keep session
     *
     * @param string $keepSessionType
     *          type to keep session
     *
     * @param int $keepSessionDuration
     *          duration to keep session
     *
     * @param string $keepSessionCookieName
     *          cookie name for keep session
     *
     * @param boolean $xForwardFor
     *          switch for acquiring real ip
     *
     * @param string $healthCheckType
     *          type for health check
     *
     * @param int $healthCheckPort
     *          port for health check
     *
     * @param string $healthCheckURI
     *          uri for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $healthCheckNormalStatus
     *          normal status for http health check
     *
     * @param int $serverTimeout
     *          timeout for backend server
     *
     * @param int $redirectPort
     *          port for redirect
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createHttpListener($blbId, $listenerPort, $backendPort, $scheduler, $keepSession = false,
                                       $keepSessionType = null, $keepSessionDuration = 3600, $keepSessionCookieName = null,
                                       $xForwardFor = false, $healthCheckType = null, $healthCheckPort = null, $healthCheckURI = null,
                                       $healthCheckTimeoutInSecond = 3, $healthCheckInterval = 3, $unhealthyThreshold = 3, $healthyThreshold = 3,
                                       $healthCheckNormalStatus = null, $serverTimeout = 30, $redirectPort = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['listenerPort'] = $listenerPort;
        $body['backendPort'] = $backendPort;
        $body['scheduler'] = $scheduler;
        if ($keepSession !== null) {
            $body['keepSession'] = $keepSession;
        }
        if ($keepSessionType !== null) {
            $body['keepSessionType'] = $keepSessionType;
        }
        if ($keepSessionDuration !== null) {
            $body['keepSessionDuration'] = $keepSessionDuration;
        }
        if ($keepSessionCookieName !== null) {
            $body['keepSessionCookieName'] = $keepSessionCookieName;
        }
        if ($xForwardFor !== null) {
            $body['xForwardFor'] = $xForwardFor;
        }
        if ($healthCheckType !== null) {
            $body['healthCheckType'] = $healthCheckType;
        }
        if ($healthCheckPort !== null) {
            $body['healthCheckPort'] = $healthCheckPort;
        }
        if ($healthCheckURI !== null) {
            $body['healthCheckURI'] = $healthCheckURI;
        }
        if ($healthCheckNormalStatus !== null) {
            $body['healthCheckNormalStatus'] = $healthCheckNormalStatus;
        }
        if ($serverTimeout !== null) {
            $body['serverTimeout'] = $serverTimeout;
        }
        if ($redirectPort !== null) {
            $body['redirectPort'] = $redirectPort;
        }
        $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        $body['healthCheckInterval'] = $healthCheckInterval;
        $body['unhealthyThreshold'] = $unhealthyThreshold;
        $body['healthyThreshold'] = $healthyThreshold;
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/HTTPlistener'
        );
    }

    /**
     * Create a https listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param array $certIds
     *          SSL certs for listener
     *
     * @param boolean $keepSession
     *          switch for keep session
     *
     * @param string $keepSessionType
     *          type to keep session
     *
     * @param int $keepSessionDuration
     *          duration to keep session
     *
     * @param string $keepSessionCookieName
     *          cookie name for keep session
     *
     * @param boolean $xForwardFor
     *          switch for acquiring real ip
     *
     * @param string $healthCheckType
     *          type for health check
     *
     * @param int $healthCheckPort
     *          port for health check
     *
     * @param string $healthCheckURI
     *          uri for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $healthCheckNormalStatus
     *          normal status for http health check
     *
     * @param int $serverTimeout
     *          timeout for backend server
     *
     * @param boolean $ie6Compatible
     *          switch for compatibility with IE6
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createHttpsListener($blbId, $listenerPort, $backendPort, $scheduler, $certIds, $keepSession = false,
                                        $keepSessionType = null, $keepSessionDuration = 3600, $keepSessionCookieName = null,
                                        $xForwardFor = false, $healthCheckType = null, $healthCheckPort = null, $healthCheckURI = null,
                                        $healthCheckTimeoutInSecond = 3, $healthCheckInterval = 3, $unhealthyThreshold = 3, $healthyThreshold = 3,
                                        $healthCheckNormalStatus = null, $serverTimeout = 30, $ie6Compatible = true, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['listenerPort'] = $listenerPort;
        $body['backendPort'] = $backendPort;
        $body['scheduler'] = $scheduler;
        $body['certIds'] = $this->objectToArray($certIds);
        if ($keepSession !== null) {
            $body['keepSession'] = $keepSession;
        }
        if ($keepSessionType !== null) {
            $body['keepSessionType'] = $keepSessionType;
        }
        if ($keepSessionDuration !== null) {
            $body['keepSessionDuration'] = $keepSessionDuration;
        }
        if ($keepSessionCookieName !== null) {
            $body['keepSessionCookieName'] = $keepSessionCookieName;
        }
        if ($xForwardFor !== null) {
            $body['xForwardFor'] = $xForwardFor;
        }
        if ($healthCheckType !== null) {
            $body['healthCheckType'] = $healthCheckType;
        }
        if ($healthCheckPort !== null) {
            $body['healthCheckPort'] = $healthCheckPort;
        }
        if ($healthCheckURI !== null) {
            $body['healthCheckURI'] = $healthCheckURI;
        }
        if ($healthCheckNormalStatus !== null) {
            $body['healthCheckNormalStatus'] = $healthCheckNormalStatus;
        }
        if ($serverTimeout !== null) {
            $body['serverTimeout'] = $serverTimeout;
        }
        if ($ie6Compatible !== null) {
            $body['ie6Compatible'] = $ie6Compatible;
        }
        $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        $body['healthCheckInterval'] = $healthCheckInterval;
        $body['unhealthyThreshold'] = $unhealthyThreshold;
        $body['healthyThreshold'] = $healthyThreshold;
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/HTTPSlistener'
        );
    }

    /**
     * list tcp listener.
     *
     * @param string $blbId
     *          id of blb instance
     *
     * @param int listenerPort
     *          port of listener
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listTcpListeners($blbId, $listenerPort = null, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($listenerPort !== null) {
            $params['listenerPort'] = $listenerPort;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/TCPlistener'
        );
    }

    /**
     * list udp listener.
     *
     * @param string $blbId
     *          id of blb instance
     *
     * @param int listenerPort
     *          port of listener
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listUdpListeners($blbId, $listenerPort = null, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($listenerPort !== null) {
            $params['listenerPort'] = $listenerPort;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/UDPlistener'
        );
    }

    /**
     * list http listener.
     *
     * @param string $blbId
     *          id of blb instance
     *
     * @param int listenerPort
     *          port of listener
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listHttpListeners($blbId, $listenerPort = null, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($listenerPort !== null) {
            $params['listenerPort'] = $listenerPort;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/HTTPlistener'
        );
    }

    /**
     * list https listener.
     *
     * @param string $blbId
     *          id of blb instance
     *
     * @param int listenerPort
     *          port of listener
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listHttpsListeners($blbId, $listenerPort = null, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($listenerPort !== null) {
            $params['listenerPort'] = $listenerPort;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/HTTPSlistener'
        );
    }

    /**
     * update a tcp listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateTcpListener($blbId, $listenerPort, $backendPort = null, $scheduler = null, $healthCheckTimeoutInSecond = null, $healthCheckInterval = null, $unhealthyThreshold = null, $healthyThreshold = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if ($backendPort !== null) {
            $body['backendPort'] = $backendPort;
        }
        if ($scheduler !== null) {
            $body['scheduler'] = $scheduler;
        }
        if ($healthCheckTimeoutInSecond !== null) {
            $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        }
        if ($healthCheckInterval !== null) {
            $body['healthCheckInterval'] = $healthCheckInterval;
        }
        if ($unhealthyThreshold !== null) {
            $body['unhealthyThreshold'] = $unhealthyThreshold;
        }
        if ($healthyThreshold !== null) {
            $body['healthyThreshold'] = $healthyThreshold;
        }
        $body['end'] = '';
        $params = array();
        $params['listenerPort'] = $listenerPort;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/TCPlistener'
        );
    }

    /**
     * update a udp listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param string $healthCheckString
     *          string to send for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateUdpListener($blbId, $listenerPort, $backendPort, $scheduler, $healthCheckString, $healthCheckTimeoutInSecond = null, $healthCheckInterval = null, $unhealthyThreshold = null, $healthyThreshold = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['backendPort'] = $backendPort;
        $body['scheduler'] = $scheduler;
        $body['healthCheckString'] = $healthCheckString;
        if ($healthCheckTimeoutInSecond !== null) {
            $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        }
        if ($healthCheckInterval !== null) {
            $body['healthCheckInterval'] = $healthCheckInterval;
        }
        if ($unhealthyThreshold !== null) {
            $body['unhealthyThreshold'] = $unhealthyThreshold;
        }
        if ($healthyThreshold !== null) {
            $body['healthyThreshold'] = $healthyThreshold;
        }
        $body['end'] = '';
        $params = array();
        $params['listenerPort'] = $listenerPort;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/UDPlistener'
        );
    }

    /**
     * update a http listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param boolean $keepSession
     *          switch for keep session
     *
     * @param string $keepSessionType
     *          type to keep session
     *
     * @param int $keepSessionDuration
     *          duration to keep session
     *
     * @param string $keepSessionCookieName
     *          cookie name for keep session
     *
     * @param boolean $xForwardFor
     *          switch for acquiring real ip
     *
     * @param string $healthCheckType
     *          type for health check
     *
     * @param int $healthCheckPort
     *          port for health check
     *
     * @param string $healthCheckURI
     *          uri for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $healthCheckNormalStatus
     *          normal status for http health check
     *
     * @param int $serverTimeout
     *          timeout for backend server
     *
     * @param int $redirectPort
     *          port for redirect
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateHttpListener($blbId, $listenerPort, $backendPort = null, $scheduler = null, $keepSession = null,
                                       $keepSessionType = null, $keepSessionDuration = null, $keepSessionCookieName = null,
                                       $xForwardFor = null, $healthCheckType = null, $healthCheckPort = null, $healthCheckURI = null,
                                       $healthCheckTimeoutInSecond = null, $healthCheckInterval = null, $unhealthyThreshold = null, $healthyThreshold = null,
                                       $healthCheckNormalStatus = null, $serverTimeout = null, $redirectPort = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if ($backendPort !== null) {
            $body['backendPort'] = $backendPort;
        }
        if ($scheduler !== null) {
            $body['scheduler'] = $scheduler;
        }
        if ($keepSession !== null) {
            $body['keepSession'] = $keepSession;
        }
        if ($keepSessionType !== null) {
            $body['keepSessionType'] = $keepSessionType;
        }
        if ($keepSessionDuration !== null) {
            $body['keepSessionDuration'] = $keepSessionDuration;
        }
        if ($keepSessionCookieName !== null) {
            $body['keepSessionCookieName'] = $keepSessionCookieName;
        }
        if ($xForwardFor !== null) {
            $body['xForwardFor'] = $xForwardFor;
        }
        if ($healthCheckType !== null) {
            $body['healthCheckType'] = $healthCheckType;
        }
        if ($healthCheckPort !== null) {
            $body['healthCheckPort'] = $healthCheckPort;
        }
        if ($healthCheckURI !== null) {
            $body['healthCheckURI'] = $healthCheckURI;
        }
        if ($healthCheckNormalStatus !== null) {
            $body['healthCheckNormalStatus'] = $healthCheckNormalStatus;
        }
        if ($serverTimeout !== null) {
            $body['serverTimeout'] = $serverTimeout;
        }
        if ($redirectPort !== null) {
            $body['redirectPort'] = $redirectPort;
        }
        if ($healthCheckTimeoutInSecond !== null) {
            $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        }
        if ($healthCheckInterval !== null) {
            $body['healthCheckInterval'] = $healthCheckInterval;
        }
        if ($unhealthyThreshold !== null) {
            $body['unhealthyThreshold'] = $unhealthyThreshold;
        }
        if ($healthyThreshold !== null) {
            $body['healthyThreshold'] = $healthyThreshold;
        }
        $body['end'] = '';
        $params = array();
        $params['listenerPort'] = $listenerPort;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/HTTPlistener'
        );
    }

    /**
     * update a https listener with the specified options.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param int $listenerPort
     *          front end port of listener
     *
     * @param int $backendPort
     *          back end port of listener
     *
     * @param string $scheduler
     *          scheduler of load balance
     *
     * @param array $certIds
     *          SSL certs for listener
     *
     * @param boolean $keepSession
     *          switch for keep session
     *
     * @param string $keepSessionType
     *          type to keep session
     *
     * @param int $keepSessionDuration
     *          duration to keep session
     *
     * @param string $keepSessionCookieName
     *          cookie name for keep session
     *
     * @param boolean $xForwardFor
     *          switch for acquiring real ip
     *
     * @param string $healthCheckType
     *          type for health check
     *
     * @param int $healthCheckPort
     *          port for health check
     *
     * @param string $healthCheckURI
     *          uri for health check
     *
     * @param int $healthCheckTimeoutInSecond
     *          timeout of health check, default 3 seconds
     *
     * @param int $healthCheckInterval
     *          interval of health check, default 3 seconds
     *
     * @param int $unhealthyThreshold
     *          times threshold of unhealthy check, default 3 times
     *
     * @param int $healthyThreshold
     *          times threshold of healthy check, default 3 times
     *
     * @param string $healthCheckNormalStatus
     *          normal status for http health check
     *
     * @param int $serverTimeout
     *          timeout for backend server
     *
     * @param boolean $ie6Compatible
     *          switch for compatibility with IE6
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateHttpsListener($blbId, $listenerPort, $backendPort = null, $scheduler = null, $certIds = null, $keepSession = null,
                                        $keepSessionType = null, $keepSessionDuration = null, $keepSessionCookieName = null,
                                        $xForwardFor = null, $healthCheckType = null, $healthCheckPort = null, $healthCheckURI = null,
                                        $healthCheckTimeoutInSecond = null, $healthCheckInterval = null, $unhealthyThreshold = null, $healthyThreshold = null,
                                        $healthCheckNormalStatus = null, $serverTimeout = null, $ie6Compatible = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if ($backendPort !== null) {
            $body['backendPort'] = $backendPort;
        }
        if ($scheduler !== null) {
            $body['scheduler'] = $scheduler;
        }
        if ($certIds !== null) {
            $body['certIds'] = $this->objectToArray($certIds);
        }
        if ($keepSession !== null) {
            $body['keepSession'] = $keepSession;
        }
        if ($keepSessionType !== null) {
            $body['keepSessionType'] = $keepSessionType;
        }
        if ($keepSessionDuration !== null) {
            $body['keepSessionDuration'] = $keepSessionDuration;
        }
        if ($keepSessionCookieName !== null) {
            $body['keepSessionCookieName'] = $keepSessionCookieName;
        }
        if ($xForwardFor !== null) {
            $body['xForwardFor'] = $xForwardFor;
        }
        if ($healthCheckType !== null) {
            $body['healthCheckType'] = $healthCheckType;
        }
        if ($healthCheckPort !== null) {
            $body['healthCheckPort'] = $healthCheckPort;
        }
        if ($healthCheckURI !== null) {
            $body['healthCheckURI'] = $healthCheckURI;
        }
        if ($healthCheckNormalStatus !== null) {
            $body['healthCheckNormalStatus'] = $healthCheckNormalStatus;
        }
        if ($serverTimeout !== null) {
            $body['serverTimeout'] = $serverTimeout;
        }
        if ($ie6Compatible !== null) {
            $body['ie6Compatible'] = $ie6Compatible;
        }
        if ($healthCheckTimeoutInSecond !== null) {
            $body['healthCheckTimeoutInSecond'] = $healthCheckTimeoutInSecond;
        }
        if ($healthCheckInterval !== null) {
            $body['healthCheckInterval'] = $healthCheckInterval;
        }
        if ($unhealthyThreshold !== null) {
            $body['unhealthyThreshold'] = $unhealthyThreshold;
        }
        if ($healthyThreshold !== null) {
            $body['healthyThreshold'] = $healthyThreshold;
        }
        $body['end'] = '';
        $params = array();
        $params['listenerPort'] = $listenerPort;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/HTTPSlistener'
        );
    }

    /**
     * delete a listener.
     *
     * @param string $blbId
     *          id of blb
     *
     * @param array $portList
     *          ports of listener to be deleted
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function deleteListeners($blbId, $portList, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['portList'] = $this->objectToArray($portList);
        $params = array();
        $params['batchdelete'] = '';
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/listener'
        );
    }

    /**
     * add backend server
     *
     * @param string $blbId
     *          blb instance id
     *
     * @param array $backendServerList
     *          back end servers to be added
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function addBackendServer($blbId, $backendServerList, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['backendServerList'] = $this->objectToArray($backendServerList);
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/backendserver'
        );
    }

    /**
     * list backend servers mounted with blb instance. Health Status will be presented while listener port is necessary
     *
     * @param string $blbId
     *          blb instance id
     *
     * @param int listenerPort
     *          port of listener
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listBackendServersWithPort($blbId, $listenerPort, $marker = null, $maxKeys = 1000, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        $params['listenerPort'] = $listenerPort;
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/backendserver'
        );
    }

    /**
     * list backend servers mounted with blb instance
     *
     * @param string $blbId
     *          blb instance id
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listBackendServers($blbId, $marker = null, $maxKeys = 1000, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/blb/' . $blbId . '/backendserver'
        );
    }

    /**
     * update weight of backend servers
     *
     * @param string $blbId
     *          blb instance id
     *
     * @param array $backendServerList
     *          back end servers to be updated
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function updateBackendServer($blbId, $backendServerList, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['backendServerList'] = $this->objectToArray($backendServerList);
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        $params['update'] = '';
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/backendserver'
        );
    }

    /**
     * remove backend servers
     *
     * @param string $blbId
     *          blb instance id
     *
     * @param array $backendServerList
     *          back end servers to be removed
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function removeBackendServers($blbId, $backendServerList, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['backendServerList'] = $this->objectToArray($backendServerList);
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/blb/' . $blbId . '/backendserver'
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Blb\model;

class BackendServer
{
    var $instanceId;
    var $weight;

    /**
     * BackendServer constructor.
     *
     * @param int $weight
     * @param string $instanceId
     */
    function __construct($instanceId, $weight)
    {
        $this->instanceId = $instanceId;
        $this->weight = $weight;
    }
}<?php
/**
 * Created by IntelliJ IDEA.
 * User: zhangjing60
 * Date: 17/8/14
 * Time: 下午4:15
 */

namespace BaiduBce\Services\Route;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;

class RouteClient extends BceBaseClient {
    
    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * RouteClient constructor.
     * @param array $config
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'route');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * @param string $routeTableId  
     *        The id of the route table
     * 
     * @param string $clientToken 
     *         if the clientToken is not specified by the user, a random String
     *         generated by default algorithm will be used.
     * 
     * @param string $sourceAddress
     *        the source address of the route 
     * 
     * @param string $destinationAddress
     *         the destination address of the route
     * 
     * @param string $nexthopId
     *        the next hop id
     *        when the nexthopType is "defaultGateway",this field can be empty
     * 
     * @param string $nexthopType
     *        route type
     *        the Bcc type is "custom";
     *        the VPN type is "VPN";
     *        the NAT type is "NAT";
     *        the local gateway type is "defaultGateway"
     * 
     * @param string $description
     *        the option param to describe the route table
     * 
     * @param array $options
     *        The optional bce configuration, which will overwrite the
     *         default configuration that was passed while creating EipClient instance.
     * 
     * @return mixed
     * 
     */
    public function createRouteRule($routeTableId,  $sourceAddress, $destinationAddress,
    $nexthopType, $description, $nexthopId = null, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($routeTableId)) {
            throw new \InvalidArgumentException(
                'request $routeTableId  should not be empty .'
            );
        }
        if (empty($sourceAddress)) {
            throw new \InvalidArgumentException(
                'request $sourceAddress  should not be empty .'
            );
        }
        if (empty($destinationAddress)) {
            throw new \InvalidArgumentException(
                'request $destinationAddress  should not be empty .'
            );
        }
        if (empty($nexthopType)) {
            throw new \InvalidArgumentException(
                'request $nexthopType  should not be empty .'
            );
        }
        if (empty($description)) {
            throw new \InvalidArgumentException(
                'request $descrption  should not be empty .'
            );
        }
        $body['routeTableId'] = $routeTableId;
        $body['sourceAddress'] = $sourceAddress;
        $body['destinationAddress'] = $destinationAddress;
        $body['nexthopId'] = $nexthopId;
        $body['nexthopType'] = $nexthopType;
        $body['description'] = $description;
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/route/rule'
        );
        
    }

    /**
     * @param string $routeTableId
     *        the id of the route table
     *        vpcId and routeTableId cannot be empty at the same time
     * 
     * @param string $vpcId
     *        the vpc id 
     *        vpcId and routeTableId cannot be empty at the same time 
     * 
     * @param array $options
     *        The optional bce configuration, which will overwrite the
     *         default configuration that was passed while creating EipClient instance.
     * 
     * @return mixed
     * 
     */
    public function getRouteTable( $vpcId = null, $routeTableId = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($routeTableId)  && empty($vpcId )) {
            throw new \InvalidArgumentException(
                'request $routeTableId and $vpcId should not be empty at the same time.'
            );
        }
        if (!empty($routeTableId)) {
            $params['routeTableId'] = $routeTableId;
        }
        if (!empty($vpcId)) {
            $params['vpcId'] = $vpcId;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/route'
        );

    }

    /**
     * @param string $routeTableId
     *        the id of the specified route table
     * @param string $clientToken
     *        if the clientToken is not specified by the user, a random String
     *         generated by default algorithm will be used.
     * 
     * @param array $options
     *        The optional bce configuration, which will overwrite the
     *         default configuration that was passed while creating EipClient instance.
     * 
     * @return mixed
     * 
     */
    public function deleteRouteRule($routeRuleId, $clientToken = null, $options = array()) {
        $params = array();
        list($config) = $this->parseOptions($options, 'config');
        if(empty($routeRuleId) ) {
            throw new \InvalidArgumentException(
                'request $routeRuleId should not be empty.'
            );
        }
        // $params['routeRuleId'] = $routeRuleId;
        
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/route/rule/' .$routeRuleId
        );
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright 2021 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\EipTp;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;


/**
 * This module provides a client class for EipTp.
 */
class EipTpClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The EipTpClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'eiptp');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an eiptp with the specified options.
     *
     * @param int $reservationLength
     *          The reservation length of the eiptp including 1, 6 and 12 months.
     *
     * @param string $capacity
     *          The capacity of the eiptp.
     *          When reservationLength = 1 => capacity: {"10G"/"50G"/"100G"/"500G"/"1T"/"5T"/"10T"/"50T"}
     *          When reservationLength = 6 => capacity: {"60G"/"300G"/"600G"/"3T"/"6T"/"30T"/"60T"/"300T"}
     *          When reservationLength = 12 => capacity: {"1T"/"10T"/"50T"/"100T"/"500T"/"1P"}
     *
     * @param string $deductPolicy
     *          The deduct policy of the eiptp including "FullTimeDurationPackage" and "TimeDurationPackage".
     *          The default deduct policy is "FullTimeDurationPackage", the optional parameter.
     *
     * @param string $packageType
     *          The eiptp package type.
     *          The default package type is "WebOutBytes", the optional parameter.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */

    public function createEipTp($reservationLength, $capacity,
                                $deductPolicy = null, $packageType = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($reservationLength)) {
            throw new \InvalidArgumentException(
                'request $reservationLength should not be empty.'
            );
        }
        if (empty($capacity)) {
            throw new \InvalidArgumentException(
                'request $capacity should not be empty.'
            );
        }
        $body['reservationLength'] = $reservationLength;
        $body['capacity'] = $capacity;
        if (!empty($deductPolicy)) {
            $body['deductPolicy'] = $deductPolicy;
        }
        if (!empty($packageType)) {
            $body['packageType'] = $packageType;
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eiptp'
        );
    }

    /**
     * Get detail of the eiptp by the passed id.
     *
     * @param string $id
     *          the eiptp id for query.
     *
     * @return mixed
     */
    public function getEipTp($id, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config
            ),
            '/eiptp/' . $id
        );
    }

    /**
     * Get a list of eiptp owned by the authenticated user filtered by specific conditions.
     *
     * @param string $id
     *          eiptp's id condition, the optional parameter.
     *
     * @param string $deductPolicy
     *          eiptp's deduct policy condition, "FullTimeDurationPackage" or "TimeDurationPackage", the optional parameter.
     *
     * @param string $status
     *          eiptp's status condition, "RUNNING", "EXPIRED" or "USED_UP", the optional parameter.
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function listEipTps($id = null, $deductPolicy = null, $status = null, $marker = null, $maxKeys = 1000,
                               $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($id !== null) {
            $params['id'] = $id;
        }
        if ($deductPolicy !== null) {
            $params['deductPolicy'] = $deductPolicy;
        }
        if ($status !== null) {
            $params['status'] = $status;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eiptp'
        );
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Sms;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\Auth\SignOptions;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Exception\BceServiceException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;

class SmsClient extends BceBaseClient
{
    private $signer;
    private $httpClient;

    /**
     * SmsClient constructor.
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'SmsClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
        date_default_timezone_set("UTC");
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @throws BceClientException
     * @throws BceServiceException
     * @return mixed
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);

        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        // 自定义签名内容
        $options[SignOptions::HEADERS_TO_SIGN]= array(
            strtolower(HttpHeaders::HOST) => strtolower(HttpHeaders::HOST),
            strtolower(HttpHeaders::BCE_DATE) => strtolower(HttpHeaders::BCE_DATE),
        );

        $path = $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer,
            null,
            $options
        );

        $result = $this->parseJsonResult($response['body']);
        $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
        return $result;
    }

    /**
     * check Template Param
     *
     * @param $name
     * @param $content
     * @param $smsType
     * @param $countryType
     * @throws BceClientException
     * @return void
     */
    private function checkTemplateParam($name, $content, $smsType, $countryType)
    {
        if (empty($name)) {
            throw new BceClientException("name should not be null or empty");
        }

        if (empty($content)) {
            throw new BceClientException("content should not be null or empty");
        }

        if (empty($smsType)) {
            throw new BceClientException("smsType should not be null or empty");
        }

        if (empty($countryType)) {
            throw new BceClientException("countryType should not be null or empty");
        }
    }

    /**
     * check Signature Param
     *
     * @param $content
     * @param $contentType
     * @param $countryType
     * @throws BceClientException
     * @return void
     */
    private function checkSignatureParam($content, $contentType, $countryType)
    {
        if (empty($content)) {
            throw new BceClientException("content should not be null or empty");
        }

        if (empty($contentType)) {
            throw new BceClientException("contentType should not be null or empty");
        }

        if (empty($countryType)) {
            throw new BceClientException("countryType should not be null or empty");
        }
    }

    /**
     * Get clientToken
     *
     * @return string
     */
    private function getClientToken()
    {
        return md5(uniqid(mt_rand(), true));
    }

    /**
     * Send the sms message v3
     *
     * @param String $mobile 手机号码,支持单个或多个手机号,多个手机号之间以英文逗号分隔,e.g. 13800138000,13800138001,一次请求最多支持200个手机号
     * @param String $signatureId 短信签名,需在平台申请,并审核通过后方可使用
     * @param String $templateId 短信模板ID,模板申请成功后自动创建,全局内唯一。e.g. smsTpl:6nHdNumZ4ZtGaKO
     * @param array $contentVar 模板变量内容,用于替换短信模板中定义的变量,为json字符串格式
     *        array('content' => '您的验证码为123456')
     * @param String $custom option: The user self defined param
     * @param String $userExtId option: The user self defined channel code
     * @param String $merchantUrlId option: The id of callback url specified by user
     * @param String $clientToken option: The parameter for idempotence of http post
     * @param array $options
     * @throws BceClientException
     */
    public function sendMessage($mobile, $signatureId, $templateId, $contentVar, $custom = null, $userExtId = null,
                                $merchantUrlId = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam = array();

        if (empty($mobile)) {
            throw new BceClientException("The parameter mobile "
                ."should NOT be null or empty string");
        }
        $requestParam['mobile'] = $mobile;

        if (empty($signatureId)) {
            throw new BceClientException("The parameter signatureId "
                ."should NOT be null or empty string");
        }
        $requestParam['signatureId'] = $signatureId;

        if (empty($templateId)) {
            throw new BceClientException("The parameter templateId "
                ."should NOT be null or empty string");
        }
        $requestParam['template'] = $templateId;

        if (empty($contentVar)) {
            throw new BceClientException("The parameter contentVar "
                ."should NOT be null or empty string");
        }
        $requestParam['contentVar'] = $contentVar;

        if (!empty($custom)) {
            $requestParam['custom'] = $custom;
        }

        if (!empty($userExtId)) {
            $requestParam['userExtId'] = $userExtId;
        }

        if (!empty($merchantUrlId)) {
            $requestParam['merchantUrlId'] = $merchantUrlId;
        }

        $params = array();
        if (!empty($clientToken)) {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($requestParam),
                'params' => $params
            ),
            '/api/v3/sendsms'
        );
    }

    /**
     * Create message template
     *
     * @param String $name Template's name
     * @param String $content Template's content
     * @param String $smsType The sms type of the template content
     * @param String $countryType The countryType indicates the countries or regions in which the template can be used.
     *        The value of countryType could be DOMESTIC or INTERNATIONAL or GLOBAL.
     * @param String $description Description of the template
     * @throws BceClientException|BceServiceException
     * @return mixed
     */
    public function createTemplate($name, $content, $smsType, $countryType, $description, $options = array())
    {
        $requestParam = array();
        $this->checkTemplateParam($name, $content, $smsType, $countryType);
        if (empty($description)) {
            throw new BceClientException("description should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam['name'] = $name;
        $requestParam['content'] = $content;
        $requestParam['smsType'] = $smsType;
        $requestParam['countryType'] = $countryType;
        $requestParam['description'] = $description;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($requestParam),
                'params' => array(
                    'clientToken' => $this->getClientToken()
                )
            ),
            '/sms/v3/template'
        );
    }

    /**
     * Update message template
     *
     * @param String $templateId TemplateId
     * @param String $name Template's name
     * @param String $content Template's content
     * @param String $smsType The sms type of the template content
     * @param String $countryType The countryType indicates the countries or regions in which the template can be used.
     *                     The value of countryType could be DOMESTIC or INTERNATIONAL or GLOBAL.
     * @param String $description option: Description of the template
     * @return mixed
     * @throws BceClientException|BceServiceException
     */
    public function updateTemplate($templateId, $name, $content, $smsType, $countryType, $description = null,
                                   $options = array())
    {
        $requestParam = array();
        $this->checkTemplateParam($name, $content, $smsType, $countryType);

        if (empty($templateId)) {
            throw new BceClientException("templateId should not be null or empty");
        }

        if (!empty($description)) {
            $requestParam['description'] = $description;
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam['name'] = $name;
        $requestParam['content'] = $content;
        $requestParam['smsType'] = $smsType;
        $requestParam['countryType'] = $countryType;
        $requestParam['templateId'] = $templateId;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($requestParam)
            ),
            '/sms/v3/template/'.$templateId
        );
    }

    /**
     * Delete template
     *
     * @param String $templateId
     * @param array $options
     * @return void
     * @throws BceClientException|BceServiceException
     */
    public function deleteTemplate($templateId, $options = array())
    {
        if (empty($templateId)) {
            throw new BceClientException("templateId should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config
            ),
            '/sms/v3/template/'.$templateId
        );
    }

    /**
     * Query template detail
     *
     * @param String $templateId
     * @param array $options
     * @return mixed
     * @throws BceClientException|BceServiceException
     */
    public function getTemplateDetail($templateId, $options = array())
    {
        if (empty($templateId)) {
            throw new BceClientException("templateId should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config
            ),
            '/sms/v3/template/'.$templateId
        );
    }

    /**
     * Create signature
     *
     * @param String $content Text content of the signature. e.g. Baidu
     * @param String $contentType The type of the signature.
     *        The value of contentType could be Enterprise or MobileApp or Web or WeChatPublic or Brand or Else.
     * @param String $countryType The countryType indicates the countries or regions in which the signature can be used
     *        The value of countryType could be DOMESTIC or INTERNATIONAL or GLOBAL.
     * @param String $description Description of the signature
     * @param String $signatureFileBase64 The base64 encoding string of the signature certificate picture.
     * @param String $signatureFileFormat The format of the signature certificate picture.
     *              which can only be one of JPG、PNG、JPEG.
     * @param array $options
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function createSignature($content, $contentType, $countryType, $description = null,
                                    $signatureFileBase64 = null, $signatureFileFormat = null, $options = array())
    {
        $requestParam = array();

        $this->checkSignatureParam($content, $contentType, $countryType);

        if (!empty($description)) {
            $requestParam['description'] = $description;
        }

        if (!empty($signatureFileBase64)) {
            $requestParam['signatureFileBase64'] = $signatureFileBase64;
        }

        if (!empty($signatureFileFormat)) {
            $requestParam['signatureFileFormat'] = $signatureFileFormat;
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam['content'] = $content;
        $requestParam['contentType'] = $contentType;
        $requestParam['countryType'] = $countryType;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($requestParam),
                'params' => array(
                    'clientToken' => $this->getClientToken()
                )
            ),
            '/sms/v3/signatureApply'
        );


    }

    /**
     * Update signature
     *
     * @param String $signatureId signatureId
     * @param String $content Text content of the signature. e.g. Baidu
     * @param String $contentType The type of the signature.
     *        The value of contentType could be Enterprise or MobileApp or Web or WeChatPublic or Brand or Else.
     * @param String $countryType The countryType indicates the countries or regions in which the signature can be used
     *        The value of countryType could be DOMESTIC or INTERNATIONAL or GLOBAL.
     * @param String $description Description of the signature
     * @param String $signatureFileBase64 The base64 encoding string of the signature certificate picture.
     * @param String $signatureFileFormat The format of the signature certificate picture.
     *              which can only be one of JPG、PNG、JPEG.
     * @param array $options
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function updateSignature($signatureId, $content, $contentType, $countryType, $description = null,
                                    $signatureFileBase64 = null, $signatureFileFormat = null, $options = array())
    {
        $requestParam = array();

        $this->checkSignatureParam($content, $contentType, $countryType);

        if (empty($signatureId)) {
            throw new BceClientException("signatureId should not be null or empty");
        }

        if (!empty($description)) {
            $requestParam['description'] = $description;
        }

        if (!empty($signatureFileBase64)) {
            $requestParam['signatureFileBase64'] = $signatureFileBase64;
        }

        if (!empty($signatureFileFormat)) {
            $requestParam['signatureFileFormat'] = $signatureFileFormat;
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam['content'] = $content;
        $requestParam['contentType'] = $contentType;
        $requestParam['countryType'] = $countryType;
        $requestParam['signatureId'] = $signatureId;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($requestParam)
            ),
            '/sms/v3/signatureApply/'.$signatureId
        );
    }

    /**
     * Delete Signature
     *
     * @param String $signatureId
     * @param array $options
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function deleteSignature($signatureId, $options = array())
    {
        if (empty($signatureId)) {
            throw new BceClientException("signatureId should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config
            ),
            '/sms/v3/signatureApply/'.$signatureId
        );
    }

    /**
     * Get Signature Detail
     *
     * @param String $signatureId
     * @param array $options
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function getSignatureDetail($signatureId, $options = array())
    {
        if (empty($signatureId)) {
            throw new BceClientException("signatureId should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config
            ),
            '/sms/v3/signatureApply/'.$signatureId
        );
    }

    /**
     * Get QuotaRate
     * @param array $options
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function getQuotaRate($options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array(
                    'userQuery' => ''
                )
            ),
            '/sms/v3/quota'
        );
    }

    /**
     * UpdateQuotaRate
     *
     * @param Integer $quotaPerDay
     * @param Integer $quotaPerMonth
     * @param Integer $rateLimitPerMobilePerSignByMinute
     * @param Integer $rateLimitPerMobilePerSignByHour
     * @param Integer $rateLimitPerMobilePerSignByDay
     * @param array $options
     * @return void
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function updateQuotaRate($quotaPerDay, $quotaPerMonth, $rateLimitPerMobilePerSignByMinute,
                                    $rateLimitPerMobilePerSignByHour, $rateLimitPerMobilePerSignByDay,
                                    $options = array())
    {
        $requestParam = array();

        if (empty($quotaPerDay)) {
            throw new BceClientException("quotaPerDay should not be null or empty");
        }

        if (empty($quotaPerMonth)) {
            throw new BceClientException("quotaPerMonth should not be null or empty");
        }

        if (empty($rateLimitPerMobilePerSignByMinute)) {
            throw new BceClientException("rateLimitPerMobilePerSignByMinute should not be null or empty");
        }

        if (empty($rateLimitPerMobilePerSignByHour)) {
            throw new BceClientException("rateLimitPerMobilePerSignByHour should not be null or empty");
        }

        if (empty($rateLimitPerMobilePerSignByDay)) {
            throw new BceClientException("rateLimitPerMobilePerSignByDay should not be null or empty");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $requestParam['quotaPerDay'] = $quotaPerDay;
        $requestParam['quotaPerMonth'] = $quotaPerMonth;
        $requestParam['rateLimitPerMobilePerSignByMinute'] = $rateLimitPerMobilePerSignByMinute;
        $requestParam['rateLimitPerMobilePerSignByHour'] = $rateLimitPerMobilePerSignByHour;
        $requestParam['rateLimitPerMobilePerSignByDay'] = $rateLimitPerMobilePerSignByDay;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($requestParam)
            ),
            '/sms/v3/quota'
        );
    }
}<?php


namespace BaiduBce\Services\Vpn\util;


class CheckUtils {

    /**
     * @param $arg
     * @param $fieldName
     */
    public static function isBlank($arg, $fieldName){
        if (empty($arg)) {
            throw new \InvalidArgumentException(
                'request ' . $fieldName . ' should not be empty .'
            );
        }
    }
}<?php


namespace BaiduBce\Services\Vpn;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\Vpn\model\Billing;
use BaiduBce\Services\Vpn\model\IkeConfig;
use BaiduBce\Services\Vpn\model\IpsecConfig;
use BaiduBce\Services\Vpn\util\CheckUtils;

/**
 * This module provides a client class for VpnClient.
 */
class VpnClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The VpnClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'vpn');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Return a list of vpn.
     * @param $vpcId
     *         Belonging VPC The identifier
     *
     * @param null $eip
     *        vpn bound eip address
     *
     * @param null $marker
     *        The optional parameter marker specified in the original request to specify
     *        where in the results to begin listing.
     *        Together with the marker, specifies the list result which listing should begin.
     *        If the marker is not specified, the list result will listing from the first one.
     *
     * @param null $maxkeys
     *        The optional parameter to specifies the max number of list result to return.
     *        The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating VpnClient instance.
     *
     * @return mixed
     */
    public function listVpn($vpcId, $eip = null, $marker = null, $maxkeys = null, $options = array()){
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpcId, '$vpcId');

        $params = array();
        $params['vpcId'] = $vpcId;
        if(!empty($marker)) {
            $params['marker'] = $marker;
        }
        if(!empty($maxkeys)) {
            $params['maxKeys'] = $maxkeys;
        }
        if(!empty($eip)) {
            $params['eip'] = $eip;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpn'
        );

    }

    /**
     * Create an Vpn with the specified options.
     *
     * @param $vpcId
     *           vpc  id
     *
     * @param $vpnName
     *           vpn  name
     *
     * @param Billing $billing
     *           billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param null $description
     *           vpn description
     *
     * @param null $eip
     *           bind eip
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function createVpn($vpcId, $vpnName, Billing $billing, $clientToken = null, $description = null, $eip = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpcId, '$vpcId');
        CheckUtils::isBlank($vpnName, '$vpnName');
        CheckUtils::isBlank($billing, '$billing');

        $body = array();
        $body['vpcId'] = $vpcId;
        $body['vpnName'] = $vpnName;
        $body['billing'] = $this->objectToArray($billing);
        if (!empty($description)) {
            $body['description'] = $description;
        }
        if (!empty($description)) {
            $body['eip'] = $eip;
        }

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn'
        );
    }

    /**
     * update vpn
     *
     * @param $vpnId
     *          vpn  id
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param null $vpnName
     *           vpn  name
     *
     * @param null $description
     *           vpn description
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function updateVpn($vpnId, $clientToken = null, $vpnName = null, $description = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');

        $params = array();
        $params['modifyAttribute'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        $body = array();
        if (!empty($description)) {
            $body['description'] = $description;
        }
        if (!empty($vpnName)) {
            $body['vpnName'] = $vpnName;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * get vpn
     *
     * @param $vpnId
     *          vpn  id
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function getVpn($vpnId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * delete vpn
     *
     * @param $vpnId
     *          vpn  id
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixedk
     */
    public function deleteVpn($vpnId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * vpn bind eip.
     *
     * @param $vpnId
     *          vpn id
     *
     * @param null $eip
     *          eip address
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function bindEip($vpnId, $eip, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');
        CheckUtils::isBlank($eip, '$eip');

        $params = array();
        $params['bind'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        $body = array();
        $body['eip'] = $eip;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * vpn unbind eip.
     *
     * @param $vpnId
     *          vpn id
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function unBindEip($vpnId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');

        $params = array();
        $params['unbind'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * renew vpn .
     *
     * @param $vpnId
     *          vpn id
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function renewVpn($vpnId, Billing $billing, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');
        CheckUtils::isBlank($billing, '$billing');

        $params = array();
        $params['purchaseReserved'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        $body = array();
        $body['billing'] = $this->objectToArray($billing);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn/' . $vpnId
        );
    }

    /**
     * Create an VpnConn.
     *
     * @param $vpnId
     *        vpn id
     * @param $secretKey
     *         Shared key, 8~17 characters, English, numbers and symbols must exist at the same time, and the symbols are limited to @#$%^*()_
     *
     * @param array $localSubnets
     *         Local network cidr List
     *
     * @param $remoteIp
     *         Peer VPN Gateway public network IP
     *
     * @param array $remoteSubnets
     *         Peer network cidr List
     *
     * @param $vpnConnName
     *        VPN Tunnel name, uppercase and lowercase letters, numbers and -_/. special characters, must start with a letter, length 1-65
     *
     * @param IkeConfig $ikeConfig
     *        IKE  Configuration
     *
     * @param IpsecConfig $ipsecConfig
     *        IPSec  Configuration
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param null $description
     *           vpnconn description
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function createVpnConn($vpnId, $secretKey,  array $localSubnets, $remoteIp, array $remoteSubnets, $vpnConnName, IkeConfig $ikeConfig, IpsecConfig $ipsecConfig, $clientToken = null, $description = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');
        CheckUtils::isBlank($secretKey, '$secretKey');
        CheckUtils::isBlank($localSubnets, '$localSubnets');
        CheckUtils::isBlank($remoteIp, '$remoteIp');
        CheckUtils::isBlank($remoteSubnets, '$remoteSubnets');
        CheckUtils::isBlank($vpnConnName, '$vpnConnName');
        CheckUtils::isBlank($ikeConfig, '$ikeConfig');
        CheckUtils::isBlank($ipsecConfig, '$ipsecConfig');

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        $body = array();
        $body['secretKey'] = $secretKey;
        $body['localSubnets'] = $localSubnets;
        $body['remoteIp'] = $remoteIp;
        $body['remoteSubnets'] = $remoteSubnets;
        $body['vpnConnName'] = $vpnConnName;
        $body['ikeConfig'] = $this->objectToArray($ikeConfig);
        $body['ipsecConfig'] = $this->objectToArray($ipsecConfig);
        if (!empty($description)) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn/' . $vpnId . '/vpnconn'
        );
    }

    /**
     * update an VpnConn.
     *
     * @param $vpnConnId
     *        vpnconn id
     *
     * @param $vpnId
     *        vpn id
     * @param $secretKey
     *         Shared key, 8~17 characters, English, numbers and symbols must exist at the same time, and the symbols are limited to @#$%^*()_
     *
     * @param array $localSubnets
     *         Local network cidr List
     *
     * @param $remoteIp
     *         Peer VPN Gateway public network IP
     *
     * @param array $remoteSubnets
     *         Peer network cidr List
     *
     * @param $vpnConnName
     *        VPN Tunnel name, uppercase and lowercase letters, numbers and -_/. special characters, must start with a letter, length 1-65
     *
     * @param IkeConfig $ikeConfig
     *        IKE  Configuration
     *
     * @param IpsecConfig $ipsecConfig
     *        IPSec  Configuration
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param null $description
     *           vpnconn description
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function updateVpnConn($vpnConnId, $vpnId, $secretKey,  array $localSubnets, $remoteIp, array $remoteSubnets, $vpnConnName, IkeConfig $ikeConfig, IpsecConfig $ipsecConfig, $clientToken = null, $description = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnConnId');
        CheckUtils::isBlank($vpnId, '$vpnId');
        CheckUtils::isBlank($secretKey, '$secretKey');
        CheckUtils::isBlank($localSubnets, '$localSubnets');
        CheckUtils::isBlank($remoteIp, '$remoteIp');
        CheckUtils::isBlank($remoteSubnets, '$remoteSubnets');
        CheckUtils::isBlank($vpnConnName, '$vpnConnName');
        CheckUtils::isBlank($ikeConfig, '$ikeConfig');
        CheckUtils::isBlank($ipsecConfig, '$ipsecConfig');

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        $body = array();
        $body['vpnId'] = $vpnId;
        $body['secretKey'] = $secretKey;
        $body['localSubnets'] = $localSubnets;
        $body['remoteIp'] = $remoteIp;
        $body['remoteSubnets'] = $remoteSubnets;
        $body['vpnConnName'] = $vpnConnName;
        $body['ikeConfig'] = $this->objectToArray($ikeConfig);
        $body['ipsecConfig'] = $this->objectToArray($ipsecConfig);
        if (!empty($description)) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/vpn/vpnconn/' . $vpnConnId
        );
    }

    /**
     * get vpnConn  list by vpnId
     *
     * @param $vpnId
     *          vpn  id
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function getVpnConn($vpnId, $clientToken = null , $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnId, '$vpnId');

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpn/vpnconn/' . $vpnId
        );
    }

    /**
     * delete vpnConn
     *
     * @param $vpnConnId
     *          vpnconn  id
     *
     * @param null $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating Vpn instance.
     *
     * @return mixed
     */
    public function deleteVpnConn($vpnConnId, $clientToken = null , $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        CheckUtils::isBlank($vpnConnId, '$vpnId');

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpn/vpnconn/' . $vpnConnId
        );
    }


    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray(object $obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest(string $httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }

}<?php
/*
* Copyright 2018 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Vpn\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct(int $reservationLength, string $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php


namespace BaiduBce\Services\Vpn\model;


class IpsecConfig
{
    // Encryption algorithm, value range :aes/aes192/aes256/3des
    var $ipsecEncAlg;
    // Authentication algorithm, value range :sha1/md5
    var $ipsecAuthAlg;
    // DH Grouping, value range :group2/group5/group14/group24
    var $ipsecPfs;
    // SA Life cycle, value range :180-86400
    var $ipsecLifetime;

    /**
     * @return mixed
     */
    public function getIpsecEncAlg()
    {
        return $this->ipsecEncAlg;
    }

    /**
     * @param mixed $ipsecEncAlg
     */
    public function setIpsecEncAlg($ipsecEncAlg): void
    {
        $this->ipsecEncAlg = $ipsecEncAlg;
    }

    /**
     * @return mixed
     */
    public function getIpsecAuthAlg()
    {
        return $this->ipsecAuthAlg;
    }

    /**
     * @param mixed $ipsecAuthAlg
     */
    public function setIpsecAuthAlg($ipsecAuthAlg): void
    {
        $this->ipsecAuthAlg = $ipsecAuthAlg;
    }

    /**
     * @return mixed
     */
    public function getIpsecPfs()
    {
        return $this->ipsecPfs;
    }

    /**
     * @param mixed $ipsecPfs
     */
    public function setIpsecPfs($ipsecPfs): void
    {
        $this->ipsecPfs = $ipsecPfs;
    }

    /**
     * @return mixed
     */
    public function getIpsecLifetime()
    {
        return $this->ipsecLifetime;
    }

    /**
     * @param mixed $ipsecLifetime
     */
    public function setIpsecLifetime($ipsecLifetime): void
    {
        $this->ipsecLifetime = $ipsecLifetime;
    }


}<?php


namespace BaiduBce\Services\Vpn\model;


class IkeConfig
{
    // Version, value range :v1/v2
    var $ikeVersion;
    // Negotiation mode, value range :main/aggressive
    var $ikeMode;
    // Encryption algorithm, value range :aes/aes192/aes256/3des
    var $ikeEncAlg;
    // Authentication algorithm, value range :sha1/md5
    var $ikeAuthAlg;
    //DH Grouping, value range :group2/group5/group14/group24
    var $ikePfs;
    // SA Life cycle, value range :60-86400
    var $ikeLifeTime;

    /**
     * @return mixed
     */
    public function getIkeVersion()
    {
        return $this->ikeVersion;
    }

    /**
     * @param mixed $ikeVersion
     */
    public function setIkeVersion($ikeVersion): void
    {
        $this->ikeVersion = $ikeVersion;
    }

    /**
     * @return mixed
     */
    public function getIkeMode()
    {
        return $this->ikeMode;
    }

    /**
     * @param mixed $ikeMode
     */
    public function setIkeMode($ikeMode): void
    {
        $this->ikeMode = $ikeMode;
    }

    /**
     * @return mixed
     */
    public function getIkeEncAlg()
    {
        return $this->ikeEncAlg;
    }

    /**
     * @param mixed $ikeEncAlg
     */
    public function setIkeEncAlg($ikeEncAlg): void
    {
        $this->ikeEncAlg = $ikeEncAlg;
    }

    /**
     * @return mixed
     */
    public function getIkeAuthAlg()
    {
        return $this->ikeAuthAlg;
    }

    /**
     * @param mixed $ikeAuthAlg
     */
    public function setIkeAuthAlg($ikeAuthAlg): void
    {
        $this->ikeAuthAlg = $ikeAuthAlg;
    }

    /**
     * @return mixed
     */
    public function getIkePfs()
    {
        return $this->ikePfs;
    }

    /**
     * @param mixed $ikePfs
     */
    public function setIkePfs($ikePfs): void
    {
        $this->ikePfs = $ikePfs;
    }

    /**
     * @return mixed
     */
    public function getIkeLifeTime()
    {
        return $this->ikeLifeTime;
    }

    /**
     * @param mixed $ikeLifeTime
     */
    public function setIkeLifeTime($ikeLifeTime): void
    {
        $this->ikeLifeTime = $ikeLifeTime;
    }


}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Vpn\model;

class Billing
{
    var $paymentTiming;
    var $billingMethod;
    var $reservation;

    /**
     * Billing information.
     *
     * @param string $paymentTiming
     *          The pay time of the payment
     *
     * @param string $billingMethod
     *            Billing method ,ByTraffic or ByBandwidth
     *
     * @param int $reservationLength
     *          purchase length
     *
     * @param string $reservationTimeUnit
     *          time unit of purchasing,default 'Month'
     */
    function __construct($paymentTiming='Postpaid', $billingMethod='ByBandwidth', $reservationLength=1, $reservationTimeUnit='Month')
    {
        $this->paymentTiming = $paymentTiming;
        $this->billingMethod = $billingMethod;
        $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Nat;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\Nat\model\Billing;

/**
 * This module provides a client class for NAT.
 */
class NatClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The NatClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'nat');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an nat with the specified options.
     *
     * @param string $name
     *          name of nat
     *
     * @param string $vpcId
     *          id of vpc which nat created in
     *
     * @param string $spec
     *          specification of nat
     *
     * @param array $eips
     *          eips which will be bound to the nat. The optional parameter
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createNat($name, $vpcId, $spec, $eips = null, $billing = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['name'] = $name;
        $body['vpcId'] = $vpcId;
        $body['spec'] = $spec;
        if (!empty($eips)) {
            $body['eips'] = $this->objectToArray($eips);
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBilling();
        }
        $body['billing'] = $this->objectToArray($billing);
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat'
        );
    }

    /**
     * PurchaseReserved nat with fixed duration,only Prepaid nat can do this
     *
     * @param string $natId
     *          nat id to be renewed
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default reservationLength is 1
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedNat($natId, $billing = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($billing)) {
            $reservation = array();
            $reservation['reservationTimeUnit'] = 'Month';
            $reservation['reservationLength'] = 1;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        } else {
            $reservation = array();
            $reservation['reservationTimeUnit'] = $billing->reservation->reservationTimeUnit;
            $reservation['reservationLength'] = $billing->reservation->reservationLength;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        }
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        $params['purchaseReserved'] = '';
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * bind eips to the nat
     *
     * @param array $eips
     *          eip addresses to be bound
     *
     * @param string $natId
     *          nat id to be bound
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function bindNat($eips, $natId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['eips'] = $this->objectToArray($eips);
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['bind'] = '';
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * unbind the eips from a nat instance
     *
     * @param array $eips
     *          eip addresses to be unbound
     *
     * @param string $natId
     *          nat id to be unbound
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function unbindNat($eips, $natId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['eips'] = $this->objectToArray($eips);
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['unbind'] = '';
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * rename a nat instance
     *
     * @param string $natId
     *          nat id to be renamed
     *
     * @param string $name
     *          name to be updated
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function renameNat($natId, $name, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['name'] = $name;
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * release the nat(delete operation)
     * Only the Postpaid instance or Prepaid which is expired can be released.
     *
     * @param string $natId
     *          id of nat instance to be released
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function releaseNat($natId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat/' . $natId
        );
    }

    /**
     * get a list of nat owned by the authenticated user and specified conditions.
     *
     * @param string $vpcId
     *          id of vpc which nat is in
     *
     * @param string $natId
     *          id of nat instance. The optional parameter
     *
     * @param string $name
     *          name of nat instance. The optional parameter
     *
     * @param string $ip
     *          eip address which is bound to nat instance. The optional parameter
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listNats($vpcId, $natId = null, $name = null, $ip = null, $marker = null, $maxKeys = 1000,
                             $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $params['vpcId'] = $vpcId;
        if ($natId !== null) {
            $params['natId'] = $natId;
        }
        if ($name !== null) {
            $params['name'] = $name;
        }
        if ($ip !== null) {
            $params['ip'] = $ip;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat'
        );
    }

    /**
     * get a single nat instance by nat id.
     *
     * @param string $natId
     *          id of nat instance
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function detailNats($natId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/nat/' . $natId
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The method to generate a default Billing which is Postpaid.
     *
     * @return Billing object with Postpaid PaymentTiming.
     */
    private function generateDefaultBilling()
    {
        return new Billing('Postpaid');
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }

    /**
     * Bind eips in the specified dnat.
     *
     * @param string $natId
     *          The dnat id to be bound
     *
     * @param array $dnatEips
     *          The list of eip addresses to be bound
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function bindDnatEip($natId, $dnatEips, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($dnatEips)) {
            throw new \InvalidArgumentException(
                'The request $dnatEips should not be empty.'
            );
        }
        $body['dnatEips'] = $this->objectToArray($dnatEips);
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['bind'] = '';
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * Unbind eips in the specified dnat.
     *
     * @param string $natId
     *          The dnat id to be bound
     *
     * @param array $dnatEips
     *          The list of eip addresses to be unbound
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function unbindDnatEip($natId, $dnatEips, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($dnatEips)) {
            throw new \InvalidArgumentException(
                'The request $dnatEips should not be empty.'
            );
        }
        $body['dnatEips'] = $this->objectToArray($dnatEips);
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['unbind'] = '';
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId
        );
    }

    /**
     * Create a snat rule in the specified snat.
     *
     * @param string $natId
     *          The nat id of the specified snat
     *
     * @param string $ruleName
     *          The name of the snat rule
     *
     * @param array $publicIpsAddress
     *          The list of the public ip addresses
     *
     * @param string $sourceCIDR
     *          The source cidr
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function createSnatRule($natId, $ruleName, $publicIpsAddress, $sourceCIDR, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($ruleName)) {
            throw new \InvalidArgumentException(
                'The request $ruleName should not be empty.'
            );
        }
        if(empty($publicIpsAddress)) {
            throw new \InvalidArgumentException(
                'The request $publicIpsAddress should not be empty.'
            );
        }
        if(empty($sourceCIDR)) {
            throw new \InvalidArgumentException(
                'The request $sourceCIDR should not be empty.'
            );
        }
        $body['publicIpsAddress'] = $this->objectToArray($publicIpsAddress);
        $body['sourceCIDR'] = $sourceCIDR;
        $body['ruleName'] = $ruleName;
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId . '/snatRule'
        );
    }

    /**
     * Delete a snat rule via the snat rule id in the specified snat.
     *
     * @param string $natId
     *          The nat id of the specified snat
     *
     * @param string $ruleId
     *          The id of the snat rule to be deleted
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function deleteSnatRule($natId, $ruleId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($ruleId)) {
            throw new \InvalidArgumentException(
                'The request $ruleId should not be empty.'
            );
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat/' . $natId . '/snatRule/' . $ruleId
        );
    }

    /**
     * Update a snat rule via the snat rule id in the specified snat.
     *
     * @param string $natId
     *          The nat id of the specified snat
     *
     * @param string $ruleId
     *          The id of the snat rule to be updated
     *
     * @param string $ruleName
     *          The name of the snat rule. The optional parameter
     *
     * @param string $sourceCIDR
     *          The source cidr. The optional parameter
     *
     * @param array $publicIpsAddress
     *          The list of the public ip addresses. The optional parameter
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function updateSnatRule($natId, $ruleId, $ruleName = null, $sourceCIDR = null, $publicIpsAddress = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($ruleId)) {
            throw new \InvalidArgumentException(
                'The request $ruleId should not be empty.'
            );
        }
        if (!empty($ruleName)) {
            $body['ruleName'] = $ruleName;
        }
        if (!empty($sourceCIDR)) {
            $body['sourceCIDR'] = $sourceCIDR;
        }
        if (!empty($publicIpsAddress)) {
            $body['publicIpsAddress'] = $this->objectToArray($publicIpsAddress);
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId . '/snatRule/' . $ruleId
        );
    }

    /**
     * List the information of snat rules in one specified snat.
     *
     * @param string $natId
     *          The nat id of the specified snat
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listSnatRules($natId, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }
        if (!empty($maxKeys)) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat/' . $natId . '/snatRule'
        );
    }

    /**
     * Create a dnat rule in the specified dnat.
     *
     * @param string $natId
     *          The nat id of the specified dnat
     *
     * @param string $publicIpAddress
     *          The public ip address
     *
     * @param string $privateIpAddress
     *          The private ip address
     *
     * @param string $protocol
     *          The type of protocol
     *
     * @param string $publicPort
     *          The public port. The optional parameter
     *
     * @param string $privatePort
     *          The private port. The optional parameter
     *
     * @param string $ruleName
     *          The name of the dnat rule. The optional parameter
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function createDnatRule($natId,  $publicIpAddress, $privateIpAddress, $protocol, $publicPort = null, $privatePort = null, $ruleName = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($publicIpAddress)) {
            throw new \InvalidArgumentException(
                'The request $publicIpAddress should not be empty.'
            );
        }
        if(empty($privateIpAddress)) {
            throw new \InvalidArgumentException(
                'The request $privateIpAddress should not be empty.'
            );
        }
        if(empty($protocol)) {
            throw new \InvalidArgumentException(
                'The request $protocol should not be empty.'
            );
        }
        if (!empty($ruleName)){
            $body['ruleName'] = $ruleName;
        }
        $body['publicIpAddress'] = $publicIpAddress;
        $body['privateIpAddress'] = $privateIpAddress;
        $body['protocol'] = $protocol;
        if (!empty($publicPort)){
            $body['publicPort'] = $publicPort;
        }
        if (!empty($privatePort)){
            $body['privatePort'] = $privatePort;
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId . '/dnatRule'
        );
    }

    /**
     * Delete a dnat rule via the dnat rule id in the specified dnat.
     *
     * @param string $natId
     *          The nat id of the specified dnat
     *
     * @param string $ruleId
     *          The id of the dnat rule to be deleted
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function deleteDnatRule($natId, $ruleId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($ruleId)) {
            throw new \InvalidArgumentException(
                'The request $ruleId should not be empty.'
            );
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat/' . $natId . '/dnatRule/' . $ruleId
        );
    }

    /**
     * Update a dnat rule via the dnat rule id in the specified dnat.
     *
     * @param string $natId
     *          The nat id of the specified dnat
     *
     * @param string $ruleId
     *          The id of the dnat rule to be updated
     *
     * @param string $ruleName
     *          The name of the dnat rule. The optional parameter
     *
     * @param string $protocol
     *          The type of protocol. The optional parameter
     *
     * @param int $publicPort
     *          The public port. The optional parameter
     *
     * @param int $privatePort
     *          The private port. The optional parameter
     *
     * @param string $privateIpAddress
     *          The private ip address. The optional parameter
     *
     * @param string $publicIpAddress
     *          The public ip address. The optional parameter
     *
     * @param string $clientToken
     *          If the clientToken is not specified by the user, a random string
     *          generated by default algorithm will be used
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating NatClient instance
     *
     * @return mixed
     */
    public function updateDnatRule($natId, $ruleId, $ruleName = null, $protocol = null, $publicPort = null, $privatePort = null, $privateIpAddress = null, $publicIpAddress = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if(empty($ruleId)) {
            throw new \InvalidArgumentException(
                'The request $ruleId should not be empty.'
            );
        }
        if (!empty($ruleName)) {
            $body['ruleName'] = $ruleName;
        }
        if (!empty($protocol)) {
            $body['protocol'] = $protocol;
        }
        if (!empty($publicPort)) {
            $body['publicPort'] = $publicPort;
        }
        if (!empty($privatePort)) {
            $body['privatePort'] = $privatePort;
        }
        if (!empty($privateIpAddress)) {
            $body['privateIpAddress'] = $privateIpAddress;
        }
        if (!empty($publicIpAddress)) {
            $body['publicIpAddress'] = $publicIpAddress;
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['clientToken'] = $clientToken;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/nat/' . $natId . '/dnatRule/' . $ruleId
        );
    }

    /**
     * List the information of dnat rules in one specified dnat.
     *
     * @param string $natId
     *          The nat id of the specified dnat
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listDnatRules($natId, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($natId)) {
            throw new \InvalidArgumentException(
                'The request $natId should not be empty.'
            );
        }
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }
        if (!empty($maxKeys)) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/nat/' . $natId . '/dnatRule'
        );
    }

}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Nat\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct($reservationLength, $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Nat\model;

class Billing
{
    var $paymentTiming;
    var $reservation;

    /**
     * Billing information.
     *
     * @param string $paymentTiming
     *          The pay time of the payment, default value 'Postpaid'
     *
     * @param int $reservationLength
     *          purchase length
     *
     * @param string $reservationTimeUnit
     *          time unit of purchasing,default 'Month'
     */
    function __construct($paymentTiming = 'Postpaid', $reservationLength = null, $reservationTimeUnit = null)
    {
        if ($paymentTiming !== null) {
            $this->paymentTiming = $paymentTiming;
        }
        if ($reservationLength != null || $reservationTimeUnit != null) {
            $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
        }
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\EipBp;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;


/**
 * This module provides a client class for EipBp.
 */
class EipBpClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The EipBpClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'eipbp');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an eipBp with the specified options.
     *
     * @param string $eip
     *          the eip address that the eip_bp attach.
     * @param string $eipGroupId
     *          the eipgroupId that the eip_bp attach.
     * Param $eip and $eipGroupId will has only one param take effect.
     *
     * @param int $bandwidthInMbps
     *          specify the bandwidth in Mbps
     *
     * @param string $name
     *          name of eipBp. The optional parameter
     *
     * @param string $autoReleaseTime (UTC format,like yyyy:mm:ddThh:mm:ssZ)
     *          autoReleaseTime of eipBp. The optional parameter
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */

    public function createEipBp($eip, $eipGroupId, $bandwidthInMbps, $name = null, $autoReleaseTime = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($bandwidthInMbps)) {
            throw new \InvalidArgumentException(
                '$bandwidthInMbps should not be empty.'
            );
        }
        if (empty($eip) && empty($eipGroupId)) {
            throw new \InvalidArgumentException(
                '$eip and $eipGroupId should not be empty at the same time.'
            );
        }

        $body['bandwidthInMbps'] = $bandwidthInMbps;

        if (!empty($eip)) {
            $body['eip'] = $eip;
        }
        if (!empty($eipGroupId)) {
            $body['eipGroupId'] = $eipGroupId;
        }
        if (!empty($name)) {
            $body['name'] = $name;
        }
        if (!empty($autoReleaseTime)) {
            $body['autoReleaseTime'] = $autoReleaseTime;
        }

        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipbp'
        );
    }

    /**
     * Resizing eipBp
     *
     * @param string $id
     *          eipbp's id to be resized
     *
     * @param int $newBandwidthInMbps
     *          specify new bandwidth in Mbps for eipBp
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function resizeEipBp($id, $newBandwidthInMbps, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        if (empty($newBandwidthInMbps)) {
            throw new \InvalidArgumentException(
                '$newBandwidthInMbps should not be empty.'
            );
        }
        $body = array();
        $body['bandwidthInMbps'] = $newBandwidthInMbps;
        $params = array();
        $params['resize'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipbp/' . $id
        );
    }

    /**
     * Get eipBp's detail  owned by the authenticated user and specified conditions.
     *
     * @param string $id
     *          eipBp 's id conditions
     *
     * @return mixed
     */
    public function getEipBp($id, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config
            ),
            '/eipbp' . $id
        );
    }

    /**
     * Get a list of eipBp owned by the authenticated user and specified conditions.
     * we can Also get a single eipBp function  through this interface by eipBp condition
     *
     * @param string $id
     *          eipBp 's id conditions
     *
     * @param string $name
     *          eipBp 's name condition
     *
     * @param string $bindType
     *          eipBp 's bindType condition, 'eip' or 'eipgroup'
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function listEipBps($id = null, $name = null, $bindType = null, $marker = null, $maxKeys = 1000,
                               $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($id !== null) {
            $params['id'] = $id;
        }
        if ($name !== null) {
            $params['name'] = $name;
        }
        if ($bindType !== null) {
            $params['bindType'] = $bindType;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eipbp'
        );
    }

    /**
     * Update eipBp's autoReleaseTime
     *
     * @param string $id
     *          eipBp's id to be update autoReleaseTime
     *
     * @param string $autoReleaseTime
     *          specify auto_release_time for eipBp(UTC format,like yyyy:mm:ddThh:mm:ssZ)
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function updateEipBpAutoReleaseTime($id, $autoReleaseTime, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        if (empty($autoReleaseTime)) {
            throw new \InvalidArgumentException(
                '$autoReleaseTime should not be empty.'
            );
        }
        $body = array();
        $body['autoReleaseTime'] = $autoReleaseTime;
        $params = array();
        $params['retime'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipbp/' . $id
        );
    }


    /**
     * Update eipBp's autoReleaseTime
     *
     * @param string $id
     *          eipBp's id to be rename
     *
     * @param string $name
     *          eipBp's name
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function renameEipBp($id, $name, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        if (empty($name)) {
            throw new \InvalidArgumentException(
                '$name should not be empty.'
            );
        }
        $body = array();
        $body['name'] = $name;
        $params = array();
        $params['rename'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipbp/' . $id
        );
    }

    /**
     * Release the eipBp(delete operation)
     *
     * @param string $id
     *          eipBp's id to be released
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function releaseEipBp($id, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eipbp/' . $id
        );
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php

/*
* Copyright 2019 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Mms;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Exception\BceServiceException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\DateUtils;

class MmsClient extends BceBaseClient
{
    private $signer;
    private $httpClient;
    private $prefixV2 = '/v2';

    /**
     * The MvsClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'MmsClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * 视频入库
     *
     * @param $lib string, lib name
     * @param $source string, media source
     * @param $notification string, notification
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed insert detail
     * @throws BceClientException|BceServiceException
     * */
    public function insertVideo($lib, $source, $notification, $options = array())
    {
        list($description) = $this->parseOptions($options, 'description');

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }
        if (empty($notification)) {
            throw new BceClientException("The parameter notification "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
            'notification' => $notification
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            $body,
            array(),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * 查询视频入库任务结果
     *
     * @param string $lib
     * @param string $source
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function getInsertVideoResult($lib, $source)
    {
        $parameters = array(
            'source' => $source,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(),
            $parameters,
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * 删除视频
     *
     */
    public function deleteVideo($lib, $source)
    {
        $parameters = array(
            'source' => $source,
            'deleteVideo' => '',
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(),
            $parameters,
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * 图片入库
     *
     * @param $lib
     * @param $source
     * @param $description
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function insertImage($lib, $source, $description)
    {

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            $body,
            array(),
            $this->prefixV2,
            "/imagelib/$lib"
        );
    }

    /**
     * 删除图片
     *
     */
    public function deleteImage($lib, $source)
    {
        $parameters = array(
            'source' => $source,
            'deleteImage' => '',
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(),
            $parameters,
            $this->prefixV2,
            "/imagelib/$lib"
        );
    }

    /**
     * 以图搜图
     *
     * @param $lib
     * @param $source
     * @param $description
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function searchImageByImage($lib, $source, $description)
    {
        $body = array(
            'source' => $source
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            $body,
            array('searchByImage' => ''),
            $this->prefixV2,
            "/imagelib/$lib"
        );
    }

    /**
     * 图片搜视频
     *
     * @param $lib
     * @param $source
     * @param $description
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function searchVideoByImage($lib, $source, $description)
    {
        $body = array(
            'source' => $source
        );
        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            $body,
            array('searchByImage' => ''),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * 视频搜视频
     *
     * @param $lib
     * @param $source
     * @param $description
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function searchVideoByVideo($lib, $source, $description)
    {
        $body = array(
            'source' => $source
        );
        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            $body,
            array('searchByVideo' => ''),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * 查询视频搜视频任务结果
     *
     * @param $lib
     * @param $source
     * @return mixed
     * @throws BceClientException
     * @throws BceServiceException
     */
    public function getSearchVideoByVideoResult($lib, $source)
    {
        return $this->sendRequest(
            HttpMethod::GET,
            array(),
            array('searchByVideo' => '', 'source' => $source),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $body request body
     * @param array $parameters request parameters
     * @param string $prefix prefix of request uri
     * @param string $requestPath request path
     * @return mixed The Http response and headers
     * @throws BceClientException|BceServiceException request exception
     */
    private function sendRequest($httpMethod, array $body, array $parameters, $prefix, $requestPath = '/')
    {
        $headers = array(
            HttpHeaders::CONTENT_TYPE => HttpContentTypes::JSON,
            HttpHeaders::DATE => DateUtils::formatRfc822Date(new \DateTime()),
        );

        $path = $prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $this->config,
            $httpMethod,
            $path,
            json_encode($body),
            $headers,
            $parameters,
            $this->signer
        );

        return $this->parseJsonResult($response['body']);
    }

}<?php
/*
* Copyright 2015 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Vcr;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\DateUtils;

class VcrClient extends BceBaseClient
{

    private $signer;
    private $httpClient;

    /**
     * The VcrClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'VcrClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Check a media.
     *
     * @param $source string, media source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          auth: string, media auth
     *          description: string, media description
     *          preset: string, analyze preset name
     *          notification: string, notification name
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function putMedia($source, $options = array())
    {
        list($config, $auth, $description, $preset, $notification) = $this->parseOptions($options,
            'config', 'auth', 'description', 'preset', 'notification');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
        );
        if ($auth !== null) {
            $body['auth'] = $auth;
        }
        if ($description !== null) {
            $body['description'] = $description;
        }
        if ($preset !== null) {
            $body['preset'] = $preset;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }


        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v1/media"
        );
    }

    /**
     * Get check result of media.
     *
     * @param $source string, media source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed media check result
     * @throws BceClientException
     */
    public function getMedia($source, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array('source' => $source),
            ),
            "/v1/media"
        );
    }

    /**
     * Check a audio.
     *
     * @param $source string, audio source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          preset: string, check preset name
     *          notification: string, notification name
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function putAudio($source, $options = array())
    {
        list($config, $auth, $description, $preset, $notification) = $this->parseOptions($options,
            'config', 'auth', 'description', 'preset', 'notification');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source
        );
        if ($auth !== null) {
            $body['auth'] = $auth;
        }
        if ($description !== null) {
            $body['description'] = $description;
        }
        if ($preset !== null) {
            $body['preset'] = $preset;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v2/audio"
        );
    }


    /**
     * Get check result of audio.
     *
     * @param $source string, audio source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed audio check result
     * @throws BceClientException
     */
    public function getAudio($source, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array('source' => $source),
            ),
            "/v2/audio"
        );
    }


    /**
     * Get a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed preset detail
     * @throws BceClientException
     */
    public function getPreset($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/v1/preset/$name"
        );
    }

    /**
     * List presets.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed preset lists
     */
    public function listPresets($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/v1/preset'
        );
    }

    /**
     * Check a image
     *
     * @param $source string, image source
     *      vcr support 2 image source format:
     *      1. bos path, source="bos://{bucket}/{object}, e.g. bos://test_bkt/test_dir/test_image.png
     *      2. http/https url
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed image check result
     * @throws BceClientException
     */
    public function putImage($source, $options = array())
    {
        list($config, $preset) = $this->parseOptions($options, 'config', 'preset');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source
        );
        if ($preset !== null) {
            $body['preset'] = $preset;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v1/image"
        );
    }

    /**
     * Check a image async, support gif
     *
     * @param $source string, image source
     *      vcr support 2 image source format:
     *      1. bos path, source="bos://{bucket}/{object}, e.g. bos://test_bkt/test_dir/test_image.png
     *      2. http/https url
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          description: string, image description
     *          preset: string, analyze preset name
     *          notification: string, notification name
     *      }
     * @return mixed image check result
     * @throws BceClientException
     */
    public function putImageAsync($source, $options = array())
    {
        list($config, $description, $preset, $notification) = $this->parseOptions($options,
            'config', 'description', 'preset', 'notification');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
        );
        if ($description !== null) {
            $body['description'] = $description;
        }
        if ($preset !== null) {
            $body['preset'] = $preset;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v2/image"
        );
    }


    /**
     * Get check result of image async check.
     *
     * @param $source string, media source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          preset: string, analyze preset name
     *      }
     * @return mixed media check result
     * @throws BceClientException
     */
    public function getImageAsync($source, $options = array())
    {
        list($config, $preset) = $this->parseOptions($options, 'config', 'preset');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array('source' => $source, 'preset' => $preset),
            ),
            "/v2/image"
        );
    }

    /**
     * Check a text
     *
     * @param $text string, text to check
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed text check result
     * @throws BceClientException
     */
    public function putText($text, $options = array())
    {
        list($config, $preset) = $this->parseOptions($options, 'config', 'preset');

        if (empty($text)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'text' => $text
        );
        if ($preset !== null) {
            $body['preset'] = $preset;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v1/text"
        );
    }

    /**
     * add face image
     * @param $lib string, face lib name.
     * @param $brief string, brief name.
     * @param $image string, image url.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function addFaceImage($lib, $brief, $image, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        if (empty($image)) {
            throw new BceClientException("The parameter image "
                . "should NOT be null or empty string");
        }
        $body = array(
            'brief' => $brief,
            'image' => $image
        );
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v1/face/lib/$lib"
        );
    }
    /**
     * delete face image
     * @param $lib string, face lib name.
     * @param $brief string, brief name.
     * @param $image string, image url.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function delFaceImage($lib, $brief, $image, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        if (empty($image)) {
            throw new BceClientException("The parameter image "
                . "should NOT be null or empty string");
        }
        $params = array(
            'brief' => $brief,
            'image' => $image
        );
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/v1/face/lib/$lib"
        );
    }
    /**
     * get face brief
     * @param $lib string, face lib name.
     * @param $brief string, brief name.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed face brief result
     * @throws BceClientException
     */
    public function getFaceBrief($lib, $brief, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        $params = array(
            'brief' => $brief,
        );
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/v1/face/lib/$lib"
        );
    }
    /**
     * delete face brief
     * @param $lib string, face lib name.
     * @param $brief string, brief name.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function delFaceBrief($lib, $brief, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => array('brief' => $brief),
            ),
            "/v1/face/lib/$lib"
        );
    }
    /**
     * get face lib
     * @param $lib string, face lib name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed check face lib result
     * @throws BceClientException
     */
    public function getFaceLib($lib, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/v1/face/lib/$lib"
        );
    }
    /**
     * add logo image
     * @param $lib string, logo lib name.
     * @param $brief string, brief name.
     * @param $image string, image url.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function addLogoImage($lib, $brief, $image, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        if (empty($image)) {
            throw new BceClientException("The parameter image "
                . "should NOT be null or empty string");
        }
        $body = array(
            'brief' => $brief,
            'image' => $image
        );
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/v1/logo/lib/$lib"
        );
    }
    /**
     * delete logo image
     * @param $lib string, logo lib name.
     * @param $image string, image url.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function delLogoImage($lib, $image, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($image)) {
            throw new BceClientException("The parameter image "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => array('image' => $image),
            ),
            "/v1/logo/lib/$lib"
        );
    }
    /**
     * get logo brief
     * @param $lib string, logo lib name.
     * @param $brief string, brief name.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed check logo brief result
     * @throws BceClientException
     */
    public function getLogoBrief($lib, $brief, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        $params = array(
            'brief' => $brief,
        );
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/v1/logo/lib/$lib"
        );
    }
    /**
     * delete logo brief
     * @param $lib string, logo lib name.
     * @param $brief string, brief name.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          brief: string, delete brief.
     *      }
     * @return mixed nothing
     * @throws BceClientException
     */
    public function delLogoBrief($lib, $brief, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($brief)) {
            throw new BceClientException("The parameter brief "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => array('brief' => $brief),
            ),
            "/v1/logo/lib/$lib"
        );
    }
    /**
     * get logo lib
     * @param $lib string, logo lib name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed check logo lib result
     * @throws BceClientException
     */
    public function getLogoLib($lib, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/v1/logo/lib/$lib"
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $requestPath,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
}
<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\PeerConn\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct($reservationLength, $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\PeerConn\model;

class Billing
{
    var $paymentTiming;
    var $reservation;

    /**
     * Billing information.
     *
     * @param string $paymentTiming
     *          The pay time of the payment
     *
     *
     * @param int $reservationLength
     *          purchase length
     *
     * @param string $reservationTimeUnit
     *          time unit of purchasing,default 'month'
     */
    function __construct($paymentTiming, $reservationLength, $reservationTimeUnit = 'month')
    {
        if ($paymentTiming !== null) {
            $this->paymentTiming = $paymentTiming;
        }
        $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
    }
}<?php
/*
* Copyright 2018 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/


namespace BaiduBce\Services\PeerConn;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\PeerConn\model\Billing;

/**
 * This module provides a client class for PeerConnClient.
 */
class PeerConnClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The PeerConnClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'peerconn');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an PeerConn with the specified options.
     *
     * @param int $bandwidthInMbps
     *          specify the bandwidth in Mbps.
     *
     * @param String $description
     *          specify the description of the PeerConn.The optional parameter
     *
     * @param string $localIfName
     *          the name of local interface of PeerConn. The optional parameter
     *
     * @param string $localVpcId
     *          the id of local vpc of PeerConn.
     *
     * @param string $peerAccountId
     *          the id of peer account of PeerConn.if it is the same account, this parameter does not need to be passed.
     *
     * @param string $peerVpcId
     *          the id of peer vpc of PeerConn.
     *
     * @param string $peerRegion
     *          the peer region name of PeerConn.
     *
     * @param string $peerIfName
     *          the peer interface name of PeerConn. The optional parameter.only same account can set.
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return the id of the PeerConn
     */
    public function createPeerConn($bandwidthInMbps, $localVpcId, $peerVpcId, $peerRegion, $billing, $peerAccountId = null, $peerIfName = null, $description = null, $localIfName = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($bandwidthInMbps)) {
            throw new \InvalidArgumentException(
                'request $bandwidthInMbps  should not be empty .'
            );
        }
        if (empty($localVpcId)) {
            throw new \InvalidArgumentException(
                'request $localVpcId  should not be empty .'
            );
        }
        if (empty($peerVpcId)) {
            throw new \InvalidArgumentException(
                'request $peerVpcId  should not be empty .'
            );
        }
        if (empty($peerRegion)) {
            throw new \InvalidArgumentException(
                'request $peerRegion  should not be empty .'
            );
        }
        if (empty($billing)) {
            throw new \InvalidArgumentException(
                'request $billing  should not be empty .'
            );
        }
        $body['bandwidthInMbps'] = $bandwidthInMbps;
        $body['localVpcId'] = $localVpcId;
        $body['peerVpcId'] = $peerVpcId;
        $body['peerRegion'] = $peerRegion;
        $body['billing'] = $this->objectToArray($billing);
        $body['description'] = $description;
        $body['localIfName'] = $localIfName;
        $body['peerIfName'] = $peerIfName;
        $body['peerAccountId'] = $peerAccountId;
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/peerconn'
        );
    }

    /**
     * Resizing PeerConn
     *
     * @param string peerConnId
     *          PeerConn's id to be resized
     *
     * @param int newBandwidthInMbps
     *          specify new bandwidth in Mbps for PeerConn
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return mixed
     */
    public function resizePeerConn($peerConnId, $newBandwidthInMbps, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($newBandwidthInMbps)) {
            throw new \InvalidArgumentException(
                'request $newBandwidthInMbps  should not be empty .'
            );
        }
        $body['newBandwidthInMbps'] = $newBandwidthInMbps;
        $params = array();
        $params['resize'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/peerconn/' . $peerConnId
        );
    }

    /**
     * update PeerConn
     *
     * @param string $peerConnId
     *          PeerConn's id to be updated
     *
     * @param string $localIfId
     *           PeerConn's local interface id to be updated
     *
     * @param string $localIfName
     *          specify the new localIfName for PeerConn.
     *
     * @param string $description
     *          specify the new description for PeerConn.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return mixed
     */
    public function updatePeerConn($peerConnId, $localIfId, $localIfName = null, $description = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($localIfId)) {
            throw new \InvalidArgumentException(
                'request $localIfId  should not be empty .'
            );
        }
        $body['localIfId'] = $localIfId;
        $body['localIfName'] = $localIfName;
        $body['description'] = $description;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }

    /**
     * PurchaseReserved PeerConn with fixed duration.only initiator can PurchaseReserved for diff account.
     *
     * @param string $peerConnId
     *          PeerConn's id to be renewed
     *
     * @param Billing $billing
     *          billing information.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedPeerConn($peerConnId, $billing, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($billing)) {
            throw new \InvalidArgumentException(
                'request $billing  should not be empty .'
            );
        } else {
            $reservation = array();
            $reservation['reservationTimeUnit'] = $billing->reservation->reservationTimeUnit;
            $reservation['reservationLength'] = $billing->reservation->reservationLength;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        }
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['purchaseReserved'] = null;
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/peerconn/' . $peerConnId
        );
    }


    /**
     * get a list of PeerConn which belong to the specified vpc .
     *
     * @param string $vpcId
     *          vpc's id condition
     *
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return a list of PeerConn
     */
    public function listPeerConns($vpcId, $marker = null, $maxKeys = 1000, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($vpcId !== null) {
            $params['vpcId'] = $vpcId;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn'
        );
    }

    /**
     * get a detail of the PeerConn which you specified .
     *
     * @param string $peerConnId
     *         PeerConn's id condition
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating PeerConnClient instance.
     *
     * @return the detail of PeerConn which you specified
     */
    public function getPeerConn($peerConnId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }


    /**
     * release the PeerConn(delete operation)
     * Only the Postpaid instance or Prepaid which is expired can be released.
     *
     * @param string $peerConnId
     *          the id of PeerConn which to be released
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function releasePeerConn($peerConnId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }

    /**
     * accept the apply of PeerConn
     *
     * @param string $peerConnId
     *          the id of PeerConn which to be deal apply.
     *
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function acceptPeerConnApply($peerConnId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        $params['accept'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }

    /**
     * reject the apply of PeerConn
     *
     * @param string $peerConnId
     *          the id of PeerConn which to be deal apply.
     *
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function rejectPeerConnApply($peerConnId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        $params['reject'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }


    /**
     * open PeerConn sync Dns record
     *
     * @param string $peerConnId
     *          the id of PeerConn which to be deal apply.
     *
     *
     * @param string role
     *          the param is "initiator" or "acceptor".
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function openPeerConnSyncDns($peerConnId, $role, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($role)) {
            throw new \InvalidArgumentException(
                'request $role  should not be empty .'
            );
        } else {
            $params['role'] = $role;
        }
        $params['open'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }


    /**
     * close PeerConn sync Dns record
     *
     * @param string $peerConnId
     *          the id of PeerConn which to be deal apply.
     *
     *
     * @param string role
     *          the param is "initiator" or "acceptor".
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function closePeerConnSyncDns($peerConnId, $role, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($peerConnId)) {
            throw new \InvalidArgumentException(
                'request $peerConnId  should not be empty .'
            );
        }
        if (empty($role)) {
            throw new \InvalidArgumentException(
                'request $role  should not be empty .'
            );
        } else {
            $params['role'] = $role;
        }
        $params['close'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/peerconn/' . $peerConnId
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */

    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The method to generate a default Billing which is Postpaid.
     *
     * @return Billing object with Postpaid PaymentTiming.
     */
    private function generateDefaultBilling()
    {
        return new Billing('Postpaid', 'ByBandwidth');
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright 2015 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Vca;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\DateUtils;

class VcaClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefixV1 = '/v1';
    private $prefixV2 = '/v2';

    /**
     * The VcaClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'VcaClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Analyze a media with Source.
     *
     * @param $source string, source of media
     * example:
     * bos://{bucket}/{object}
     * vod://{mediaId}
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          preset: string, analyze preset name
     *          notification: string, notification name
     *          priority: integer, priority
     *          title: string, media title
     *          subTitle: string, media subtitle
     *          category: string, media category
     *          description: string, media description
     *      }
     * @return nothing
     * @throws BceClientException
     */
    public function analyze($source, $options = array())
    {
        list($config, $preset, $notification, $priority, $title, $subTitle, $category, $description)
            = $this->parseOptions($options, 'config', 'preset', 'notification', 'priority',
            'title', 'subTitle', 'category', 'description');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array();
        $body['source'] = $source;
        if ($preset !== null) {
            $body['preset'] = $preset;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }
        if ($priority !== null) {
            $body['priority'] = $priority;
        }
        if ($title !== null) {
            $body['title'] = $title;
        }
        if ($subTitle !== null) {
            $body['subTitle'] = $subTitle;
        }
        if ($category !== null) {
            $body['category'] = $category;
        }
        if ($description !== null) {
            $body['description'] = $description;
        }

        $request = array('config' => $config);
        $request['body'] = json_encode($body);
        return $this->sendRequest(
            HttpMethod::PUT,
            $request,
            $this->prefixV2,
            "/media"
        );
    }

    /**
     * Query result of media analyzation by source.
     *
     * @param $source string, source of media
     * example:
     * bos://{bucket}/{object}
     * vod://{mediaId}
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed media analyzation detail
     * @throws BceClientException
     */
    public function queryResult($source, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array('source' => $source),
            ),
            $this->prefixV2,
            "/media"
        );
    }

    /**
     * Query sub task result for specified source of directed type.
     *
     * @param $source string, source of media
     * example:
     * bos://{bucket}/{object}
     * vod://{mediaId}
     * @param $type string, sub task type.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed media analyzation of sub task type.
     * @throws BceClientException
     */
    public function querySubTask($source, $type, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }
        if (empty($type)) {
            throw new BceClientException("The parameter type "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array('source' => $source),
            ),
            $this->prefixV2,
            "/media/$type"
        );
    }

    /**
     * Create a notification.
     *
     * @param $name string, notification name
     * @param $endpoint string, notification endpoint
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed notification detail
     * @throws BceClientException
     */
    public function createNotification($name, $endpoint, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }
        if (empty($endpoint)) {
            throw new BceClientException("The parameter endpoint "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
            'endpoint' => $endpoint,
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            $this->prefixV1,
            '/notification'
        );
    }

    /**
     * Get a notification.
     *
     * @param $name string, notification name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed notification detail
     * @throws BceClientException
     */
    public function getNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            $this->prefixV1,
            "/notification/$name"
        );
    }

    /**
     * List notifications.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return notification list
     * @throws BceClientException
     */
    public function listNotifications($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            $this->prefixV1,
            "/notification"
        );
    }

    /**
     * Create a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          isDefault: boolean, create as default preset
     *          asr: {
     *              enabled: boolean, enable asr analyzation
     *          },
     *          ocr: {
     *              enabled: boolean, enable ocr analyzation
     *          },
     *          scenarioTag: {
     *              enabled: boolean, enable scenario tag analyzation
     *          },
     *          scenarioClassify: {
     *              enabled: boolean, enable scenario classify analyzation
     *          },
     *          imageClassify: {
     *              enabled: boolean, enable image classify analyzation
     *          },
     *          faceRecognition: {
     *              enabled: boolean, enable face recognition analyzation
     *          },
     *          asrTagEnable: boolean, enable tag from asr
     *          ocrTagEnable: boolean, enable tag from ocr
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createPreset($name, $options = array())
    {
        list($config, $asr, $ocr, $scenarioTag, $scenarioClassify, $imageClassify,
            $faceRecognition, $asrTagEnable, $ocrTagEnable) = $this->parseOptions(
            $options,
            'config',
            'asr',
            'ocr',
            'scenarioTag',
            'scenarioClassify',
            'imageClassify',
            'faceRecognition',
            'asrTagEnable',
            'ocrTagEnable'
        );

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
        );

        if ($asr !== null) {
            $body['asr'] = $asr;
        }
        if ($ocr !== null) {
            $body['ocr'] = $ocr;
        }
        if ($scenarioTag !== null) {
            $body['scenarioTag'] = $scenarioTag;
        }
        if ($scenarioClassify !== null) {
            $body['scenarioClassify'] = $scenarioClassify;
        }
        if ($imageClassify !== null) {
            $body['imageClassify'] = $imageClassify;
        }
        if ($faceRecognition !== null) {
            $body['faceRecognition'] = $faceRecognition;
        }
        if ($asrTagEnable !== null) {
            $body['asrTagEnable'] = $asrTagEnable;
        }
        if ($ocrTagEnable !== null) {
            $body['ocrTagEnable'] = $ocrTagEnable;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            $this->prefixV1,
            '/preset'
        );
    }

    /**
     * Get a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed preset detail
     * @throws BceClientException
     */
    public function getPreset($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            $this->prefixV1,
            "/preset/$name"
        );
    }

    /**
     * List presets.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @param array $options
     * @return mixed
     */
    public function listPresets($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            $this->prefixV1,
            '/preset'
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $prefix, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
}
<?php
/*
* Copyright 2015 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Vod;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Services\Bos\BosClient;

class VodClient extends BceBaseClient
{
    private $signer;
    private $httpClient;
    private $bosClient;
    private $prefix = '/v1';

    /**
     * @param array $config The client configuration to connect VOD Server
     * @param array $bosConfig The client configuration to connect BOS server
     */
    function __construct(array $config, $bosConfig = array())
    {
        parent::__construct($config, 'VodClient', false);
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
        if (count($bosConfig) == 0) {
            $bosConfig = $config;
            if (isset($bosConfig[BceClientConfigOptions::ENDPOINT])) {
                unset($bosConfig[BceClientConfigOptions::ENDPOINT]);
            }
        }
        $bosConfig[BceClientConfigOptions::REGION] = 'bj';
        $this->bosClient = new BosClient($bosConfig);
    }

    /**
     * apply a vod media
     * Apply a new vod media, get mediaId, sourceBucket, sourceKey.
     * You account have the access to write the sourceBucket and sourceKey.
     * You need upload video to sourceBucket and sourceKey via BosClient,
     * Then call processMedia method to get a VOD media.
     *
     * @param string $mode apply media mode
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed created vod media info
     */
    public function applyMedia($mode='', $options = array())
    {
        list($config, $presetGroup, $priority) =
            $this->parseOptionsIgnoreExtra($options,
                'config',
                'presetGroup',
                'priority');

        $params = array(
            'apply' => null,
        );
        if (!empty($mode)) {
            $params['mode'] = $mode;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/media'
        );
    }

    /**
     * process a vod media
     * After applying media, uploading original video to bosClient,
     * you MUST call processMedia method to get a VOD media.
     *
     * @param $mediaId
     * @param $title string, the title of the media
     * @param $description string, the description of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *          sourceExtension: extension of the media source.
     *          presetGroup: preset group to be used for the media
     *          priority: priority
     *          actionAttributes: { remove watermark and prologue params for the media
     *              horizontalOffsetInPixel: number, watermark Horizontal offset
     *              verticalOffsetInPixel: number, watermark Vertical offset
     *              watermarkWidth: number, watermark region width
     *              watermarkHeight: number, watermark region height
     *              prologueCuttingInSeconds: number, prologue duration time
     *          }
     *      }
     * @return mixed created vod media info
     * @throws BceClientException
     */
    public function processMedia($mediaId, $title, $description, $options = array())
    {
        list($config, $extension, $presetGroup, $priority, $actionAttributes) =
            $this->parseOptions($options,
                'config',
                'sourceExtension',
                'presetGroup',
                'priority',
                'actionAttributes');
        if (is_null($priority)) {
            $priority = 0;
        }

        $params = array(
            'process' => null,
        );
        $body = array(
            'title' => $title,
            'description' => $description,
            'sourceExtension' => $extension,
            'transcodingPresetGroupName' => $presetGroup,
            'priority' => $priority
        );

        if ($actionAttributes !== null) {
            $body['actionAttributes'] = $actionAttributes;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            "/media/$mediaId"
        );
    }


    /**
     * rerun a vod media
     * you can call rerunMedia method to re-process a VOD media.
     *
     * @param $mediaId
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed created vod media info
     * @throws BceClientException
     */
    public function rerunMedia($mediaId, $options = array())
    {
        list($config, $presetGroup, $priority) =
            $this->parseOptions($options, 'config', 'presetGroup', 'priority');
        $params = array(
            'rerun' => null,
            'presetGroup' => $presetGroup,
            'priority' => $priority
        );
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }


    /**
     * merge vod media(s)
     * You can merge media(s) to one media
     *
     * @param $mediaClips media clips to be merged into the new media
     * @param $title the title of the new media
     * @param $description the description of the new media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *          presetGroup: the preset group of the new media
     *          priority: the priority of the new media
     *      }
     * @return mixed merged vod media info
     * @throws BceClientException
     */
    public function mergeMedia($mediaClips, $title, $description, $options = array())
    {
        list($config, $presetGroup, $priority)
            = $this->parseOptions($options, 'config', 'presetGroup', 'priority');

        $params = array(
            'merge' => null,
        );

        $attributes = array(
            'title' => $title,
            'description' => $description,
        );

        $body = array(
            'attributes' => $attributes,
            'mediaClips' => $mediaClips,
            'transcodingPresetGroupName' => $presetGroup,
            'priority' => $priority,
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            "/media"
        );
    }

    /**
     * Create a vod media via local file.
     *
     * @param $fileName string, path of local file
     * @param $title string, the title of the media
     * @param $description string, the description of the media, optional
     * @param string $mode the apply media mode
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed created vod media info
     * @throws BceClientException
     */
    public function createMediaFromFile($fileName, $title, $description = '', $mode='', $options = array())
    {
        if (empty($fileName)) {
            throw new BceClientException("The parameter fileName should NOT be null or empty string");
        }

        if (empty($title)) {
            throw new BceClientException("The parameter title should NOT be null or empty string");
        }
        // apply media
        $uploadInfo = $this->applyMedia($mode, $options);
        // upload file to bos
        $this->uploadMedia($fileName, $uploadInfo->sourceBucket, $uploadInfo->sourceKey);
        // process media
        // try to cal the extension of the file
        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (!preg_match("/^[a-z0-9]{0,10}$/", $extension)) {
            $extension = '';
        }
        $options['sourceExtension'] = $extension;

        return $this->processMedia($uploadInfo->mediaId, $title, $description, $options);
    }


    /**
     * Create a vod media via bos object.
     *
     * @param $bucket string, bos bucket name
     * @param $key    string, bos object key
     * @param $title  string, the title of the media
     * @param $description string, the description of the media, optional
     * @param string $mode the apply media mode
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed created vod media info
     * @throws BceClientException
     */
    public function createMediaFromBosObject($bucket, $key, $title, $description = '', $mode = '', $options = array())
    {
        if (empty($bucket)) {
            throw new BceClientException("The parameter fileName should NOT be null or empty string");
        }
        if (empty($key)) {
            throw new BceClientException("The parameter fileName should NOT be null or empty string");
        }
        if (empty($title)) {
            throw new BceClientException("The parameter title should NOT be null or empty string");
        }
        // apply media
        $uploadInfo = $this->applyMedia($mode, $options);
        // copy bos object
        $this->bosClient->copyObject($bucket, $key, $uploadInfo->sourceBucket, $uploadInfo->sourceKey);
        // process media
        // try to cal the extension of the file
        $extension = strtolower(pathinfo($key, PATHINFO_EXTENSION));
        if (!preg_match("/^[a-z0-9]{0,10}$/", $extension)) {
            $extension = '';
        }
        $options['sourceExtension'] = $extension;
        return $this->processMedia($uploadInfo->mediaId, $title, $description, $options);
    }

    /**
     * get the info of a vod media by mediaId
     *
     * @param $mediaId string, mediaId of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed media info
     * @throws BceClientException
     */
    public function getMedia($mediaId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/media/$mediaId"
        );
    }

    /**
     * get the info of current user's all vod media by marker
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *          marker: string, marker of current query
     *          maxSize: int, max size of media(s) of current query
     *          title: string, title prefix of the media(s)
     *          status: string, status of the media(s)
     *          begin: string, the low limit of the createTime of the media(s)
     *          end: string, the upper limit of the createTime of the media(s)
     *      }
     * @return mixed the info of user's all media
     * @throws BceClientException
     */
    public function listMediaByMarker($options = array())
    {
        list($config, $marker, $maxSize, $title, $status, $begin, $end) =
            $this->parseOptions($options, 'config', 'marker', 'maxSize', 'title', 'status', 'begin', 'end');

        $params = array(
            'marker' => $marker,
            'maxSize' => $maxSize,
            'title' => $title,
            'status' => $status,
            'begin' => $begin,
            'end' => $end,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/media'
        );
    }

    /**
     * get the info of current user's all vod media by page
     *
     * @param $pageNo integer, pageNo of the resultSet
     * @param $pageSize integer, pageSize of the resultSet
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *          title: string, title prefix of the media(s)
     *          status: string, status of the media(s)
     *          begin: string, the low limit of the createTime of the media(s)
     *          end: string, the upper limit of the createTime of the media(s)
     *      }
     * @return mixed the info of user's all media
     * @throws BceClientException
     */
    public function listMediaByPage($pageNo,
                                    $pageSize,
                                    $options = array())
    {
        list($config, $title, $status, $begin, $end) =
            $this->parseOptions($options, 'config', 'title', 'status', 'begin', 'end');

        $params = array(
            'pageNo' => $pageNo,
            'pageSize' => $pageSize,
            'title' => $title,
            'status' => $status,
            'begin' => $begin,
            'end' => $end,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/media'
        );
    }

    /**
     * update the attributes of a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param $title string, new title of the media
     * @param $description string, new description of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of updating
     * @throws BceClientException
     */
    public function updateMedia($mediaId, $title, $description, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        if (empty($title)) {
            throw new BceClientException("The parameter title should NOT be null or empty string");
        }

        $body = array(
            'title' => $title,
            'description' => $description,
        );

        $params = array(
            'attributes' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }

    /**
     * update the attributes of a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param $title string, new title of the media
     * @param $description string, new description of the media
     * @param $sourceExtension string, new sourceExtension of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of updating
     * @throws BceClientException
     */
    public function updateMediaAttributes($mediaId, $title, $description, $sourceExtension, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        if (empty($title)) {
            throw new BceClientException("The parameter title should NOT be null or empty string");
        }

        $body = array(
            'title' => $title,
            'description' => $description,
            'sourceExtension' => $sourceExtension,
        );

        $params = array(
            'attributes' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }
    /**
     * disable a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of disabling
     * @throws BceClientException
     */
    public function disableMedia($mediaId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        $params = array(
            'disable' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }

    /**
     * publish a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of publishing
     * @throws BceClientException
     */
    public function publishMedia($mediaId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        $params = array(
            'publish' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }


    /**
     * get the statistic of a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param $startTime string
     * @param $endTime string
     * @param $aggregate string, 'true' or 'false'
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of publishing
     * @throws BceClientException
     */
    public function getMediaStatistic($mediaId,
                                      $startTime,
                                      $endTime,
                                      $aggregate,
                                      $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }
        $params = array();
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        if (!empty($aggregate)) {
            $params['aggregate'] = $aggregate;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistic/media/$mediaId"
        );
    }

    /**
     * delete a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of deleting
     * @throws BceClientException
     */
    public function deleteMedia($mediaId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/media/$mediaId"
        );
    }

    /**
     * get the delivery info of a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the vod media's playable source file and cover page
     * @throws BceClientException
     */
    public function getMediaDelivery($mediaId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/media/$mediaId/delivery"
        );
    }


    /**
     * get the source code for a vod media.
     * vod offer html code and file/cover.
     * html can be simply embed in your html code,
     * while file/cover can be fill in android/ios player or else.
     *
     * @param $mediaId string, mediaId of the media
     * @param $width : integer, the width of the player size
     * @param $height : integer, the height of the player size
     * @param $autoStart : string, whether the player start to play the media automatically
     * @param $ak : string, player code need ak to be filled, if not applied, vod will use ak in config automatically.
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the vod media's playable source file and cover page
     * @throws BceClientException
     */
    public function getMediaCode($mediaId,
                                 $width,
                                 $height,
                                 $autoStart,
                                 $ak,
                                 $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }
        if ($ak == '') {
            $ak = $this->config["credentials"]["ak"];
        }
        $params = array(
            'width' => $width,
            'height' => $height,
            'autostart' => $autoStart,
            'ak' => $ak,
        );

        $response = $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/media/$mediaId/code"
        );
        return $response;
    }


    /**
     * create a new vod notification
     *
     * @param $name string, name of vod notification
     * @param $endpoint string, endpoint of vod notification
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function createNotification($name, $endpoint, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name should NOT be null or empty string");
        }

        if (empty($endpoint)) {
            throw new BceClientException("The parameter endpoint should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
            'endpoint' => $endpoint,
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/notification'
        );
    }

    /**
     * get a vod notification by name
     *
     * @param $name string, name of vod notification
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function getNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }

    /**
     * delete a vod notification by name
     *
     * @param $name string, name of vod notification
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function deleteNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }

    /**
     * list all vod notifications
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function listNotification($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/notification'
        );
    }


    /**
     * get a vod strategy group by name
     *
     * @param $name string, name of vod strategy group
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function getStrategyGroup($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/strategygroup/$name"
        );
    }

    /**
     * list all vod strategy groups
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function listStrategyGroup($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/strategygroup'
        );
    }

    /**
     * get a vod preset group by name
     *
     * @param $name string, name of vod preset group
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function getPresetGroup($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/presetgroup/$name"
        );
    }

    /**
     * list all vod preset groups
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the result of creating
     * @throws BceClientException
     */
    public function listPresetGroup($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/presetgroup'
        );
    }

    /**
     * get the source download info of a vod media
     *
     * @param $mediaId string, mediaId of the media
     * @param $expiredInSeconds integer, expire time of the url
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default vod client configuration that was passed in constructor.
     *      }
     * @return mixed the vod media's playable source file and cover page
     * @throws BceClientException
     */
    public function getMediaSource($mediaId, $expiredInSeconds, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($mediaId)) {
            throw new BceClientException("The parameter mediaId should NOT be null or empty string");
        }
        if (empty($expiredInSeconds)) {
            $expiredInSeconds = -1;
        }

        $params = array(
            'sourcedownload' => null,
            'expiredInSeconds' => $expiredInSeconds,
        );
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/media/$mediaId"
        );
    }





    /**
     * Upload the media source to bos.
     *
     * @param $fileName
     * @param $bucket
     * @param $key
     * @throws \Exception
     */
    private function uploadMedia($fileName, $bucket, $key)
    {
        // init multi-part upload
        $initUploadResponse = $this->bosClient->initiateMultipartUpload($bucket, $key);
        $uploadId = $initUploadResponse->uploadId;

        // do upload part
        try {
            $offset = 0;
            $partNumber = 1;
            $partSize = BosClient::MIN_PART_SIZE;
            $length = $partSize;
            $partList = array();
            $bytesLeft = filesize($fileName);

            while ($bytesLeft > 0) {
                $length = ($length > $bytesLeft) ? $bytesLeft : $length;
                $uploadResponse = $this->bosClient->uploadPartFromFile(
                    $bucket,
                    $key,
                    $uploadId,
                    $partNumber,
                    $fileName,
                    $offset,
                    $length);
                array_push($partList, array(
                    'partNumber' => $partNumber,
                    'eTag' => $uploadResponse->metadata['etag'],
                ));
                $offset += $length;
                $partNumber++;
                $bytesLeft -= $length;
            }

            // complete upload
            $this->bosClient->completeMultipartUpload($bucket, $key, $uploadId, $partList);
        } catch (\Exception $e) {
            $this->bosClient->abortMultipartUpload($bucket, $key, $uploadId);
            throw $e;
        }
    }


    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);
        $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
        return $result;
    }
}
<?php
/*
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Cdn;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;

class CdnClient extends BceBaseClient
{
    /**
     * @var \BaiduBce\Auth\SignerInterface
     */
    private $signer;
    private $httpClient;
    private $prefix = '/v2';

    /**
     * The CdnClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'CdnClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * List all domains of current user.
     *
     * @param array $options None
     * @return domain list the server response.
     * @throws BceClientException
     */
    public function listDomains($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain'
        );
    }

    /**
     * list all domains of this user where options
     *
     * @param $options
     * @return mixed
     */
    public function listUserDomains($options)
    {
        $params = $options;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/user/domains'
        );
    }

    /**
     *query if domain can be add
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function validDomain($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array();

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/valid'
        );
    }

    /**
     * create domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param array $origin [<the origin address list>]
     * @return response
     * @throws BceClientException
     */
    public function createDomain($domain, $origin, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        if (empty($origin)) {
            throw new BceClientException("The parameter origin should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = $options;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('origin' => $origin)),
            ),
            '/domain/'.$domain
        );
    }

    /**
     * delete a domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @return response
     * @throws BceClientException
     */
    public function deleteDomain($domain, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = $options;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain/'.$domain
        );
    }

    /**
     * enable a domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @return response
     * @throws BceClientException
     */
    public function enableDomain($domain, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('enable' => '');

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain/'.$domain
        );
    }

    /**
     * disable a domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @return response
     * @throws BceClientException
     */
    public function disableDomain($domain, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('disable' => '');

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain/'.$domain
        );
    }

    /**
     * update origin address of the domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param array $origin [<the origin address list>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainOrigin($domain, $origin, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        if (empty($origin)) {
            throw new BceClientException("The parameter origin should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('origin' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('origin' => $origin)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get configuration of the domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainConfig($domain, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = $options;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain cacheShare
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainCacheShare($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('cacheShare' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain cacheShare
     *
     * @param $domain
     * @param $cacheShare
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainCacheShare($domain, $cacheShare)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($cacheShare)) {
            throw new BceClientException("The parameter cacheShare should NOT be empty");
        }

        $params = array('cacheShare' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($cacheShare)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain trafficLimit
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainTrafficLimit($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('trafficLimit' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain trafficLimit
     *
     * @param $domain
     * @param $trafficLimit
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainTrafficLimit($domain, $trafficLimit)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($trafficLimit)) {
            throw new BceClientException("The parameter trafficLimit should NOT be empty");
        }

        $params = array('trafficLimit' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($trafficLimit)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain uaAcl
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainUaACL($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('uaAcl' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set request ua access control
     *
     * @param string $domain
     * @param string $flag white or black
     * @param array $aclList
     * @param array $options
     * @return response
     * @throws BceClientException
     */
    public function setDomainUaAcl($domain, $flag, $aclList)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }
        if (empty($flag) || (($flag != 'black') && ($flag != 'white'))) {
            throw new BceClientException("The parameter flag should be black or white");

        }
        if (!is_array($aclList)) {
            throw new BceClientException("Acl list must be array, please check your input");
        }

        $params = array('uaAcl' => '');

        $acl = array();
        if ($flag == 'white') {
            $acl['whiteList'] = $aclList;
        }
        if ($flag == 'black') {
            $acl['blackList'] = $aclList;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode(array('uaAcl' => $acl)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain originProtocol
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainOriginProtocol($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('originProtocol' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain originProtocol
     *
     * @param $domain
     * @param $originProtocol
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainOriginProtocol($domain, $originProtocol)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($originProtocol)) {
            throw new BceClientException("The parameter originProtocol should NOT be empty");
        }

        $params = array('originProtocol' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($originProtocol)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain retryOrigin
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainRetryOrigin($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('retryOrigin' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain retryOrigin
     *
     * @param $domain
     * @param $retryOrigin
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainRetryOrigin($domain, $retryOrigin)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($retryOrigin)) {
            throw new BceClientException("The parameter retryOrigin should NOT be empty");
        }

        $params = array('retryOrigin' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($retryOrigin)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain ipv6Dispatch
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainIpv6Dispatch($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('ipv6Dispatch' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain ipv6Dispatch
     *
     * @param $domain
     * @param $ipv6Dispatch
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainIpv6Dispatch($domain, $ipv6Dispatch)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($ipv6Dispatch)) {
            throw new BceClientException("The parameter ipv6Dispatch should NOT be empty");
        }

        $params = array('ipv6Dispatch' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($ipv6Dispatch)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain quic
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainQuic($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('quic' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain quic
     *
     * @param $domain
     * @param $quic
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainQuic($domain, $quic)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($quic)) {
            throw new BceClientException("The parameter quic should NOT be empty");
        }

        $params = array('quic' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($quic)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain offlineMode
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainOfflineMode($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('offlineMode' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain offlineMode
     *
     * @param $domain
     * @param $offlineMode
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainOfflineMode($domain, $offlineMode)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($offlineMode)) {
            throw new BceClientException("The parameter offlineMode should NOT be empty");
        }

        $params = array('offlineMode' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($offlineMode)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain ocsp
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainOcsp($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('ocsp' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain ocsp
     *
     * @param $domain
     * @param $ocsp
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainOcsp($domain, $ocsp)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be empty");
        }
        if (empty($ocsp)) {
            throw new BceClientException("The parameter ocsp should NOT be empty");
        }

        $params = array('ocsp' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($ocsp)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get baidu back to source ip address segment
     * 
     * @return mixed
     */
    public function getNodesList()
    {
        $params = array();
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/nodes/list'
        );
    }

    /**
     * get domain errorPage
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainErrorPage($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('errorPage' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain errorPage
     *
     * @param $domain
     * @param $errorPage
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainErrorPage($domain, $errorPage)
    {
        if (empty($domain) || empty($errorPage)) {
            throw new BceClientException("The parameter domain and errorPage should NOT be null");
        }

        $params = array('errorPage' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($errorPage)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set domain requestAuth
     *
     * @param $domain
     * @param $requestAuth
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainRequestAuth($domain, $requestAuth)
    {
        if (empty($domain) || empty($requestAuth)) {
            throw new BceClientException("The parameter domain and requestAuth should NOT be null");
        }

        $params = array('requestAuth' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($requestAuth)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get Cross-domain setting of domain
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainCors($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('cors' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set Cross-domain setting of domain
     *
     * @param $domain
     * @param array $cors
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainCors($domain, $cors = array())
    {
        if (empty($domain) || empty($cors)) {
            throw new BceClientException("The parameter domain and cors should NOT be null");
        }

        $params = array('cors' => '');
        $body = $cors;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get IP access frequency limit settings
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainAccessLimit($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('accessLimit' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set IP access frequency limit
     *
     * @param $domain
     * @param array $accessLimit
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainAccessLimit($domain, $accessLimit = array())
    {
        if (empty($domain) || empty($accessLimit)) {
            throw new BceClientException("The parameter domain and accessLimit should NOT be null");
        }

        $params = array('accessLimit' => '');
        $body = $accessLimit;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get User Real IP
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainClientIp($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('clientIp' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set User Real IP setting
     *
     * @param $domain
     * @param array $clientIp
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainClientIp($domain, $clientIp = array())
    {
        if (empty($domain) || empty($clientIp)) {
            throw new BceClientException("The parameter domain and clientIp should NOT be null");
        }

        $params = array('clientIp' => '');
        $body = $clientIp;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set Protocol Following Back Source
     *
     * @param $domain
     * @param array $followProtocol
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainFollowProtocol($domain, $followProtocol = array())
    {
        if (empty($domain) || empty($followProtocol)) {
            throw new BceClientException("The parameter domain and followProtocol should NOT be null");
        }

        $params = array('followProtocol' => '');
        $body = $followProtocol;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get range back source settings
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainRangeSwitch($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('rangeSwitch' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set range back source
     *
     * @param $domain
     * @param array $rangeSwitch
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainRangeSwitch($domain, $rangeSwitch = array())
    {
        if (empty($domain) || empty($rangeSwitch)) {
            throw new BceClientException("The parameter domain and rangeSwitch should NOT be null");
        }

        $params = array('rangeSwitch' => '');
        $body = $rangeSwitch;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get Mobile Access Control Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainMobileAccess($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('mobileAccess' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set Mobile Access Control Configuration
     *
     * @param $domain
     * @param array $mobileAccess
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainMobileAccess($domain, $mobileAccess = array())
    {
        if (empty($domain) || empty($mobileAccess)) {
            throw new BceClientException("The parameter domain and mobileAccess should NOT be null");
        }

        $params = array('mobileAccess' => '');
        $body = $mobileAccess;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get HttpHeader Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainHttpHeader($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('httpHeader' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set HttpHeader Configuration
     *
     * @param $domain
     * @param array $httpHeader
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainHttpHeader($domain, $httpHeader = array())
    {
        if (empty($domain) || empty($httpHeader)) {
            throw new BceClientException("The parameter domain and httpHeader should NOT be null");
        }

        $params = array('httpHeader' => '');
        $body = $httpHeader;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get seoSwitch Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainSeoSwitch($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('seoSwitch' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set seoSwitch Configuration
     *
     * @param $domain
     * @param array $seoSwitch
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainSeoSwitch($domain, $seoSwitch = array())
    {
        if (empty($domain) || empty($seoSwitch)) {
            throw new BceClientException("The parameter domain and seoSwitch should NOT be null");
        }

        $params = array('seoSwitch' => '');
        $body = $seoSwitch;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get fileTrim Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainFileTrim($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('fileTrim' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set fileTrim Configuration
     *
     * @param $domain
     * @param array $fileTrim
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainFileTrim($domain, $fileTrim = array())
    {
        if (empty($domain) || empty($fileTrim)) {
            throw new BceClientException("The parameter domain and fileTrim should NOT be null");
        }

        $params = array('fileTrim' => '');
        $body = $fileTrim;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get mediaDrag Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainMediaDrag($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('mediaDrag' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set mediaDrag Configuration
     *
     * @param $domain
     * @param array $mediaDrag
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainMediaDrag($domain, $mediaDrag = array())
    {
        if (empty($domain) || empty($mediaDrag)) {
            throw new BceClientException("The parameter domain and mediaDrag should NOT be null");
        }

        $params = array('mediaDrag' => '');
        $body = $mediaDrag;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get compress Configuration
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainCompress($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('compress' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set compress Configuration
     *
     * @param $domain
     * @param array $compress
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainCompress($domain, $compress = array())
    {
        if (empty($domain) || empty($compress)) {
            throw new BceClientException("The parameter domain and compress should NOT be null");
        }

        $params = array('compress' => '');
        $body = $compress;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set https Configuration
     *
     * @param $domain
     * @param array $https
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainHttps($domain, $https = array())
    {
        if (empty($domain) || empty($https)) {
            throw new BceClientException("The parameter domain and https should NOT be null");
        }

        $params = array('https' => '');
        $body = $https;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get cache rules of a domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainCacheTTL($domain, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('cacheTTL' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set cache rules of a domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param array $rules [<cache ruless>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainCacheTTL($domain, $rules, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }
        if (empty($rules) || !is_array($rules)) {
            throw new BceClientException("The parameter rules should be a non empty array");
        }
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }

        $params = array('cacheTTL' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('cacheTTL' => $rules)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get the cacheFullUrl
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainCacheFullUrl($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('cacheFullUrl' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set if use the full url as cache key
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param bool $flag [<if use the full url as cache key>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainCacheFullUrl($domain, $flag, $options = array())
    {
        if (empty($domain) || empty($flag)) {
            throw new BceClientException("The parameter domain or flag should NOT be null");
        }
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }

        $params = array('cacheFullUrl' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('cacheFullUrl' => $flag)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain ipACL
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainIpACL($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('ipACL' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set request ip access control
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param array $blackList [<ip black list>]
     * @param array $whiteList [<ip white list>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainIpAcl($domain, $flag, $aclList, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }
        if (empty($flag) || (($flag != 'black') && ($flag != 'white'))) {
            throw new BceClientException("The parameter flag should be black or white");

        }
        if (empty($aclList)) {
            throw new BceClientException("Acl list is empty, please check your input");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('ipACL' => '');

        $acl = array();
        if ($flag == 'white') {
            $acl['whiteList'] = $aclList;
        }
        if ($flag == 'black') {
            $acl['blackList'] = $aclList;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('ipACL' => $acl)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get domain refererAcl
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainRefererAcl($domain)
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        $params = array('refererACL' => '');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set request referer access control
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param array $blackList [<referer black list>]
     * @param array $whiteList [<referer white list>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainRefererAcl($domain, $flag, $allowEmpty,
                                        $aclList, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }
        if (empty($flag) || (($flag != 'black') && ($flag != 'white'))) {
            throw new BceClientException("The parameter flag should be black or white");

        }
        if (empty($aclList)) {
            throw new BceClientException("Acl list is empty, please check your input");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('refererACL' => '');

        $acl = array();
        $acl['allowEmpty'] = $allowEmpty;
        if ($flag == 'white') {
            $acl['whiteList'] = $aclList;
        }
        if ($flag == 'black') {
            $acl['blackList'] = $aclList;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('refererACL' => $acl)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * set limit rate
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param int $rate [<limit rate value (Byte/s)>]
     * @return response
     * @throws BceClientException
     */
    public function setDomainLimitRate($domain, $rate, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }
        if (empty($rate) || !is_int($rate)) {
            throw new BceClientException("The parameter rate should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array('limitRate' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode(array('limitRate' => $rate)),
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * query pv and qps of the domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @param int $withRegion [<if need client region distribution>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainPvStat($domain=null, $startTime=null, $endTime=null,
                                    $period=300, $withRegion=null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;
        $params['withRegion'] = $withRegion;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/pv'
        );
    }

    /**
     * query the total number of client of a domain or all domains of the user
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainUvStat($domain=null, $startTime=null, $endTime=null,
                                    $period=3600, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/uv'
        );
    }

    /**
     * query average of the domain or all domains of the user
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainAvgSpeedStat($domain=null, $startTime=null, $endTime=null,
                                          $period=300, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/avgspeed'
        );
    }

    /**
     * query bandwidth of the domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @param int $withRegion [<if need client region distribution>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainFlowStat($domain=null, $startTime=null, $endTime=null,
                                      $period=300, $withRegion=null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;
        $params['withRegion'] = $withRegion;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/flow'
        );
    }

    /**
     * @param $options array
     * @return response
     */
    public function getDomainSrcFlowStat($domain=null, $startTime=null, $endTime=null,
                                         $period=300, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/srcflow'
        );
    }

    /**
     * query hit rate of the domain
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainHitRateStat($domain=null, $startTime=null, $endTime=null,
                                         $period=300, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/hitrate'
        );
    }

    /**
     * query http response code of a domain or all domains of the user
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @param int $withRegion [<if need client region distribution>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainHttpCodeStat($domain=null, $startTime=null, $endTime=null,
                                          $period=300, $withRegion=null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;
        $params['withRegion'] = $withRegion;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/httpcode'
        );
    }

    /**
     * query top n url of the domain or all domains of the user
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainTopUrlStat($domain=null, $startTime=null, $endTime=null,
                                        $period=3600, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/topn/url'
        );
    }

    /**
     * query top n referer of the domain or all domains of the user
     * @param array $options None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $period [<time interval of query result>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainTopRefererStat($domain=null, $startTime=null, $endTime=null,
                                            $period=3600, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['domain'] = $domain;
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        $params['period'] = $period;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/stat/topn/referer'
        );
    }

    /**
     * get refresh and preload records for specified conditions
     *
     * @param $domain
     * @return mixed
     * @throws BceClientException
     */
    public function getRecords($recordsParams = array())
    {
        $params = $recordsParams;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'params' => $params,
            ),
            '/cache/records'
        );
    }

    /**
     * purge the cache of specified url or directory
     * @param array $tasks The task list
     *      {
     *          url: The url to be purged.
     *          type: 'file' or 'directory'
     *      }
     * @param array $options None
     * @return task id
     * @throws BceClientException
     */
    public function purge(array $tasks, $options = array())
    {
        if (empty($tasks)) {
            throw new BceClientException("The parameter tasks "
                ."should NOT be null or empty array");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        if (!empty($config)) {
            unset($options['config']);
        }
        $params = $options;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode(array(
                    'tasks' => $tasks
                )),
                'params' => $params,
            ),
            '/cache/purge'
        );
    }

    /**
     * Get status of specified purge task.
     *
     * @param array $options None
     * @param string $taskId [<purge task id to query>]
     * @param string $url [<purge url to query>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $marker [<'nextMarker' get from last query>]
     * @throws BceClientException
     * @return response
     */
    public function listPurgeStatus($taskId = null, $url = null, $startTime = null,
                                    $endTime = null, $marker = null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();

        if (!empty($taskId)) {
            $params['id'] = $taskId;
        }
        if (!empty($url)) {
            $params['url'] = $url;
        }
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/cache/purge'
        );
    }

    /**
     * prefetch the source of specified url from origin
     * @param array $options None
     * @param array $tasks The task list
     *      {
     *          url: The url to be prefetch.
     *          speed: The flowrate limit of this prefetch task.
     *          startTime: Schedule the prefetch task to specified time.
     *      }
     * @return task id
     * @throws BceClientException
     */
    public function prefetch(array $tasks, $options = array())
    {
        if (empty($tasks)) {
            throw new BceClientException("The parameter tasks "
                ."should NOT be null or empty array");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        if (!empty($config)) {
            unset($options['config']);
        }
        $params = $options;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode(array(
                    'tasks' => $tasks
                )),
                'params' => $params,
            ),
            '/cache/prefetch'
        );
    }

    /**
     * query the status of prefetch tasks
     * @param array $options None
     * @param string $taskId [<purge task id to query>]
     * @param string $url [<purge url to query>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @param int $marker [<'nextMarker' get from last query>]
     * @throws BceClientException
     * @return response
     */
    public function listPrefetchStatus($taskId = null, $url = null, $startTime = null,
                                       $endTime = null, $marker = null, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();

        if (!empty($taskId)) {
            $params['id'] = $taskId;
        }
        if (!empty($url)) {
            $params['url'] = $url;
        }
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/cache/prefetch'
        );
    }

    /**
     * query purge quota of the user
     * @param $options array None
     * @throws BceClientException
     * @return response
     */
    public function listQuota($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/cache/quota'
        );
    }

    /**
     * get log of the domain in specified period of time
     * @param $options array None
     * @param string $domain [<the domain name>]
     * @param timestamp $startTime [<query start time>]
     * @param timestamp $endTime [<query end time>]
     * @return response
     * @throws BceClientException
     */
    public function getDomainLog($domain, $startTime = null, $endTime = null, $options = array())
    {
        if (empty($domain)) {
            throw new BceClientException("The parameter domain should NOT be null");
        }

        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        if (!empty($startTime)) {
            $params['startTime'] = $startTime;
        }
        if (!empty($endTime)) {
            $params['endTime'] = $endTime;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/log/'.$domain.'/log'
        );
    }

    /**
     * get log of the domain list in specified period of time
     *
     * @param array $options
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainsLog($options = array())
    {
        if (empty($options)) {
            throw new BceClientException("The parameter options should NOT be null");
        }

        $body = $options;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'body' => json_encode($body)
            ),
            '/log/list'
        );
    }

    /**
     * check specified ip if belongs to Baidu CDN
     * @param $options array None
     * @param string $ip [<specified ip>]
     * @return response
     * @throws BceClientException
     */
    public function ipQuery($action, $ip, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');

        if (!empty($config)) {
            unset($options['config']);
        }
        $params = array();
        $params['action'] = $action;
        $params['ip'] = $ip;

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/utils'
        );
    }

    /**
     * query stats of the domain or uid or tagId, eg : flow pv
     * @param $statParam array stat query parameters
     * @param $options array None
     * @return response
     * @throws BceClientException
     */
    public function getDomainStats(array $statParam, $options = array()) {
        list($config) = $this->parseOptionsIgnoreExtra($options, 'config');
        $params = $options;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($statParam),
                'params' => $params,
            ),
            '/stat/query'
        );
    }

    /**
     * open/close dynamic acceleration service
     *
     * @param array $action
     * @return mixed
     * @throws BceClientException
     */
    public function setDsa($action = array())
    {
        if (empty($action)) {
            throw new BceClientException("The parameter action should NOT be null");
        }

        $body = $action;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'body' => json_encode($body)
            ),
            '/dsa'
        );
    }

    /**
     * set Dynamic Acceleration Rules
     *
     * @param array $dsa
     * @return mixed
     * @throws BceClientException
     */
    public function setDomainDsa($domain, $dsa = array())
    {
        if (empty($domain) || empty($dsa)) {
            throw new BceClientException("The parameter domain and dsa should NOT be null");
        }

        $body = $dsa;
        $params = array('dsa' => '');

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'params' => $params,
                'body' => json_encode($body)
            ),
            '/domain/'.$domain.'/config'
        );
    }

    /**
     * get dsa domain list
     *
     * @return mixed
     */
    public function getDomainDsa()
    {

        return $this->sendRequest(
            HttpMethod::GET,
            array(

            ),
            '/dsa/domain'
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);
        $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
        return $result;
    }
}
<?php
/*
* Copyright 2015 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Mvs;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;

class MvsClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefixV2 = '/v2';

    /**
     * The MvsClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'MvsClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Insert one media.
     *
     * @param $lib string, lib name
     * @param $source string, media source
     * @param $notification string, notification
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed insert detail
     * @throws BceClientException
     */
    public function insertVideo($lib, $source, $notification, $options = array())
    {
        list($config, $description) = $this->parseOptions($options, 'config', 'description');

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }
        if (empty($notification)) {
            throw new BceClientException("The parameter notification "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
            'notification' => $notification
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }

    /**
     * Search video by video.
     *
     * @param $lib string, lib name
     * @param $source string, media source
     * @param $notification string, notification
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed search video by video detail
     * @throws BceClientException
     */
    public function searchVideoByVideo($lib, $source, $notification, $options = array())
    {
        list($config, $description) = $this->parseOptions($options, 'config', 'description');

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }
        if (empty($notification)) {
            throw new BceClientException("The parameter notification "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
            'notification' => $notification
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => array('searchByVideo' => '')
            ),
            $this->prefixV2,
            "/videolib/$lib"
        );
    }


    /**
     * Insert one image.
     *
     * @param $lib string, lib name
     * @param $source string, media source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed insert detail
     * @throws BceClientException
     */
    public function insertImage($lib, $source, $options = array())
    {
        list($config, $description) = $this->parseOptions($options, 'config', 'description');

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => array('search' => ''),
            ),
            $this->prefixV2,
            "/imagelib/$lib"
        );
    }

    /**
     * Insert one image.
     *
     * @param $lib string, lib name
     * @param $source string, media source
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed insert detail
     * @throws BceClientException
     */
    public function searchImageByImage($lib, $source, $options = array())
    {
        list($config, $description) = $this->parseOptions($options, 'config', 'description');

        if (empty($lib)) {
            throw new BceClientException("The parameter lib "
                . "should NOT be null or empty string");
        }
        if (empty($source)) {
            throw new BceClientException("The parameter source "
                . "should NOT be null or empty string");
        }

        $body = array(
            'source' => $source,
        );

        if ($description != null) {
            $body['description'] = $description;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => array('searchByImage' => ''),
            ),
            $this->prefixV2,
            "/imagelib/$lib"
        );
    }


    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $prefix, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
}
<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bcc;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Services\Bcc\model\Billing;
use BaiduBce\Services\Bcc\model\SecurityGroupRuleModel;

/**
 * This module provides a client class for BCC.
 */
class BccClient extends BceBaseClient 
{

    private $signer;
    private $httpClient;
    private $prefix = '/v2';

    /**
     * The BccClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'bcc');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create a bcc Instance with the specified options.
     * You must fill the field of clientToken,which is especially for keeping idempotent.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceType (unicode)
     *          The specified Specification to create the instance,
     *          See more detail on
     *               https://cloud.baidu.com/doc/BCC/API.html#InstanceType
     *
     * @param int $cpuCount
     *          The parameter to specified the cpu core to create the instance.
     *
     * @param int $memoryCapacityInGB
     *          The parameter to specified the capacity of memory in GB to create the instance.
     *
     * @param string $imageId (unicode)
     *          The id of image, list all available image in BccClient.listImages.
     *
     * @param Billing $billing
     *          Billing information.
     *
     * @param int $localDiskSizeInGB
     *          The optional parameter to specify the temporary disk size in GB.
     *          The temporary disk excludes the system disk, available is 0-500GB.
     *
     * @param array $createCdsList
     *          The optional array of volume detail info to create.
     *
     * @param int $networkCapacityInMbps
     *          The optional parameter to specify the bandwidth in Mbps for the new instance.
     *          It must among 0 and 200, default value is 0.
     *          If it's specified to 0, it will get the internal ip address only.
     *
     * @param int $purchaseCount
     *          The number of instance to buy, the default value is 1.
     *
     * @param string $name
     *          The optional parameter to desc the instance that will be created.
     *
     * @param string $adminPass
     *          The optional parameter to specify the password for the instance.
     *          If specify the adminPass,the adminPass must be a 8-16 characters String
     *          which must contains letters, numbers and symbols.
     *          The symbols only contains "!@#$%^*()".
     *          The adminPass will be encrypted in AES-128 algorithm
     *          with the substring of the former 16 characters of user SecretKey.
     *          If not specify the adminPass, it will be specified by an random string.
     *          See more detail on
     *               https://bce.baidu.com/doc/BCC/API.html#.7A.E6.31.D8.94.C1.A1.C2.1A.8D.92.ED.7F.60.7D.AF
     *
     * @param string $zoneName
     *          The optional parameter to specify the available zone for the instance.
     *          See more detail through listZones method
     *
     * @param string $subnetId
     *          The optional parameter to specify the id of subnet from vpc, optional param
     *          default value is default subnet from default vpc
     *
     * @param string $securityGroupId
     *          The optional parameter to specify the securityGroupId of the instance
     *          vpcId of the securityGroupId must be the same as the vpcId of subnetId
     *          See more detail through listSecurityGroups method
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createInstance($cpuCount, $memoryCapacityInGB, $imageId, $options = array())
    {
        list($instanceType, $billing, $localDiskSizeInGB, $createCdsList, $networkCapacityInMbps,
            $purchaseCount, $name, $adminPass, $zoneName, $subnetId, $securityGroupId,
            $clientToken, $config) = $this->parseOptions($options,
            'instanceType',
            'billing',
            'localDiskSizeInGB',
            'createCdsList',
            'networkCapacityInMbps',
            'purchaseCount',
            'name',
            'adminPass',
            'zoneName',
            'subnetId',
            'securityGroupId',
            'clientToken',
            'config');
        $params = array();
        if ($clientToken !== null) {
            $params['clientToken'] = $clientToken;
        } else {
            $params['clientToken'] = $this->generateClientToken();
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBilling();
        }
        if (empty($cpuCount)) {
            throw new \InvalidArgumentException(
                '$cpuCount should not be empty.'
            );
        }
        if (empty($memoryCapacityInGB)) {
            throw new \InvalidArgumentException(
                '$memoryCapacityInGb should not be empty.'
            );
        }
        if (empty($imageId)) {
            throw new \InvalidArgumentException(
                '$imageId should not be empty.'
            );
        }
        $body = array();
        $body['cpuCount'] = $cpuCount;
        $body['memoryCapacityInGB'] = $memoryCapacityInGB;
        $body['imageId'] = $imageId;
        $body['billing'] = $this->objectToArray($billing);
        if ($instanceType !== null) {
            $body['instanceType'] = $instanceType;
        }
        if (!empty($localDiskSizeInGB)) {
            $body['localDiskSizeInGB'] = $localDiskSizeInGB;
        }
        if ($createCdsList !== null) {
            $body['createCdsList'] = $createCdsList;
        }
        if (!empty($networkCapacityInMbps)) {
            $body['networkCapacityInMbps'] = $networkCapacityInMbps;
        }
        if (empty($purchaseCount)) {
            $purchaseCount = 1;
        }
        $body['purchaseCount'] = $purchaseCount;
        if ($name !== null) {
            $body['name'] = $name;
        }
        if ($adminPass !== null) {
            $credentials = $this->config[BceClientConfigOptions::CREDENTIALS];
            $secretAccessKey = null;
            if(isset($credentials['sk'])){
                $secretAccessKey = $credentials['sk'];
            }
            if(isset($credentials['secretAccessKey'])){
                $secretAccessKey = $credentials['secretAccessKey'];
            }
            $cipherAdminPass = $this->aes128WithFirst16Char($adminPass, $secretAccessKey);
            $body['adminPass'] = $cipherAdminPass;
        }
        if ($zoneName !== null) {
            $body['zoneName'] = $zoneName;
        }
        if ($subnetId != null) {
            $body['subnetId'] = $subnetId;
        }
        if ($securityGroupId != null) {
            $body['securityGroupId'] = $securityGroupId;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance'
        );
    }

    /**
     * Create a Instance from dedicatedHost with the specified options.
     * You must fill the field of clientToken,which is especially for keeping idempotent.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param int $cpuCount
     *          The specified number of cpu core to create the instance,
     *          is less than or equal to the remain of dedicated host.
     *
     * @param int $memoryCapacityInGB
     *          The capacity of memory to create the instance,
     *          is less than or equal to the remain of dedicated host.
     *
     * @param string $imageId
     *          The id of image, list all available image in BccClient.listImages.
     *
     * @param string $dedicatedHostId (unicode)
     *          The id of dedicated host, we can locate the instance in specified dedicated host.
     *
     * @param array $ephemeralDisks
     *          The optional array of ephemeral volume detail info to create.
     *
     * @param int $purchaseCount
     *          The number of instance to buy, the default value is 1.
     *
     * @param string $name
     *          The optional parameter to desc the instance that will be created.
     *
     * @param string $adminPass
     *          The optional parameter to specify the password for the instance.
     *          If specify the adminPass,the adminPass must be a 8-16 characters String
     *          which must contains letters, numbers and symbols.
     *          The symbols only contains "!@#$%^*()".
     *          The adminPass will be encrypted in AES-128 algorithm
     *          with the substring of the former 16 characters of user SecretKey.
     *          If not specify the adminPass, it will be specified by an random string.
     *          See more detail on
     *              https://bce.baidu.com/doc/BCC/API.html#.7A.E6.31.D8.94.C1.A1.C2.1A.8D.92.ED.7F.60.7D.AF
     *
     * @param string $subnetId
     *          The optional parameter to specify the id of subnet from vpc, optional param
     *          default value is default subnet from default vpc
     *
     * @param string $securityGroupId
     *          The optional parameter to specify the securityGroupId of the instance
     *          vpcId of the securityGroupId must be the same as the vpcId of subnetId
     *          See more detail through listSecurityGroups method
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createInstanceFromDedicatedHost($cpuCount, $memoryCapacityInGB, $imageId, $dedicatedHostId,
                                                    $options = array())
    {
        list($ephemeralDisks, $purchaseCount, $name, $adminPass, $subnetId, $securityGroupId,
            $clientToken, $config) = $this->parseOptions($options,
            'ephemeralDisks',
            'purchaseCount',
            'name',
            'adminPass',
            'subnetId',
            'securityGroupId',
            'clientToken',
            'config');
        $params = array();
        if ($clientToken !== null) {
            $params['clientToken'] = $clientToken;
        } else {
            $params['clientToken'] = $this->generateClientToken();
        }
        if (empty($cpuCount)) {
            throw new \InvalidArgumentException(
                '$cpuCount should not be empty.'
            );
        }
        if (empty($memoryCapacityInGB)) {
            throw new \InvalidArgumentException(
                '$memoryCapacityInGb should not be empty.'
            );
        }
        if (empty($imageId)) {
            throw new \InvalidArgumentException(
                '$imageId should not be empty.'
            );
        }
        if (empty($dedicatedHostId)) {
            throw new \InvalidArgumentException(
                '$dedicatedHostId should not be empty.'
            );
        }
        $body = array();
        $body['cpuCount'] = $cpuCount;
        $body['memoryCapacityInGB'] = $memoryCapacityInGB;
        $body['imageId'] = $imageId;
        $body['dedicatedHostId'] = $dedicatedHostId;
        if ($ephemeralDisks !== null) {
            $body['ephemeralDisks'] = $this->objectToArray($ephemeralDisks);
        }
        if (empty($purchaseCount)) {
            $purchaseCount = 1;
        }
        $body['purchaseCount'] = $purchaseCount;
        if ($name !== null) {
            $body['name'] = $name;
        }
        if ($adminPass !== null) {
            $body['adminPass'] = $adminPass;
        }

        print_r(json_encode($body));
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance'
        );
    }

    /**
     * Return a array of instances owned by the authenticated user.
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param string $internalIp
     *          The identified internal ip of instance.
     *
     * @param string $dedicatedHostId
     *          get instance list filtered by id of dedicated host
     *
     * @param string $zoneName
     *          get instance list filtered by name of available zone
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listInstances($marker=null, $maxKeys=null, $internalIp=null, $dedicatedHostId=null,
                                  $zoneName=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        if ($internalIp !== null) {
            $params['internalIp'] = $internalIp;
        }
        if ($dedicatedHostId !== null) {
            $params['dedicatedHostId'] = $dedicatedHostId;
        }
        if ($zoneName !== null) {
            $params['zoneName'] = $zoneName;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/instance'
        );
    }

    /**
     * Get the detail information of specified instance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function getInstance($instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Starting the instance owned by the user.
     * You can start the instance only when the instance is Stopped,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          id of instance proposed to start.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function startInstance($instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $params['start'] = null;
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Stopping the instance owned by the user.
     * You can stop the instance only when the instance is Running,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param bool $forceStop
     *          The optional parameter to stop the instance forcibly.If true,
     *          it will stop the instance just like power off immediately
     *          and it may result in losing important data which have not been written to disk.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function stopInstance($instanceId, $forceStop=false, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['forceStop'] = $forceStop;
        $params = array();
        $params['stop'] = null;
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Rebooting the instance owned by the user.
     * You can reboot the instance only when the instance is Running,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.get_instance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param bool $forceStop
     *          The optional parameter to stop the instance forcibly.If true,
     *          it will stop the instance just like power off immediately
     *          and it may result in losing important data which have not been written to disk.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function rebootInstance($instanceId, $forceStop=false, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['forceStop'] = $forceStop;
        $params = array();
        $params['reboot'] = null;
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Modifying the password of the instance.
     * You can change the instance password only when the instance is Running or Stopped ,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param string $adminPass (unicode)
     *          The new password to update.
     *          The adminPass will be encrypted in AES-128 algorithm
     *          with the substring of the former 16 characters of user SecretKey.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function modifyInstancePassword($instanceId, $adminPass, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($adminPass)) {
            throw new \InvalidArgumentException(
                'request $adminPass should not be empty.'
            );
        }
        $body = array();
        $credentials = $this->config[BceClientConfigOptions::CREDENTIALS];
        $secretAccessKey = null;
        if(isset($credentials['sk'])){
            $secretAccessKey = $credentials['sk'];
        }
        if(isset($credentials['secretAccessKey'])){
            $secretAccessKey = $credentials['secretAccessKey'];
        }
        $cipherAdminPass = $this->aes128WithFirst16Char($adminPass, $secretAccessKey);
        $body['adminPass'] = $cipherAdminPass;
        $params = array();
        $params['changePass'] = null;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Modifying the special attribute to new value of the instance.
     * You can reboot the instance only when the instance is Running or Stopped ,
     * otherwise, it's will get 409 errorCode.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param string $name (unicode)
     *          The new value for instance's name.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function modifyInstanceAttributes($instanceId, $name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($name)) {
            throw new \InvalidArgumentException(
                'request $name should not be empty.'
            );
        }
        $body = array();
        $body['name'] = $name;
        $params = array();
        $params['modifyAttribute'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Rebuilding the instance owned by the user.
     * After rebuilding the instance,
     * all of snapshots created from original instance system disk will be deleted,
     * all of customized images will be saved for using in the future.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param string $imageId (unicode)
     *          The id of the image which is used to rebuild the instance.
     *
     * @param string $adminPass (unicode)
     *          The admin password to login the instance.
     *          The admin password will be encrypted in AES-128 algorithm
     *          with the substring of the former 16 characters of user SecretKey.
     *          See more detail on
     *              https://bce.baidu.com/doc/BCC/API.html#.7A.E6.31.D8.94.C1.A1.C2.1A.8D.92.ED.7F.60.7D.AF
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function rebuildInstance($instanceId, $imageId, $adminPass, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($imageId)) {
            throw new \InvalidArgumentException(
                'request $imageId should not be empty.'
            );
        }
        if (empty($adminPass)) {
            throw new \InvalidArgumentException(
                'request $adminPass should not be empty.'
            );
        }
        $body = array();
        $credentials = $this->config[BceClientConfigOptions::CREDENTIALS];
        $secretAccessKey = null;
        if(isset($credentials['sk'])){
            $secretAccessKey = $credentials['sk'];
        }
        if(isset($credentials['secretAccessKey'])){
            $secretAccessKey = $credentials['secretAccessKey'];
        }
        $cipherAdminPass = $this->aes128WithFirst16Char($adminPass, $secretAccessKey);
        $body['imageId'] = $imageId;
        $body['adminPass'] = $cipherAdminPass;

        $params = array();
        $params['rebuild'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Releasing the instance owned by the user.
     * Only the Postpaid instance or Prepaid which is expired can be released.
     * After releasing the instance,
     * all of the data will be deleted.
     * all of volumes attached will be auto detached, but the volume snapshots will be saved.
     * all of snapshots created from original instance system disk will be deleted,
     * all of customized images created from original instance system disk will be reserved.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function releaseInstance($instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Resizing the instance owned by the user.
     * The Prepaid instance can not be downgrade.
     * Only the Running/Stopped instance can be resized, otherwise, it's will get 409 errorCode.
     * After resizing the instance,it will be reboot once.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          The id of instance.
     *
     * @param int $cpuCount
     *          The parameter of specified the cpu core to resize the instance.
     *
     * @param int $memoryCapacityInGB
     *          The parameter of specified the capacity of memory in GB to resize the instance.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function resizeInstance($instanceId, $cpuCount, $memoryCapacityInGB, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($cpuCount)) {
            throw new \InvalidArgumentException(
                'request $cpuCount should be positive.'
            );
        }
        if (empty($memoryCapacityInGB)) {
            throw new \InvalidArgumentException(
                'request $memoryCapacityInGB should be positive.'
            );
        }
        $body = array();
        $body['cpuCount'] = $cpuCount;
        $body['memoryCapacityInGB'] = $memoryCapacityInGB;
        $params = array();
        if (empty($clientToken)) {
            $params['resize'] = null;
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['resize'] = null;
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Binding the instance to specified securitygroup.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance.
     *
     * @param string $securityGroupId (unicode)
     *          The id of the securitygroup.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function bindInstanceToSecurityGroup($instanceId, $securityGroupId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($securityGroupId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupId should not be empty.'
            );
        }
        $body = array();
        $body['securityGroupId'] = $securityGroupId;
        $params = array();
        $params['bind'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Unbinding the instance from securitygroup.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance.
     *
     * @param string $securityGroupId (unicode)
     *          The id of the securitygroup.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function unbindInstanceFromSecurityGroup($instanceId, $securityGroupId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($securityGroupId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupId should not be empty.'
            );
        }
        $body = array();
        $body['securityGroupId'] = $securityGroupId;
        $params = array();
        $params['unbind'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * Getting the vnc url to access the instance.
     * The vnc url can be used once.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function getInstanceVnc($instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/instance/' . $instanceId . '/vnc'
        );
    }

    /**
     * PurchaseReserved the instance with fixed duration.
     * You can not purchaseReserved the instance which is resizing.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getInstance.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance.
     *
     * @param Billing $billing
     *          Billing information.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedInstance($instanceId, $billing=null, $clientToken=null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBillingWithReservation();
        }
        $body = array();
        $body['billing'] = $this->objectToArray($billing);
        $params = array();
        if (empty($clientToken)) {
            $params['purchaseReserved'] = null;
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['purchaseReserved'] = null;
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/instance/' . $instanceId
        );
    }

    /**
     * The interface will be deprecated in the future,
     * we suggest to use triad (instanceType,cpuCount,memoryCapacityInGB) to specified the instance configuration.
     * Listing all of specification for instance resource to buy.
     * See more detail on
     * https://bce.baidu.com/doc/BCC/API.html#.E5.AE.9E.E4.BE.8B.E5.A5.97.E9.A4.90.E8.A7.84.E6.A0.BC
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listInstanceSpecs($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/instance/spec'
        );
    }

    /**
     * Create a volume with the specified options.
     * You can use this method to create a new empty volume by specified options
     * or you can create a new volume from customized volume snapshot but not system disk snapshot.
     * By using the cdsSizeInGB parameter you can create a newly empty volume.
     * By using snapshotId parameter to create a volume form specific snapshot.
     *
     * @param int $cdsSizeInGB
     *          The size of volume to create in GB.
     *          By specifying the snapshotId,
     *          it will create volume from the specified snapshot and the parameter cdsSizeInGB will be ignored.
     *
     * @param Billing $billing
     *          Billing information.
     *
     * @param int $purchaseCount
     *          The optional parameter to specify how many volumes to buy, default value is 1.
     *          The maximum to create for one time is 5.
     *
     * @param string $storageType menu{'hp1', 'std1'}
     *          The storage type of volume, see more detail in
     *          https://bce.baidu.com/doc/BCC/API.html#StorageType
     *
     * @param string $zoneName
     *          The optional parameter to specify the available zone for the volume.
     *          See more detail through BccClient.listZones method
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createVolumeWithCdsSize($cdsSizeInGB, $billing=null, $purchaseCount=1, $storageType='hp1',
                                                $zoneName=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($cdsSizeInGB)) {
            throw new \InvalidArgumentException(
                'request $cdsSizeInGB should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBilling();
        }
        $body = array();
        $body['cdsSizeInGB'] = $cdsSizeInGB;
        $body['billing'] = $this->objectToArray($billing);
        if ($purchaseCount !== null) {
            $body['purchaseCount'] = $purchaseCount;
        }
        if ($storageType !== null) {
            $body['storageType'] = $storageType;
        }
        if ($zoneName !== null) {
            $body['zoneName'] = $zoneName;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume'
        );
    }

    /**
     * Create a volume with the specified options.
     * You can use this method to create a new empty volume by specified options
     * or you can create a new volume from customized volume snapshot but not system disk snapshot.
     * By using the cdsSizeInGB parameter you can create a newly empty volume.
     * By using snapshotId parameter to create a volume form specific snapshot.
     *
     * @param string $snapshotId (unicode)
     *          The id of snapshot.
     *          By specifying the snapshotId,
     *          it will create volume from the specified snapshot and the parameter cdsSizeInGB will be ignored.
     *
     * @param Billing $billing
     *          Billing information.
     *
     * @param int $purchaseCount
     *          The optional parameter to specify how many volumes to buy, default value is 1.
     *          The maximum to create for one time is 5.
     *
     * @param string $storageType menu{'hp1', 'std1'}
     *          The storage type of volume, see more detail in
     *              https://bce.baidu.com/doc/BCC/API.html#StorageType
     *
     * @param string $zoneName
     *          The optional parameter to specify the available zone for the volume.
     *          See more detail through BccClient.listZones method
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createVolumeWithSnapshotId($snapshotId, $billing=null, $purchaseCount=1, $storageType='hp1',
                                                $zoneName=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($snapshotId)) {
            throw new \InvalidArgumentException(
                'request $snapshotId should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBilling();
        }
        $body = array();
        $body['snapshotId'] = $snapshotId;
        $body['billing'] = $this->objectToArray($billing);
        if ($purchaseCount !== null) {
            $body['purchaseCount'] = $purchaseCount;
        }
        if ($storageType !== null) {
            $body['storageType'] = $storageType;
        }
        if ($zoneName !== null) {
            $body['zoneName'] = $zoneName;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume'
        );
    }

    /**
     * Listing volumes owned by the authenticated user.
     *
     * @param string $instanceId
     *          The id of instance. The optional parameter to list the volume.
     *          If it's specified,only the volumes attached to the specified instance will be listed.
     *
     * @param string $zoneName
     *          The name of available zone. The optional parameter to list volumes
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listVolumes($instanceId=null, $zoneName=null, $marker=null, $maxKeys=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($instanceId !== null) {
            $params['instanceId'] = $instanceId;
        }
        if ($zoneName !== null) {
            $params['zoneName'] = $zoneName;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/volume'
        );
    }

    /**
     * Get the detail information of specified volume.
     *
     * @param string $volumeId (unicode)
     *          The id of the volume.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function getVolume($volumeId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Attaching the specified volume to a specified instance.
     * You can attach the specified volume to a specified instance only
     * when the volume is Available and the instance is Running or Stopped,
     * otherwise, it's will get 409 errorCode.
     *
     * @param string $volumeId (unicode)
     *          The id of the volume which will be attached to specified instance.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance which will be attached with a volume.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function attachVolume($volumeId, $instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        $body = array();
        $body['instanceId'] = $instanceId;
        $params = array();
        $params['attach'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Detaching the specified volume from a specified instance.
     * You can detach the specified volume from a specified instance only
     * when the instance is Running or Stopped ,
     * otherwise, it's will get 409 errorCode.
     *
     * @param string $volumeId (unicode)
     *          The id of the volume which will be detached to specified instance.
     *
     * @param string $instanceId (unicode)
     *          The id of the instance which will be detached with a volume.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function detachVolume($volumeId, $instanceId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        $body = array();
        $body['instanceId'] = $instanceId;
        $params = array();
        $params['detach'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Releasing the specified volume owned by the user.
     * You can release the specified volume only
     * when the instance is among state of  Available/Expired/Error,
     * otherwise, it's will get 409 errorCode.
     *
     * @param string $volumeId (unicode)
     *          The id of the volume which will be released.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function releaseVolume($volumeId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Resizing the specified volume with newly size.
     * You can resize the specified volume only when the volume is Available,
     * otherwise, it's will get 409 errorCode.
     * The prepaid volume can not be downgrade.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getVolume.
     *
     * @param string $volumeId (unicode)
     *          The id of volume which you want to resize.
     *
     * @param int $newCdsSizeInGB
     *          The new volume size you want to resize in GB.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function resizeVolume($volumeId, $newCdsSizeInGB, $clientToken, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($newCdsSizeInGB)) {
            throw new \InvalidArgumentException(
                'request $newCdsSizeInGB should not be empty.'
            );
        }

        $body = array();
        $body['newCdsSizeInGB'] = $newCdsSizeInGB;
        $params = array();
        if (empty($clientToken)) {
            $params['resize'] = null;
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['resize'] = null;
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Rollback the volume with the specified volume snapshot.
     * You can rollback the specified volume only when the volume is Available,
     * otherwise, it's will get 409 errorCode.
     * The snapshot used to rollback must be created by the volume,
     * otherwise,it's will get 404 errorCode.
     * If rolling back the system volume,the instance must be Running or Stopped,
     * otherwise, it's will get 409 errorCode.After rolling back the
     * volume,all the system disk data will erase.
     *
     * @param string $volumeId (unicode)
     *          The id of volume which will be rollback.
     *
     * @param string $snapshotId (unicode)
     *          The id of snapshot which will be used to rollback the volume.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function rollbackVolume($volumeId, $snapshotId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($snapshotId)) {
            throw new \InvalidArgumentException(
                'request $snapshotId should not be empty.'
            );
        }
        $body = array();
        $body['snapshotId'] = $snapshotId;
        $params = array();
        $params['rollback'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * PurchaseReserved the instance with fixed duration.
     * You can not purchaseReserved the instance which is resizing.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getVolume.
     *
     * @param string $volumeId (unicode)
     *          The id of volume which will be renew.
     *
     * @param Billing $billing
     *          Billing information.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedVolume($volumeId, $billing=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($billing)) {
            $billing = $this->generateDefaultBillingWithReservation();
        }
        $body = array();
        $body['billing'] = $this->objectToArray($billing);
        $params = array();
        if (empty($clientToken)) {
            $params['purchaseReserved'] = null;
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['purchaseReserved'] = null;
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/volume/' . $volumeId
        );
    }

    /**
     * Creating a customized image which can be used for creating instance.
     * You can create an image from an instance with this method.
     * While creating an image from an instance, the instance must be Running or Stopped,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getImage.
     *
     * @param string $imageName (unicode)
     *          The name for the image that will be created.
     *          The name length from 1 to 65,only contains letters,digital and underline.
     *
     * @param string $instanceId (unicode)
     *          The optional parameter specify the id of the instance which will be used to create the new image.
     *          When instanceId and snapshotId are specified ,only instanceId will be used.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createImageFromInstanceId($imageName, $instanceId, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($imageName)) {
            throw new \InvalidArgumentException(
                'request $imageName should not be empty.'
            );
        }
        if (empty($instanceId)) {
            throw new \InvalidArgumentException(
                'request $instanceId should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['imageName'] = $imageName;
        $body['instanceId'] = $instanceId;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/image'
        );
    }

    /**
     * Creating a customized image which can be used for creating instance.
     * You can create an image from an snapshot with tihs method.
     * You can create the image only from system snapshot.
     * While creating an image from a system snapshot,the snapshot must be Available,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getImage.
     *
     * @param string $imageName (unicode)
     *          The name for the image that will be created.
     *          The name length from 1 to 65,only contains letters,digital and underline.
     *
     * @param string $snapshotId (unicode)
     *          The optional parameter specify the id of the snapshot which will be used to create the new image.
     *          When instanceId and snapshotId are specified ,only instanceId will be used.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createImageFromSnapshotId($imageName, $snapshotId, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($imageName)) {
            throw new \InvalidArgumentException(
                'request $imageName should not be empty.'
            );
        }
        if (empty($snapshotId)) {
            throw new \InvalidArgumentException(
                'request $snapshotId should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['imageName'] = $imageName;
        $body['snapshotId'] = $snapshotId;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/image'
        );
    }

    /**
     * Listing images owned by the authenticated user.
     *
     * @param string $imageType menu{'All', 'System', 'Custom', 'Integration'}
     *          The optional parameter to filter image to list.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#ImageType"
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listImages($imageType='All', $marker=null, $maxKeys=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $params['imageType'] = $imageType;
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/image'
        );
    }

    /**
     * Get the detail information of specified image.
     *
     * @param string $imageId (unicode)
     *          The id of image.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function getImage($imageId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($imageId)) {
            throw new \InvalidArgumentException(
                'request $imageId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/image/' . $imageId
        );
    }

    /**
     * Deleting the specified image.
     * Only the customized image can be deleted,
     * otherwise, it's will get 403 errorCode.
     *
     * @param string $imageId (unicode)
     *          The id of image.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function deleteImage($imageId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($imageId)) {
            throw new \InvalidArgumentException(
                'request $imageId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/image/' . $imageId
        );
    }

    /**
     * Creating snapshot from specified volume.
     * You can create snapshot from system volume and CDS volume.
     * While creating snapshot from system volume,the instance must be Running or Stopped,
     * otherwise, it's will get 409 errorCode.
     * While creating snapshot from CDS volume, the volume must be InUs or Available,
     * otherwise, it's will get 409 errorCode.
     * This is an asynchronous interface,
     * you can get the latest status by BccClient.getSnapshot.
     *
     * @param string $volumeId (unicode)
     *          The id which specify where the snapshot will be created from.
     *          If you want to create an snapshot from a customized volume, a id of the volume will be set.
     *          If you want to create an snapshot from a system volume, a id of the instance will be set.
     *
     * @param string $snapshotName (unicode)
     *          The name for the snapshot that will be created.
     *          The name length from 1 to 65,only contains letters,digital and underline.
     *
     * @param string $desc
     *          The optional parameter to describe the information of the new snapshot.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createSnapshot($volumeId, $snapshotName, $desc=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($volumeId)) {
            throw new \InvalidArgumentException(
                'request $volumeId should not be empty.'
            );
        }
        if (empty($snapshotName)) {
            throw new \InvalidArgumentException(
                'request $snapshotName should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['volumeId'] = $volumeId;
        $body['snapshotName'] = $snapshotName;
        if ($desc !== null) {
            $body['desc'] = $desc;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/snapshot'
        );
    }

    /**
     * List snapshots
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param string $volumeId
     *          The id of the volume.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listSnapshots($marker=null, $maxKeys=null, $volumeId=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($marker !== null || $maxKeys !== null || $volumeId !== null) {
            $params = array();
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        if ($volumeId !== null) {
            $params['volumeId'] = $volumeId;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/snapshot'
        );
    }

    /**
     * Get the detail information of specified snapshot.
     *
     * @param string $snapshotId (unicode)
     *          The id of snapshot.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function getSnapshot($snapshotId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($snapshotId)) {
            throw new \InvalidArgumentException(
                'request $snapshotId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/snapshot/' . $snapshotId
        );
    }

    /**
     * Deleting the specified snapshot.
     * Only when the snapshot is CreatedFailed or Available,the specified snapshot can be deleted.
     * otherwise, it's will get 403 errorCode.
     *
     * @param string $snapshotId (unicode)
     *          The id of snapshot.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function deleteSnapshot($snapshotId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($snapshotId)) {
            throw new \InvalidArgumentException(
                'request $snapshotId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/snapshot/' . $snapshotId
        );
    }

    /**
     * Creating a newly SecurityGroup with specified rules.
     *
     * @param string $name (unicode)
     *          The name of SecurityGroup that will be created.
     *
     * @param array $rules (array[SecurityGroupRuleModel])
     *          The array of rules which define how the SecurityGroup works.
     *
     * @param string $vpcId
     *          The optional parameter to specify the id of VPC to SecurityGroup
     *
     * @param string $desc
     *          The optional parameter to describe the SecurityGroup that will be created.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function createSecurityGroup($name, $rules, $vpcId=null, $desc=null, $clientToken=null,
                                        $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($name)) {
            throw new \InvalidArgumentException(
                'request $name should not be empty.'
            );
        }
        if (empty($rules)) {
            throw new \InvalidArgumentException(
                'request $rules should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['name'] = $name;
        $body['rules'] = $this->objectToArray($rules);
        if ($vpcId != null) {
            $body['vpcId'] = $vpcId;
        }
        if ($desc !== null) {
            $body['desc'] = $desc;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/securityGroup'
        );
    }

    /**
     * Listing SecurityGroup owned by the authenticated user.
     *
     * @param string $instanceId
     *          The id of instance. The optional parameter to list the SecurityGroup.
     *          If it's specified,only the SecurityGroup related to the specified instance will be listed
     *
     * @param string $vpcId
     *          filter by vpcId, optional parameter.
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *          Together with the marker, specifies the list result which listing should begin.
     *          If the marker is not specified, the list result will listing from the first one.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listSecurityGroups($instanceId=null, $vpcId=null, $marker=null, $maxKeys=null,
                                       $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($instanceId !== null || $marker !== null || $maxKeys !== null) {
            $params = array();
        }
        if ($instanceId !== null) {
            $params['instanceId'] = $instanceId;
        }
        if ($vpcId != null) {
            $params['vpcId'] = $vpcId;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/securityGroup'
        );
    }

    /**
     * Deleting the specified SecurityGroup.
     *
     * @param string $securityGroupId (unicode)
     *          The id of SecurityGroup that will be deleted.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function deleteSecurityGroup($securityGroupId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($securityGroupId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupId should not be empty.'
            );
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/securityGroup/' . $securityGroupId
        );
    }

    /**
     * authorize a security group rule to the specified security group
     *
     * @param string $securityGroupId (unicode)
     *          The id of SecurityGroup that will be authorized.
     *
     * @param SecurityGroupRuleModel $rule
     *          security group rule detail.
     *          Through protocol/portRange/direction/sourceIp/sourceGroupId, we can confirmed only one rule.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function authorizeSecurityGroupRule($securityGroupId, $rule, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($securityGroupId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupId should not be empty.'
            );
        }
        if (empty($rule)) {
            throw new \InvalidArgumentException(
                'request $rule should not be empty.'
            );
        }

        $params = array();
        $params['authorizeRule'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['rule'] = $this->objectToArray($rule);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/securityGroup/' . $securityGroupId
        );
    }

    /**
     * revoke a security group rule from the specified security group
     *
     * @param string $securityGroupId (unicode)
     *          The id of SecurityGroup that will be revoked.
     *
     * @param SecurityGroupRuleModel $rule
     *          security group rule detail.
     *          Through protocol/portRange/direction/sourceIp/sourceGroupId, we can confirmed only one rule.
     *
     * @param string $clientToken
     *          An ASCII string whose length is less than 64.
     *          The request will be idempotent if client token is provided.
     *          If the clientToken is not specified by the user,
     *          a random String generated by default algorithm will be used.
     *          See more detail at
     *              https://bce.baidu.com/doc/BCC/API.html#.E5.B9.82.E7.AD.89.E6.80.A7
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function revokeSecurityGroupRule($securityGroupId, $rule, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($securityGroupId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupId should not be empty.'
            );
        }
        if (empty($rule)) {
            throw new \InvalidArgumentException(
                'request $rule should not be empty.'
            );
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body = array();
        $body['rule'] = $this->objectToArray($rule);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/securityGroup/' . $securityGroupId
        );
    }

    /**
     * Get zone detail list within current region
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function listZones($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/zone'
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * The encryption implement for AES-128 algorithm for BCE password encryption.
     * Only the first 16 bytes of $secretAccessKey will be used to encrypt the $adminPass.
     *
     * See more detail on
     * <a href = "https://bce.baidu.com/doc/BCC/API.html#.7A.E6.31.D8.94.C1.A1.C2.1A.8D.92.ED.7F.60.7D.AF">
     *     BCE API doc</a>
     *
     * @param String $adminPass
     *          The content String to encrypt.
     *
     * @param String $secretAccessKey
     *          The security key to encrypt.
     *          Only the first 16 bytes of privateKey will be used to encrypt the content.
     *
     * @return string
     *          The encrypted string of the original content with AES-128 algorithm.
     */
    private function aes128WithFirst16Char($adminPass, $secretAccessKey)
    {
        $adminPass = $this->pkcs5Pad($adminPass);
        $secretAccessKey = substr($secretAccessKey, 0, 16);
        $crypted = openssl_encrypt($adminPass, 'AES-128-ECB', $secretAccessKey, OPENSSL_RAW_DATA);
        return bin2hex(substr($crypted, 0, 16));
    }

    /**
     * This is a filling algorithm, the purpose is to ensure that the content length reached 16
     *
     * @param String $adminPass
     *          The content String to filling.
     *
     * @return string
     *          ensure that the content length reached 16
     */
    private function pkcs5Pad($adminPass)
    {
        $pad = 16 - (strlen($adminPass) % 16);
        return $adminPass . str_repeat(chr($pad), $pad);
    }

    /**
     * The method to generate a default Billing which is Postpaid.
     *
     * @return Billing object with Postpaid PaymentTiming.
     */
    private function generateDefaultBilling() {
        return new Billing('Postpaid');
    }

    /**
     * The method to generate a default Billing with default Reservation which default ReservationLength is 1.
     *
     * @return Billing object with default Reservation which default ReservationLength is 1
     */
    private function generateDefaultBillingWithReservation() {
        return new Billing();
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }

    /**
     * Delete the specified security group rule via the rule id
     *
     * @param string $securityGroupRuleId
     *          The id of security group rule to be deleted
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function deleteSecurityGroupRule($securityGroupRuleId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($securityGroupRuleId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupRuleId should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            '/securityGroup' . '/rule/' . $securityGroupRuleId
        );
    }

    /**
     * Update the specified security group rule via params shown below
     *
     * @param string $securityGroupRuleId
     *          The id of security group rule to be updated
     *
     * @param string $remark
     *          The remark of the security group rule to be updated. The optional parameter
     *
     * @param string $portRange
     *          The port range of the security group rule to be updated. The optional parameter
     *
     * @param string $sourceIp
     *          The source ip of the security group rule to be updated. The optional parameter
     *
     * @param string $sourceGroupId
     *          The id of the source security group. The optional parameter
     *
     * @param string $destIp
     *          The destination ip address. The optional parameter
     *
     * @param string $destGroupId
     *          The id of the destination security group. The optional parameter
     *
     * @param string $protocol
     *          The protocol type. The optional parameter
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating BccClient instance.
     *
     * @return mixed
     */
    public function updateSecurityGroupRule($securityGroupRuleId, $remark=null, $portRange=null,
                                            $sourceIp=null, $sourceGroupId=null, $destIp=null,
                                            $destGroupId=null, $protocol=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($securityGroupRuleId)) {
            throw new \InvalidArgumentException(
                'request $securityGroupRuleId should not be empty.'
            );
        }
        $body = array();
        $body['securityGroupRuleId'] = $securityGroupRuleId;
        if ($remark != null) {
            $body['remark'] = $remark;
        }
        if ($portRange !== null) {
            $body['portRange'] = $portRange;
        }
        if ($sourceIp != null) {
            $body['sourceIp'] = $sourceIp;
        }
        if ($sourceGroupId !== null) {
            $body['sourceGroupId'] = $sourceGroupId;
        }
        if ($destIp != null) {
            $body['destIp'] = $destIp;
        }
        if ($destGroupId !== null) {
            $body['destGroupId'] = $destGroupId;
        }
        if ($protocol !== null) {
            $body['protocol'] = $protocol;
        }
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/securityGroup' . '/rule' . '/update'
        );
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bcc\model;

class EphemeralDisk
{
    var $sizeInGB;
    var $storageType;

    /**
     * This class define detail of creating ephemeral volume.
     *
     * @param int $sizeInGB
     *          The size of volume in GB.
     *
     * @param string $storageType
     *          The storage type of volume,
     *          see more detail in https://bce.baidu.com/doc/BCC/API.html#StorageType
     */
    function __construct($sizeInGB, $storageType='sata')
    {
        $this->storageType = $storageType;
        $this->sizeInGB = $sizeInGB;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bcc\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct($reservationLength, $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bcc\model;

class SecurityGroupRuleModel
{
    var $remark;
    var $direction;
    var $ethertype;
    var $portRange;
    var $protocol;
    var $sourceGroupId;
    var $sourceIp;
    var $destGroupId;
    var $destIp;
    var $securityGroupId;

    /**
     * This class define the rule of the securitygroup.
     *
     * @param string $remark
     *          The remark for the rule.
     *
     * @param string $direction
     *          The parameter to define the rule direction,available value are "ingress/egress".
     *
     * @param string $ethertype
     *          The ethernet protocol.
     *
     * @param string $portRange
     *          The port range to specify the port which the rule will work on.
     *          Available range is rang [0, 65535], the fault value is "" for all port.
     *
     * @param string $protocol
     *          The parameter specify which protocol will the rule work on, the fault value is "" for all protocol.
     *          Available protocol are tcp, udp and icmp.
     *
     * @param string $sourceGroupId
     *          The id of source securitygroup.
     *          Only works for direction = "ingress".
     *
     * @param string $sourceIp
     *          The source ip range with CIDR formats. The default value 0.0.0.0/0 (allow all ip address),
     *          other supported formats such as 10.159.6.18/12 or 10.159.6.186. Only supports IPV4.
     *          Only works for  direction = "ingress".
     *
     * @param string $destGroupId
     *          The id of destination securitygroup.
     *          Only works for  direction = "egress".
     *
     * @param string $destIp
     *          The destination ip range with CIDR formats. The default value 0.0.0.0/0 (allow all ip address),
     *          other supported formats such as 10.159.6.18/12 or 10.159.6.186. Only supports IPV4.
     *          Only works for  direction = "egress".
     *
     * @param string $securityGroupId
     *          The id of the securitygroup for the rule.
     */
    function __construct($remark=null, $direction=null, $ethertype=null, $portRange=null, $protocol=null,
                         $sourceGroupId=null, $sourceIp=null, $destGroupId=null, $destIp=null, $securityGroupId=null)
    {
        $this->remark = $remark;
        $this->direction = $direction;
        $this->ethertype = $ethertype;
        $this->portRange = $portRange;
        $this->protocol = $protocol;
        $this->sourceGroupId = $sourceGroupId;
        $this->sourceIp = $sourceIp;
        $this->destGroupId = $destGroupId;
        $this->destIp = $destIp;
        $this->securityGroupId = $securityGroupId;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bcc\model;

class Billing
{
    var $paymentTiming;
    var $reservation;

    /**
     * Billing constructor.
     * @param null $paymentTiming
     *      The pay time of the payment,
     *      see more detail in https://bce.baidu.com/doc/BCC/API.html#Billing
     * @param int $reservationLength
     *      The duration to buy in specified time unit,
     *      available values are [1,2,3,4,5,6,7,8,9,12,24,36] now.
     * @param string $reservationTimeUnit
     *      The time unit to specify the duration ,only "Month" can be used now.
     */
    function __construct($paymentTiming=null, $reservationLength=1, $reservationTimeUnit='Month')
    {
        if ($paymentTiming !== null) {
            $this->paymentTiming = $paymentTiming;
        }
        $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bos;

class StorageClass 
{
    const STANDARD = 'STANDARD';
    const STANDARD_IA = 'STANDARD_IA';
    const COLD = 'COLD';
    const ARCHIVE = 'ARCHIVE';

}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bos;

class CannedAcl
{
    const ACL_PRIVATE = 'private';
    const ACL_PUBLIC_READ = 'public-read';
    const ACL_PUBLIC_READ_WRITE = 'public-read-write';
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bos;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\Auth\SignOptions;
use BaiduBce\Bce;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Exception\BceServiceException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Util\HashUtils;
use BaiduBce\Util\HttpUtils;
use BaiduBce\Util\StringUtils;


class BosClient extends BceBaseClient
{
    const MIN_PART_SIZE = 5242880;                // 5M
    const MAX_PUT_OBJECT_LENGTH = 5368709120;     // 5G
    const MAX_USER_METADATA_SIZE = 2048;          // 2 * 1024
    const MIN_PART_NUMBER = 1;
    const MAX_PART_NUMBER = 10000;
    const BOS_URL_PREFIX = "/";

    /**
     * @var \BaiduBce\Auth\SignerInterface
     */
    private $signer;
    private $httpClient;

    /**
     * The BosClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'bos');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Get an authorization url with expire time
     *
     * @param string $bucketName The bucket name.
     * @param string $object_name The object path.
     * @param number $timestamp
     * @param number $expiration_in_seconds The valid time in seconds.
     * @param mixed $options The extra Http request headers or params.
     *
     * @return string
     */
    public function generatePreSignedUrl($bucketName, $key, $options = array())
    {
        list(
            $config,
            $headers,
            $params,
            $signOptions
        ) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::HEADERS,
            BosOptions::PARAMS,
            BosOptions::SIGN_OPTIONS
        );
        if(is_null($config)) {
            $config = $this->config;
        } else {
            $config = array_merge($this->config, $config);
        }
        if(is_null($params)) {
            $params = array();
        }
        if(is_null($headers)) {
            $headers = array();
        }

        $path = $this->getPath($bucketName, $key);

        list($hostUrl, $hostHeader) =
            HttpUtils::parseEndpointFromConfig($config);
        $headers[HttpHeaders::HOST] = $hostHeader;

        $auth = $this->signer->sign(
            $config[BceClientConfigOptions::CREDENTIALS],
            HttpMethod::GET,
            $path,
            $headers,
            $params,
            $signOptions
        );
        $params['authorization'] = $auth;

        $url = $hostUrl . HttpUtils::urlEncodeExceptSlash($path);
        $queryString = HttpUtils::getCanonicalQueryString($params, false);
        if ($queryString !== '') {
            $url .= "?$queryString";
        }
        return $url;
    }

    /**
     * List buckets of user.
     *
     * @param array $options Supported options:
     *      <ul>
     *          <li>config: The optional bce configuration, which will overwrite
     *          the default client configuration that was passed in constructor.
     *          </li>
     *      </ul>
     * @return object the server response.
     */
    public function listBuckets($options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config
            )
        );
    }

    /**
     * Create a new bucket.
     *
     * @param string $bucketName The bucket name.
     * @param array $options Supported options:
     *      <ul>
     *          <li>config: The optional bce configuration, which will overwrite
     *          the default client configuration that was passed in constructor.
     *          </li>
     *      </ul>
     * @return \stdClass
     */
    public function createBucket($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName
            )
        );
    }

    /**
     * Get Object Information of bucket.
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @property number $maxKeys The default value is 1000.
     * @property string $prefix The default value is null.
     * @property string $marker The default value is null.
     * @property string $delimiter The default value is null.
     * @property mixed $config The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function listObjects($bucketName, $options = array())
    {
        list($config, $maxKeys, $prefix, $marker, $delimiter) =
            $this->parseOptions(
                $options,
                BosOptions::CONFIG,
                BosOptions::MAX_KEYS,
                BosOptions::PREFIX,
                BosOptions::MARKER,
                BosOptions::DELIMITER
            );
        $params = array();
        if ($maxKeys !== null) {
            if (is_numeric($maxKeys)) {
                $maxKeys = number_format($maxKeys);
                $maxKeys = str_replace(',','',$maxKeys);
            }
            $params[BosOptions::MAX_KEYS] = $maxKeys;
        }
        if ($prefix !== null) {
            $params[BosOptions::PREFIX] = $prefix;
        }
        if ($marker !== null) {
            $params[BosOptions::MARKER] = $marker;
        }
        if ($delimiter !== null) {
            $params[BosOptions::DELIMITER] = $delimiter;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => $params
            )
        );
    }

    /**
     * Check whether there is some user access to this bucket.
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return boolean true means the bucket does exists.
     */
    public function doesBucketExist($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        try {
            $this->sendRequest(
                HttpMethod::HEAD,
                array(
                    BosOptions::CONFIG => $config,
                    'bucket_name' => $bucketName
                )
            );
            return true;
        } catch (BceServiceException $e) {
            if ($e->getStatusCode() === 403) {
                return true;
            }
            if ($e->getStatusCode() === 404) {
                return false;
            }
            throw $e;
        }
    }

    /**
     * Delete a Bucket
     * Must delete all the bbjects in this bucket before call this api
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function deleteBucket($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName
            )
        );
    }

    /**
     * Set Access Control Level of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $cannedAcl The grant list.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function setBucketCannedAcl(
        $bucketName,
        $cannedAcl,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'headers' => array(
                    HttpHeaders::BCE_ACL => $cannedAcl,
                ),
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Set Access Control Level of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $acl The grant list.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function setBucketAcl($bucketName, $acl, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array('accessControlList' => $acl)),
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Set Replication rule of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $replicationRule json format.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketReplication($bucketName, $replicationRule, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode($replicationRule),
                'params' => array(
                    BosOptions::REPLICATION => '',
                )
            )
        );
    }

    /**
     * Get Replication rule of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketReplication($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::REPLICATION => '',
                )
            )
        );
    }

    /**
     * Get Replication progress of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function getBucketReplicationProgress($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::REPLICATION_PROGRESS => '',
                )
            )
        );
    }

    /**
     * Delete bucket Replication
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketReplication($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::REPLICATION => '',
                )
            )
        );
    }

    /**
     * List bucket Replication
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function listBucketReplication($bucketName, $options)
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::REPLICATION => '',

                )
            )
        );
    }
    /**
     * Get Access Control Level of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getBucketAcl($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }



    /**
     * Get Access Control Level of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getBucketVersioning($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    "versioning" => '',
                )
            )
        );
    }



    /**
     * Get Region of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getBucketLocation($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        $response = $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::LOCATION => '',
                ),
            )
        );
        return $response->locationConstraint;
    }

    /**
     * Set Lifecycle of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $lifecycleRule json format.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketLifecycle($bucketName, $lifecycleRule, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array("rule" => $lifecycleRule)),
                'params' => array(
                    BosOptions::LIFECYCLE => '',
                )
            )
        );
    }

    /**
     * Get Lifecycle rule of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketLifecycle($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::LIFECYCLE => '',
                )
            )
        );
    }

    /**
     * Delete bucket Lifecycle
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketLifecycle($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::LIFECYCLE => '',
                )
            )
        );
    }

    /**
     * Set Logging of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $logging json format.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketLogging(
        $bucketName,
        $logging,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode($logging),
                'params' => array(
                    BosOptions::LOGGING => '',
                )
            )
        );
    }

    /**
     * Get Logging of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketLogging($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::LOGGING => '',
                )
            )
        );
    }

    /**
     * Delete bucket Logging
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketLogging($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::LOGGING => '',
                )
            )
        );
    }

    /**
     * Set Trash of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $trashDir json format.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketTrash(
        $bucketName,
        $trashDir = ".trash",
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array("trashDir" => $trashDir)),
                'params' => array(
                    BosOptions::TRASH => '',
                )
            )
        );
    }

    /**
     * Get Trash of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketTrash($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::TRASH => '',
                )
            )
        );
    }

    /**
     * Delete bucket Trash
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketTrash($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::TRASH => '',
                )
            )
        );
    }

    /**
     * Set StaticWebsite of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $trashDir json format.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketStaticWebsite(
        $bucketName,
        $staticWebsite,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode($staticWebsite),
                'params' => array(
                    BosOptions::WEBSITE => '',
                )
            )
        );
    }

    /**
     * Get StaticWebsite of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketStaticWebsite($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::WEBSITE => '',
                )
            )
        );
    }

    /**
     * Delete bucket StaticWebsite
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketStaticWebsite($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::WEBSITE => '',
                )
            )
        );
    }

    /**
     * Set Encryption of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $encryptionAlgorithm string, only support 'AES256'.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketEncryption($bucketName, $encryptionAlgorithm, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array("encryptionAlgorithm" => $encryptionAlgorithm)),
                'params' => array(
                    BosOptions::ENCRYPTION => '',
                )
            )
        );
    }

    /**
     * Get Encryption of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketEncryption($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::ENCRYPTION => '',
                )
            )
        );
    }

    /**
     * Delete bucket Encryption
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketEncryption($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::ENCRYPTION => '',
                )
            )
        );
    }

    /**
     * Set Cors of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $cors.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketCors($bucketName, $cors, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array("corsConfiguration" => $cors)),
                'params' => array(
                    BosOptions::CORS => '',
                )
            )
        );
    }

    /**
     * Get Cors of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketCors($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::CORS => '',
                )
            )
        );
    }

    /**
     * Delete bucket Cors
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketCors($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::CORS => '',
                )
            )
        );
    }

    /**
     * Set CopyrightProtection of bucket
     *
     * @param string $bucketName The bucket name.
     * @param string $copyrightProtection.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function putBucketCopyrightProtection($bucketName, $copyrightProtection, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array("resource" => $copyrightProtection)),
                'params' => array(
                    BosOptions::COPYRIGHTPROTECTION => '',
                )
            )
        );
    }

    /**
     * Get CopyrightProtection of bucket
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function getBucketCopyrightProtection($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::COPYRIGHTPROTECTION => '',
                )
            )
        );
    }

    /**
     * Delete bucket CopyrightProtection
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */


    public function deleteBucketCopyrightProtection($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::COPYRIGHTPROTECTION => '',
                )
            )
        );
    }

    /**
     * Put symlink of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $symlink x-bce-symlink-target.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function putObjectSymlink(
        $bucketName,
        $key,
        $symlink,
        $options = array()
    ) {
        if (empty($key)) {
            throw new \InvalidArgumentException('$key should not be empty or null.');
        }
        if (empty($symlink) || strcmp($key, $symlink) == 0) {
            throw new \InvalidArgumentException('$symlink should not be empty or null or equals to $key.');
        }

        $headers = array();
        $headers[HttpHeaders::BCE_SYMLINK_TARGET] = $symlink;
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config) = $this->parseOptions($options,
            BosOptions::CONFIG,
            BosOptions::BCE_SYMLINK_TARGET,
            BosOptions::BCE_FORBID_OVERWRITE,
            BosOptions::STORAGE_CLASS,
            BosOptions::USER_METADATA
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'headers' => $headers,
                'params' => array(
                    BosOptions::SYMLINK => '',
                )
            )
        );
    }

    /**
     * Get symlink of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getObjectSymLink($bucketName, $key, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'params' => array(
                    BosOptions::SYMLINK => '',
                )
            )
        );
    }

    /**
     * Set Access Control Level of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param array $cannedAcl x-bce-acl/x-bce-grant-permission.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function setObjectCannedAcl(
        $bucketName,
        $key,
        $cannedAcl = array(),
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'headers' => $cannedAcl,
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Set Access Control Level of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $acl The grant list.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function setObjectAcl($bucketName, $key, $acl, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'body' => json_encode(array('accessControlList' => $acl)),
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Delete Access Control Level of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $acl The grant list.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function deleteObjectAcl($bucketName, $key, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Get Access Control Level of object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getObjectAcl($bucketName, $key, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'params' => array(
                    BosOptions::ACL => '',
                )
            )
        );
    }

    /**
     * Create object and put content of string to the object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $data The object content.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function putObjectFromString(
        $bucketName,
        $key,
        $data,
        $options = array()
    ) {
        return $this->putObject(
            $bucketName,
            $key,
            $data,
            strlen($data),
            base64_encode(md5($data, true)),
            $options
        );
    }

    /**
     * Put object and copy content of file to the object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $filename The absolute file path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function putObjectFromFile(
        $bucketName,
        $key,
        $filename,
        $options = array()
    ) {
        if (!isset($options[BosOptions::CONTENT_TYPE])) {
            $options[BosOptions::CONTENT_TYPE] = MimeTypes::guessMimeType(
                $filename
            );
        }

        list($contentLength, $contentMd5) = $this->parseOptionsIgnoreExtra(
            $options,
            BosOptions::CONTENT_LENGTH,
            BosOptions::CONTENT_MD5
        );

        if ($contentLength === null) {
            $contentLength = filesize($filename);
        } else {
            if (!is_int($contentLength) && !is_long($contentLength)) {
                throw new \InvalidArgumentException(
                    '$contentLength should be int or long.'
                );
            }
            unset($options[BosOptions::CONTENT_LENGTH]);
        }

        $fp = fopen($filename, 'rb');
        if ($contentMd5 === null) {
            $contentMd5 = base64_encode(HashUtils::md5FromStream($fp, 0, $contentLength));
        } else {
            unset($options[BosOptions::CONTENT_MD5]);
        }

        try {
            $response = $this->putObject(
                $bucketName,
                $key,
                $fp,
                $contentLength,
                $contentMd5,
                $options);
            //streams are close in the destructor of stream object in guzzle
            if (is_resource($fp)) {
                fclose($fp);
            }
            return $response;
        } catch (\Exception $e) {
            if (is_resource($fp)) {
                fclose($fp);
            }
            throw $e;
        }
    }

    /**
     * Upload a object to one bucket
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string|resource $data The object content, which can be a string or a resource.
     * @param int $contentLength
     * @param string $contentMd5
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function putObject(
        $bucketName,
        $key,
        $data,
        $contentLength,
        $contentMd5,
        $options = array()
    ) {
        if (empty($key)) {
            throw new \InvalidArgumentException('$key should not be empty or null.');
        }
        if (!is_int($contentLength) && !is_long($contentLength)) {
            throw new \InvalidArgumentException(
                '$contentLength should be int or long.'
            );
        }
        if ($contentLength < 0) {
            throw new \InvalidArgumentException(
                '$contentLength should not be negative.'
            );
        }
        if (empty($contentMd5)) {
            throw new \InvalidArgumentException(
                '$contentMd5 should not be empty or null.'
            );
        }
        $this->checkData($data);

        $headers = array();
        $headers[HttpHeaders::CONTENT_MD5] = $contentMd5;
        $headers[HttpHeaders::CONTENT_LENGTH] = $contentLength;
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'body' => $data,
                'headers' => $headers,
            )
        );
    }

    /**
     * Fetch a object to one bucket
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $fetchSource
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function fetchObject(
        $bucketName,
        $key,
        $fetchSource,
        $options = array()
    ) {
        if (empty($key)) {
            throw new \InvalidArgumentException('$key should not be empty or null.');
        }

        if (empty($fetchSource)) {
            throw new \InvalidArgumentException('$fetchSource should not be empty or null.');
        }
        $headers = array();
        $headers[HttpHeaders::BCE_FETCH_SOURCE] = $fetchSource;
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config, $storageClass, $fetchMode) = $this->parseOptions($options,
            BosOptions::CONFIG,
            BosOptions::STORAGE_CLASS,
            BosOptions::BCE_FETCH_MODE);
        if ($fetchMode !== null) {
            $headers[HttpHeaders::BCE_FETCH_MODE] = $fetchMode;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'headers' => $headers,
                'params' => array(
                    BosOptions::FETCH => '',
                )
            )
        );
    }

    /**
     * create a append object or append the string to a existing object
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string|resource $data The object content, which can be a string or a resource.
     * @param int offset the current offset of append object
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return the new offset of append object
     */

    public function appendObjectFromString(
        $bucketName,
        $key,
        $data,
        $offset,
        $options = array()
    ) {
        if (empty($key)) {
            throw new \InvalidArgumentException('$key should not be empty or null.');
        }
        if (!is_int($offset) && !is_long($offset)) {
            throw new \InvalidArgumentException(
                '$offset should be int or long.'
            );
        }
        $contentLength = strlen($data);
        $contentMd5 = base64_encode(md5($data, true));

        $this->checkData($data);

        $headers = array();
        $headers[HttpHeaders::CONTENT_MD5] = $contentMd5;
        $headers[HttpHeaders::CONTENT_LENGTH] = $contentLength;
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        $param = array();
        if ($offset !== 0) {
            $param['offset'] = $offset;
        }
        $param['append'] = '';
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'body' => $data,
                'headers' => $headers,
                'params' => $param,
            )
        );
    }
     /**
     * create a append object or append the file to a existing object
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $filename.
     * @param int offset the current offset of append object
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */

    public function appendObjectFromFile(
        $bucketName,
        $key,
        $filename,
        $offset,
        $options = array()
    ) {

        $contentLength = filesize($filename);

        $fp = fopen($filename, 'rb');
        $contentMd5 = base64_encode(HashUtils::md5FromStream($fp, 0, $contentLength));

        $headers = array();
        $headers[HttpHeaders::CONTENT_MD5] = $contentMd5;
        $headers[HttpHeaders::CONTENT_LENGTH] = $contentLength;
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        $param = array();
        if ($offset !== 0) {
            $param['offset'] = $offset;
        }
        $param['append'] = '';

        try {
            $this->checkData($fp);
            $response = $this->sendRequest(
                HttpMethod::POST,
                array(
                    BosOptions::CONFIG => $config,
                    'bucket_name' => $bucketName,
                    'key' => $key,
                    'body' => $fp,
                    'headers' => $headers,
                    'params' => $param,
                )
            );
            if (is_resource($fp)) {
                fclose($fp);
            }
            return $response;

        } catch (\Exception $e) {
            if (is_resource($fp)) {
                fclose($fp);
            }
            throw $e;
        }
    }

    /**
     * Get the object from a bucket.
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param resource $outputStream
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getObject(
        $bucketName,
        $key,
        $outputStream,
        $options = array()
    ) {
        list($config, $range) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::RANGE
        );
        $headers = array();
        if ($range !== null) {
            switch(gettype($range)) {
                case 'array':
                    if (!isset($range[0]) || !(is_int($range[0]) || is_long($range[0]))) {
                        throw new \InvalidArgumentException(
                            'range[0] is not defined.'
                        );
                    }
                    if (!isset($range[1]) || !(is_int($range[1]) || is_long($range[1]))) {
                        throw new \InvalidArgumentException(
                            'range[1] is not defined.'
                        );
                    }
                    $range = sprintf('%d-%d', $range[0], $range[1]);
                    break;
                case 'string':
                    break;
                default:
                    throw new \InvalidArgumentException(
                        'Option "range" should be either an array of two '
                        . 'integers or a string'
                    );
            }
            $headers[HttpHeaders::RANGE] = sprintf('bytes=%s', $range);
        }

        $response = $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'headers' => $headers,
                'outputStream' => $outputStream,
                'parseUserMetadata' => true
            )
        );
        return $response;
    }

    /**
     * Get the object cotent as string
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $range If specified, only get the range part.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     * @return mixed
     */
    public function getObjectAsString(
        $bucketName,
        $key,
        $options = array()
    ) {
        $outputStream = fopen('php://memory', 'r+');
        try {
            $this->getObject($bucketName, $key, $outputStream, $options);
            rewind($outputStream);
            $result = stream_get_contents($outputStream);
            if (is_resource($outputStream)) {
                fclose($outputStream);
            }
            return $result;
        } catch (\Exception $e) {
            if (is_resource($outputStream)) {
                fclose($outputStream);
            }
            throw $e;
        }
    }

    /**
     * Get Content of Object and Put Content to File
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $filename The destination file name.
     * @param string $range The HTTP 'Range' header.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function getObjectToFile(
        $bucketName,
        $key,
        $filename,
        $options = array()
    )
    {
        $outputStream = fopen($filename, 'w+');
        try {
            $response = $this->getObject(
                $bucketName,
                $key,
                $outputStream,
                $options
            );
            if(is_resource($outputStream)) {
                fclose($outputStream);
            }
            return $response;
        } catch (\Exception $e) {
            if(is_resource($outputStream)) {
                fclose($outputStream);
            }
            throw $e;
        }
    }

    /**
     * Delete Object
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function deleteObject($bucketName, $key, $options = array())
    {
        list($config) = $this->parseOptions(
            $options,
            BosOptions::CONFIG
        );

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
            )
        );
    }
    /**
     * Delete objects in bulk.
     *
     * @param $bucketName string The bucket name.
     * @param $objects string The list of objects to be deleted.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function deleteMultipleObjects($bucketName, $objects, $options=array())
    {
        list($config) = $this->parseOptions( $options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array(
                    'objects' => $objects
                )),
                'params' => array(
                    BosOptions::DELETE => '',
                )
            )
        );
    }
    /**
     * Get Object meta information
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function getObjectMetadata($bucketName, $key, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        $response = $this->sendRequest(
            HttpMethod::HEAD,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'parseUserMetadata' => true
            )
        );

        return $response->metadata;
    }

    /**
     * Copy one object to another.
     *
     * @param string $sourceBucketName The source bucket name.
     * @param string $sourceKey The source object path.
     * @param string $targetBucketName The target bucket name.
     * @param string $targetKey The target object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function copyObject(
        $sourceBucketName,
        $sourceKey,
        $targetBucketName,
        $targetKey,
        $options = array()
    ) {
        if (empty($sourceBucketName)) {
            throw new \InvalidArgumentException(
                '$sourceBucketName should not be empty or null.'
            );
        }
        if (empty($sourceKey)) {
            throw new \InvalidArgumentException(
                '$sourceKey should not be empty or null.'
            );
        }
        if (!isset($this->config[BceClientConfigOptions::CUSTOM]) && empty($targetBucketName)) {
            throw new \InvalidArgumentException(
                '$targetBucketName should not be empty or null.'
            );
        }
        if (empty($targetKey)) {
            throw new \InvalidArgumentException(
                '$targetKey should not be empty or null.'
            );
        }

        list($config, $userMetadata, $etag, $storageClass, $keepTime, $contentType) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::USER_METADATA,
            BosOptions::ETAG,
            BosOptions::STORAGE_CLASS,
            BosOptions::BCE_KEEP_TIME,
            BosOptions::CONTENT_TYPE
        );

        $headers = array();

        $headers[HttpHeaders::BCE_COPY_SOURCE] =
            HttpUtils::urlEncodeExceptSlash(
                sprintf("/%s/%s", $sourceBucketName, $sourceKey)
            );
        if ($etag !== null) {
            $etag = trim($etag, '"');
            $headers[HttpHeaders::BCE_COPY_SOURCE_IF_MATCH] = '"' . $etag . '"';
        }
        if ($userMetadata === null) {
            $headers[HttpHeaders::BCE_COPY_METADATA_DIRECTIVE] = 'copy';
        } else {
            $headers[HttpHeaders::BCE_COPY_METADATA_DIRECTIVE] = 'replace';
            $this->populateRequestHeadersWithUserMetadata(
                $headers,
                $userMetadata
            );
        }
        if ($storageClass !== null) {
            $headers[HttpHeaders::BCE_STORAGE_CLASS] = $storageClass;
        }
        if ($keepTime !== null) {
            $headers[HttpHeaders::BCE_KEEP_TIME] = $headers[HttpHeaders::BCE_COPY_SOURCE];
        }
        if ($contentType !== null) {
           $headers[HttpHeaders::CONTENT_TYPE] = $contentType;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $targetBucketName,
                'key' => $targetKey,
                'headers' => $headers,
            )
        );
    }

    /**
     * Initialize multi_upload_file.
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function initiateMultipartUpload(
        $bucketName,
        $key,
        $options = array()
    ) {
        $headers = array();
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config,
            $copySourceBucket,
            $copySourceObject) = $this->parseOptions(
            $options, 
            BosOptions::CONFIG,
            BosOptions::COPY_SOURCE_BUCKET,
            BosOptions::COPY_SOURCE_OBJECT);

        if ($copySourceBucket != null && $copySourceObject != null) {
            $headers[HttpHeaders::BCE_KEEP_TIME] =
                HttpUtils::urlEncodeExceptSlash(
                    sprintf("/%s/%s", $copySourceBucket, $copySourceObject));
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'headers' => $headers,
                'params' => array('uploads' => ''),
            )
        );
    }

    /**
     * Abort upload a part which is being uploading.
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $uploadId The uploadId returned by initiateMultipartUpload.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function abortMultipartUpload(
        $bucketName,
        $key,
        $uploadId,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'params' => array('uploadId' => $uploadId),
            )
        );
    }
    /**
     * upload a part by copy from another object from bos
     *
     * @param string $sourceBucketName  
     * @param string $sourceKey source object
     * @param string $targetBucketName
     * @param string $targetKey target object
     * @param string $uploadId The uploadId returned by initiateMultipartUpload.
     * @param int $partNumber The part index, 1-based.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function uploadPartCopy(
        $sourceBucketName,
        $sourceKey,
        $targetBucketName,
        $targetKey,
        $uploadId,
        $partNumber,
        $options = array()
    ) {
    
        if (empty($sourceBucketName)) {
            throw new \InvalidArgumentException(
                '$sourceBucketName should not be empty or null.'
            );
        }
        if (empty($sourceKey)) {
            throw new \InvalidArgumentException(
                '$sourceKey should not be empty or null.'
            );
        }
        if (empty($targetBucketName)) {
            throw new \InvalidArgumentException(
                '$targetBucketName should not be empty or null.'
            );
        }
        if (empty($targetKey)) {
            throw new \InvalidArgumentException(
                '$targetKey should not be empty or null.'
            );
        }
        if ($partNumber < BosClient::MIN_PART_NUMBER
            || $partNumber > BosClient::MAX_PART_NUMBER
        ) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Invalid $partNumber %d. The valid range is from %d to %d.',
                    $partNumber,
                    BosClient::MIN_PART_NUMBER,
                    BosClient::MAX_PART_NUMBER
                )
            );
        }

        list($config,$etag,$unEtag,$unModified,$modified,$range) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::OBJECT_COPY_SOURCE_IF_MATCH_TAG,
            BosOptions::OBJECT_COPY_SOURCE_IF_NONE_MATCH_TAG,
            BosOptions::OBJECT_COPY_SOURCE_IF_UNMODIFIED_SINCE,
            BosOptions::OBJECT_COPY_SOURCE_IF_MODIFIED_SINCE,
            BosOptions::RANGE
        );

        $headers = array();

        $headers[HttpHeaders::BCE_COPY_SOURCE] =
            HttpUtils::urlEncodeExceptSlash(
                sprintf("/%s/%s", $sourceBucketName, $sourceKey)
            );
        if ($etag != null) {
            $etag = trim($etag, '"');
            $headers[HttpHeaders::BCE_COPY_SOURCE_IF_MATCH] = '"' . $etag . '"';
        }
        if ($unEtag != null) {
            $unEtag = trim($unEtag,'"');
            $headers[HttpHeaders::BCE_COPY_SOURCE_IF_NONE_MATCH] = '"' . $unEtag . '"';
        }
        if ($unModified != null) {
            $headers[HttpHeaders::BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE]
                = $unModified;
        }
        if ($modified != null) {
            $headers[HttpHeaders::BCE_COPY_SOURCE_IF_MODIFIED_SINCE]
                = $modified;
        }
        if ($range !== null) {
            switch(gettype($range)) {
                case 'array':
                    if (!isset($range[0]) || !(is_int($range[0]) || is_long($range[0]))) {
                        throw new \InvalidArgumentException(
                            'range[0] is not defined.'
                        );
                    }
                    if (!isset($range[1]) || !(is_int($range[1]) || is_long($range[1]))) {
                        throw new \InvalidArgumentException(
                            'range[1] is not defined.'
                        );
                    }
                    $range = sprintf('%d-%d', $range[0], $range[1]);
                    break;
                case 'string':
                    break;
                default:
                    throw new \InvalidArgumentException(
                        'Option "range" should be either an array of two '
                        . 'integers or a string'
                    );
            }
            $headers[HttpHeaders::BCE_COPY_RANGE] = sprintf('bytes=%s', $range);
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $targetBucketName,
                'key' => $targetKey,
                'params' => array(
                    'partNumber' => $partNumber,
                    'uploadId' => $uploadId,
                ),
                'headers' => $headers,
            )
        );
    }

    /**
     * Upload a part from a file handle
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $uploadId The uploadId returned by initiateMultipartUpload.
     * @param int $partNumber The part index, 1-based.
     * @param int $contentLength The uploaded part size.
     * @param string $contentMd5 The part md5 check sum.
     * @param string $data The file pointer.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function uploadPart(
        $bucketName,
        $key,
        $uploadId,
        $partNumber,
        $contentLength,
        $contentMd5,
        $data,
        $options = array()
    ) {
        if (!isset($this->config[BceClientConfigOptions::CUSTOM]) && empty($bucketName)) {
            throw new \InvalidArgumentException(
                '$bucketName should not be empty or null.'
            );
        }
        if (empty($key)) {
            throw new \InvalidArgumentException(
                '$key should not be empty or null.'
            );
        }
        if (!is_int($contentLength) && !is_long($contentLength)) {
            throw new \InvalidArgumentException(
                '$contentLength should be int or long.'
            );
        }
        if ($partNumber < BosClient::MIN_PART_NUMBER
            || $partNumber > BosClient::MAX_PART_NUMBER
        ) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Invalid $partNumber %d. The valid range is from %d to %d.',
                    $partNumber,
                    BosClient::MIN_PART_NUMBER,
                    BosClient::MAX_PART_NUMBER
                )
            );
        }

        if ($contentMd5 === null) {
            throw new \InvalidArgumentException(
                '$contentMd5 should not be null.'
            );
        }

        $this->checkData($data);

        list($config, $contentCRC32, $contentSHA256) = $this->parseOptions($options, 
            BosOptions::CONFIG, 
            BosOptions::CONTENT_CRC32,
            BosOptions::CONTENT_SHA256
        );

        $headers = array();
        $headers[HttpHeaders::CONTENT_MD5] = $contentMd5;
        $headers[HttpHeaders::CONTENT_LENGTH] = $contentLength;
        $headers[HttpHeaders::CONTENT_TYPE] = HttpContentTypes::OCTET_STREAM;
        if ($contentCRC32 !== null) {
            $headers[HttpHeaders::BCE_CONTENT_CRC32] = $contentCRC32;
        }
        if ($contentSHA256 !== null) {
            $headers[HttpHeaders::BCE_CONTENT_SHA256] = $contentSHA256;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'body' => $data,
                'params' => array(
                    'partNumber' => $partNumber,
                    'uploadId' => $uploadId
                ),
                'headers' => $headers,
            )
        );
    }

    /**
     * Upload a part from starting with offset.
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $uploadId The uploadId returned by initiateMultipartUpload.
     * @param number $partNumber The part index, 1-based.
     * @param number $length The uploaded part size.
     * @param string $filename The file name.
     * @param number $offset The file offset.
     * @param number $contentMd5 The part md5 check sum.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function uploadPartFromFile(
        $bucketName,
        $key,
        $uploadId,
        $partNumber,
        $filename,
        $offset = 0,
        $length = -1,
        $options = array()
    ) {
        if (!is_int($offset) && !is_long($offset)) {
            throw new \InvalidArgumentException(
                '$offset should be int or long.'
            );
        }
        if (!is_int($length) && !is_long($length)) {
            throw new \InvalidArgumentException(
                '$length should be int or long.'
            );
        }

        $fp = fopen($filename, 'rb');
        try {
            if ($length < 0) {
                fseek($fp, 0, SEEK_END);
                $length = ftell($fp) - $offset;
            }
            $contentMd5 = base64_encode(HashUtils::md5FromStream($fp, $offset, $length));
            fseek($fp, $offset, SEEK_SET);
            $response = $this->uploadPart(
                $bucketName,
                $key,
                $uploadId,
                $partNumber,
                $length,
                $contentMd5,
                $fp,
                $options
            );
            //guzzle will close fp
            if (is_resource($fp)) {
                fclose($fp);
            }
            return $response;
        } catch (\Exception $e) {
            if(is_resource($fp)) {
                fclose($fp);
            }
            throw $e;
        }
    }

    /**
     * List parts that have been upload success.
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $uploadId The uploadId returned by initiateMultipartUpload.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function listParts($bucketName, $key, $uploadId, $options = array())
    {
        if (!isset($this->config[BceClientConfigOptions::CUSTOM]) && empty($bucketName)) {
            throw new \InvalidArgumentException(
                '$bucketName should not be empty or null.'
            );
        }
        if (empty($key)) {
            throw new \InvalidArgumentException(
                '$key should not be empty or null.'
            );
        }
        if (empty($uploadId)) {
            throw new \InvalidArgumentException(
                '$uploadId should not be empty or null.'
            );
        }

        list($config, $maxParts, $partNumberMarker) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::LIMIT,
            BosOptions::MARKER
        );
        $params = array();
        $params['uploadId'] = $uploadId;
        if ($maxParts !== null) {
            if (is_numeric($maxParts)) {
                $maxParts = number_format($maxParts);
                $maxParts = str_replace(',','',$maxParts);
            }
            $params['maxParts'] = $maxParts;
        }
        if ($partNumberMarker !== null) {
            $params['partNumberMarker'] = $partNumberMarker;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'params' => $params,
            )
        );
    }

    /**
     * After finish all the task, complete multi_upload_file.
     * bucket, key, upload_id, part_list, options=None
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $uploadId The upload id.
     * @param array $partList (partnumber and etag) list
     * @param array $options
     *
     * @return mixed
     */
    public function completeMultipartUpload(
        $bucketName,
        $key,
        $uploadId,
        array $partList,
        $options = array()
    ) {
        if (!isset($this->config[BceClientConfigOptions::CUSTOM]) && empty($bucketName)) {
            throw new \InvalidArgumentException(
                '$bucketName should not be empty or null.'
            );
        }
        if (empty($key)) {
            throw new \InvalidArgumentException(
                '$key should not be empty or null.'
            );
        }
        if (empty($uploadId)) {
            throw new \InvalidArgumentException(
                '$uploadId should not be empty or null.'
            );
        }

        $headers = array();
        $this->populateRequestHeadersWithOptions($headers, $options);
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'key' => $key,
                'body' => json_encode(array('parts' => $partList)),
                'headers' => $headers,
                'params' => array('uploadId' => $uploadId),
            )
        );
    }

    /**
     * List Multipart upload task which haven't been ended.
     * call initiateMultipartUpload but not call completeMultipartUpload or abortMultipartUpload
     *
     * @param string $bucketName The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function listMultipartUploads($bucketName, $options = array())
    {
        list(
            $config,
            $keyMarker,
            $maxUploads,
            $delimiter,
            $prefix
        ) = $this->parseOptions(
            $options,
            BosOptions::CONFIG,
            BosOptions::MARKER,
            BosOptions::LIMIT,
            BosOptions::DELIMITER,
            BosOptions::PREFIX
        );
        $params = array();
        $params['uploads'] = '';
        if ($keyMarker !== null) {
            $params['keyMarker'] = $keyMarker;
        }
        if ($maxUploads !== null) {
            if (is_numeric($maxUploads)) {
                $maxUploads = number_format($maxUploads);
                $maxUploads = str_replace(',','',$maxUploads);
            }
            $params['maxUploads'] = $maxUploads;
        }
        if ($delimiter !== null) {
            $params['delimiter'] = $delimiter;
        }
        if ($prefix !== null) {
            $params['prefix'] = $prefix;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => $params,
            )
        );
    }

    /**
     * Put super file to the object using the multipart upload interface
     *
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     * @param string $filename The absolute file path.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function putSuperObjectFromFile(
        $bucketName,
        $key,
        $filename,
        $options = array()
    ) {
        $partSize = self::MIN_PART_SIZE; // default part size
        if (isset($options[BosOptions::PART_SIZE])) {
            $partSize = $options[BosOptions::PART_SIZE];
            if ($partSize < 1024 * 1024 || $partSize > self::MAX_PUT_OBJECT_LENGTH) {
                throw new InvalidArgumentException(
                    'multipart size should not be less than 1MB or greater than 5GB'
                );
            }
        }

        // step1: init multipart upload
        $offset = 0;
        $partNumber = 1;
        $bytesLeft = filesize($filename);
        $partList = array();
        $response = $this->initiateMultipartUpload($bucketName, $key, $options);
        $uploadId =$response->uploadId;

        // step2: upload multipart one by one
        while ($bytesLeft > 0) {
            $partSize = ($partSize > $bytesLeft) ? $bytesLeft : $partSize;
            try {
                $response = $this->uploadPartFromFile($bucketName,
                    $key,
                    $uploadId,
                    $partNumber,
                    $filename,
                    $offset,
                    $partSize);
            } catch (BceServiceException $e) {
                $this->abortMultipartUpload($bucketName, $key, $uploadId);
                throw $e;
            }
            array_push(
                $partList,
                array("partNumber"=>$partNumber, "eTag"=>$response->metadata[BosOptions::ETAG],)
            );
            $offset += $partSize;
            $partNumber++;
            $bytesLeft -= $partSize;
        }

        // step3: complete multipart upload with user-metadata
        $completeOptions = array();
        if (isset($options[BosOptions::USER_METADATA])) {
            $completeOptions = array(
                BosOptions::USER_METADATA => $options[BosOptions::USER_METADATA]

            );
        }
        return $this->completeMultipartUpload($bucketName, $key, $uploadId, $partList, $completeOptions);
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs)
    {
        $defaultArgs = array(
            BosOptions::CONFIG => array(),
            'bucket_name' => null,
            'key' => null,
            'body' => null,
            'headers' => array(),
            'params' => array(),
            'outputStream' => null,
            'parseUserMetadata' => false
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args[BosOptions::CONFIG])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args[BosOptions::CONFIG]
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] =
                HttpContentTypes::JSON;
        }
        // prevent low version curl add a default pragma:no-cache
        if (!isset($args['headers'][HttpHeaders::PRAGMA])) {
            $args['headers'][HttpHeaders::PRAGMA] = '';
        }

        $path = $this->getPath($args['bucket_name'], $args['key']);

        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer,
            $args['outputStream']
        );
        if ($args['outputStream'] === null) {
            $result = $this->parseJsonResult($response['body']);
        } else {
            $result = new \stdClass();
        }
        $result->metadata =
            $this->convertHttpHeadersToMetadata($response['headers']);
        if ($args['parseUserMetadata']) {
            $userMetadata = array();
            foreach ($response['headers'] as $key => $value) {
                if (StringUtils::startsWith($key, HttpHeaders::BCE_USER_METADATA_PREFIX)) {
                    $key = substr($key, strlen(HttpHeaders::BCE_USER_METADATA_PREFIX));
                    $userMetadata[urldecode($key)] = urldecode($value);
                }
            }
            $result->metadata[BosOptions::USER_METADATA] = $userMetadata;
        }

        return $result;

    }

    /**
     * @param string $bucketName The bucket name.
     * @param string $key The object path.
     *
     * @return string
     */
    private function getPath($bucketName = null, $key = null)
    {
        if (isset($this->config[BceClientConfigOptions::CUSTOM])) {
          $bucketName = null;
        }

        return HttpUtils::appendUri(self::BOS_URL_PREFIX, $bucketName, $key);
    }

    /**
     * @param array $headers
     * @param array $options
     */
    private function populateRequestHeadersWithOptions(
        array &$headers,
        array &$options
    ) {
        list(
            $contentType,
            $contentSHA256,
            $storageClass,
            $contentCRC32,
            $xBceAcl,
            $xBceGrantRead,
            $xBceGrantFullControl,
            $cacheControl,
            $contentDisposition,
            $expires,
            $xBceSideEncryption,
            $userMetadata,
            $xBceProcess,
            $xBceForbidOverwrite
        ) = $this->parseOptionsIgnoreExtra(
            $options,
            BosOptions::CONTENT_TYPE,
            BosOptions::CONTENT_SHA256,
            BosOptions::STORAGE_CLASS,
            BosOptions::CONTENT_CRC32,
            BosOptions::BCE_ACL,
            BosOptions::BCE_ACL_GRANT_READ,
            BosOptions::BCE_ACL_GRANT_FULL_CONTROL,
            BosOptions::CACHE_CONTROL,
            BosOptions::CONTENT_DISPOSITION,
            BosOptions::EXPIRES,
            BosOptions::BCE_SERVER_SIDE_ENCRYPTION,
            BosOptions::USER_METADATA,
            BosOptions::BCE_PROCESS,
            BosOptions::BCE_FORBID_OVERWRITE
        );
        if ($contentType !== null) {
            $headers[HttpHeaders::CONTENT_TYPE] = $contentType;
            unset($options[BosOptions::CONTENT_TYPE]);
        }
        if ($contentSHA256 !== null) {
            $headers[HttpHeaders::BCE_CONTENT_SHA256] = $contentSHA256;
            unset($options[BosOptions::CONTENT_SHA256]);
        }
        if ($contentCRC32 !== null) {
            $headers[HttpHeaders::BCE_CONTENT_CRC32] = $contentCRC32;
            unset($options[BosOptions::CONTENT_CRC32]);
        }
        if ($storageClass !== null) {
            $headers[HttpHeaders::BCE_STORAGE_CLASS] = $storageClass;
            unset($options[BosOptions::STORAGE_CLASS]);
        }
        if ($xBceAcl !== null) {
            $headers[HttpHeaders::BCE_ACL] = $xBceAcl;
            unset($options[BosOptions::BCE_ACL]);
        }
        if ($xBceGrantRead !== null) {
            $headers[HttpHeaders::BCE_ACL_GRANT_READ] = $xBceGrantRead;
            unset($options[BosOptions::BCE_ACL_GRANT_READ]);
        }
        if ($xBceGrantFullControl !== null) {
            $headers[HttpHeaders::BCE_ACL_GRANT_FULL_CONTROL] = $xBceGrantFullControl;
            unset($options[BosOptions::BCE_ACL_GRANT_FULL_CONTROL]);
        }
        if ($cacheControl !== null) {
            $headers[HttpHeaders::CACHE_CONTROL] = $cacheControl;
            unset($options[BosOptions::CACHE_CONTROL]);
        }
        if ($contentDisposition !== null) {
            $headers[HttpHeaders::CONTENT_DISPOSITION] = $contentDisposition;
            unset($options[BosOptions::CONTENT_DISPOSITION]);
        }
        if ($expires !== null) {
            $headers[HttpHeaders::EXPIRES] = $expires;
            unset($options[BosOptions::EXPIRES]);
        }
        if ($xBceSideEncryption !== null) {
            $headers[HttpHeaders::BCE_SERVER_SIDE_ENCRYPTION] = $xBceSideEncryption;
            unset($options[BosOptions::BCE_SERVER_SIDE_ENCRYPTION]);
        }
        if ($userMetadata !== null) {
            $this->populateRequestHeadersWithUserMetadata($headers, $userMetadata);
            unset($options[BosOptions::USER_METADATA]);
        }
        if ($xBceProcess !== null) {
            $headers[HttpHeaders::BCE_PROCESS] = $xBceProcess;
            unset($options[BosOptions::BCE_PROCESS]);
        }
        if ($xBceForbidOverwrite !== null) {
            $headers[HttpHeaders::BCE_FORBID_OVERWRITE] = $xBceForbidOverwrite;
            unset($options[BosOptions::BCE_FORBID_OVERWRITE]);
        }
        reset($options);
    }

    /**
     * @param array $headers
     * @param array $userMetadata
     */
    private function populateRequestHeadersWithUserMetadata(
        array &$headers,
        array $userMetadata
    ) {
        $metaSize = 0;
        foreach ($userMetadata as $key => $value) {
            $key = HttpHeaders::BCE_USER_METADATA_PREFIX
                . HttpUtils::urlEncode(trim($key));
            $value = HttpUtils::urlEncode($value);
            $metaSize += strlen($key) + strlen($value);
            if ($metaSize > BosClient::MAX_USER_METADATA_SIZE) {
                throw new BceClientException(
                    'User metadata size should not be greater than '
                    . BosClient::MAX_USER_METADATA_SIZE
                );
            }
            $headers[$key] = $value;
        }
    }

    /**
     * @param string|resource $data
     */
    private function checkData($data)
    {
        switch(gettype($data)) {
            case 'string':
                break;
            case 'resource':
                $streamMetadata = stream_get_meta_data($data);
                if (!$streamMetadata['seekable']) {
                    throw new \InvalidArgumentException(
                        '$data should be seekable.'
                    );
                }
                break;
            default:
                throw new \InvalidArgumentException(
                    'Invalid data type:' . gettype($data)
                    . ' Only string or resource is accepted.'
                );
        }
    }
    /**
     * Set user's max bucket count  and  object count.
     *
     * @param int $maxBucketCount The max bucket count.
     * @param int $maxCapacityMegaBytes The maximum capacity limit of a bucket.
     * @param int $maxObjectCount The max object count of a bucket.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
    */
    public function putUserQuota($maxBucketCount, $maxCapacityMegaBytes, $maxObjectCount, $options = array()){
        if (!is_int($maxBucketCount) || !is_int($maxCapacityMegaBytes) || $maxBucketCount < -1 || $maxCapacityMegaBytes < -1) {
            throw new InvalidArgumentException("Parameters should be valid");
        }
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        $quotaArray = array(
            'maxBucketCount' => $maxBucketCount,
            'maxCapacityMegaBytes' => $maxCapacityMegaBytes,
        );
        if($maxObjectCount) {
            if (is_int($maxObjectCount) && $maxObjectCount >= 1) {
                $quotaArray['maxObjectCount'] = $maxObjectCount;
            }
        }
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'body' => json_encode($quotaArray),
                'params' => array(
                    BosOptions::USER_QUOTA => '',
                )
            )
        );
    }

    /**
     *Get user quota.
     *
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return string
     */
    public function getUserQuota($options = array()) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'params' => array(
                    BosOptions::USER_QUOTA => '',
                )
            )
        );
    }
    /**
     * Delete user quota.
     *
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     */
    public function deleteUserQuota($options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'params' => array(
                    BosOptions::USER_QUOTA => '',
                )
            )
        );
    }

    /**
     * Initialize compliance reservation.
     *
     * @param $bucketName string The bucket name.
     * @param $retentionDays int The retention days.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function initBucketObjectLock($bucketName, $retentionDays, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' =>json_encode(array(
                    'retentionDays' => $retentionDays
                )),
                'params' => array(
                    BosOptions::OBJECT_LOCK => '',
                )
            )
        );
    }

    /**
     * Get bucket compliance reservation.
     *
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function getBucketObjectLock($bucketName, $options = array()){
        list($config) = $this->parseOptions( $options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::OBJECT_LOCK => '',
                )
            )
        );
    }

    /**
     * Delete bucket compliance reservation.
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function deleteBucketObjectLock($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::OBJECT_LOCK => '',
                )
            )
        );
    }

    /**
     * Extend the days of bucket compliance reservation.
     *
     * @param $bucketName string The bucket name.
     * @param $extendRetentionDays int The extendRetention days.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function extendBucketObjectLock($bucketName, $extendRetentionDays, $options = array())
    {
        if (!is_int($extendRetentionDays) || $extendRetentionDays < 0) {
            throw new InvalidArgumentException("Parameters should be valid");
        }
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array(
                    'extendRetentionDays' => $extendRetentionDays,
                )),
                'params' => array(
                    BosOptions::EXTEND_OBJECT_LOCK => '',
                )
            )
        );
    }

    /**
     * The retention policy compliance immediately locked into a locked state LOCKED.
     *
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function completeBucketObjectLock($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::COMPLETE_OBJECT_LOCK => '',
                )
            )
        );
    }

    /**
     * Set the notification rules on the specified bucket.
     *
     * @param $bucketName string The bucket name.
     * @param $notifications string The content of notifications.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function putNotification($bucketName, $notifications, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array(
                    'notifications' => $notifications
                )),
                'params' => array(
                    BosOptions::NOTIFICATION => '',
                )
            )
        );
    }

    /**
     * Get the notification rules on the specified bucket.
     *
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function getNotification($bucketName, $options = array()) {
        list($config) = $this->parseOptions( $options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::NOTIFICATION => '',
                )
            )
        );
    }

    /**
     * Delete the notification rules on the specified bucket.
     *
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function deleteNotification($bucketName, $options = array())
    {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::NOTIFICATION => '',
                )
            )
        );
    }

    /**
     * Set the default storage type of Bucket.
     *
     * @param $bucketName string The bucket name.
     * @param $storageClass string The storage class.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function putBucketStorageClass($bucketName, $storageClass, $options = array()) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'body' => json_encode(array(
                    'storageClass' => $storageClass
                )),
                'params' => array(
                    BosOptions::STORAGE_CLASS => '',
                )
            )
        );
    }

    /**
     * Get the default storage type of Bucket.
     *
     * @param $bucketName string The bucket name.
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.

     * @return mixed
     */
    public function getBucketStorageClass($bucketName, $options = array()) {
        list($config) = $this->parseOptions( $options, BosOptions::CONFIG);
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'params' => array(
                    BosOptions::STORAGE_CLASS => '',
                )
            )
        );
    }

    /**
     * Retrieve archived storage files.
     *
     * @param $bucketName string The bucket name.
     * @param $key string The target key.
     * @param $restoreDay int The duration after thawing.
     * @param $tier string The restore speed 
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating BosClient instance.
     *
     * @return mixed
     */
    public function restoreObject($bucketName, $key, $restoreDay = 7, $tier = "Standard", $options = array()) {
        list($config) = $this->parseOptions($options, BosOptions::CONFIG);
        if (!is_int($restoreDay)) {
            throw new \InvalidArgumentException(
                '$restoreDay should be int.'
            );
        }
        if (!in_array($tier, array("Standard", "Expedited"))) {
            throw new \InvalidArgumentException(
            "tier is not valid."
           );
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                BosOptions::CONFIG => $config,
                'bucket_name' => $bucketName,
                'headers' => array(
                    HttpHeaders::BCE_RESTORE_DAYS => $restoreDay,
                    HttpHeaders::BCE_RESTORE_TIER => $tier,
                ),
                'key' => $key,
                'params' => array(
                    BosOptions::RESTORE => '',
                )
            )
        );
      }

}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Bos;


class BosOptions
{
    // Common options
    const CONFIG = 'config';

    // Options for generatePreSignedUrl
    const SIGN_OPTIONS = 'signOptions';
    const HEADERS = 'headers';
    const PARAMS = 'params';

    const ACCESS_KEY_ID = 'accessKeyId';
    const ACCESS_KEY_SECRET = 'accessKeySecret';
    const ENDPOINT = 'endpoint';
    const CHARSET = 'charset';
    const DATE = 'date';
    const ETAG = 'etag';
    const LAST_MODIFIED = 'lastModified';

    const BUCKET = 'bucket';
    const OBJECT = 'object';

    const RANGE = 'range';

    const OBJECT_CONTENT_STRING = 'objectContentString';
    const OBJECT_CONTENT_STREAM = 'objectDataStream';

    const OBJECT_COPY_SOURCE = 'copySource';
    const OBJECT_COPY_SOURCE_IF_MATCH_TAG = 'ifMatchTag';
    const OBJECT_COPY_SOURCE_IF_NONE_MATCH_TAG = 'ifNoneMatchTag';
    const OBJECT_COPY_SOURCE_IF_UNMODIFIED_SINCE = 'ifUnmodifiedSince';
    const OBJECT_COPY_SOURCE_IF_MODIFIED_SINCE = 'ifModifiedSince';
    const OBJECT_COPY_METADATA_DIRECTIVE = 'metadataDirective';

    const BUCKET_LOCATION = 'bucketLocation';

    const LIST_MAX_UPLOAD_SIZE = 'listMaxUploadSize';

    const ACL = 'acl';
    const LOCATION = 'location';
    const REPLICATION = 'replication';
    const REPLICATION_PROGRESS = 'replicationProgress';

    const UPLOAD_ID = 'uploadId';
    const PART_NUM = 'partNum';
    const PART_LIST = 'partList';

    const CONTENT_LENGTH = 'contentLength';
    const CONTENT_TYPE = 'contentType';
    const CONTENT_MD5 = 'contentMd5';
    const CONTENT_SHA256 = 'contentSHA256';
    const USER_METADATA = 'userMetadata';
    const CONTENT_DISPOSITION = 'contentDisposition';
    const EXPIRES = 'Expires';
    const CACHE_CONTROL = 'cacheControl';

    const BCE_ACL = 'x-bce-acl';
    const BCE_ACL_GRANT_READ = 'x-bce-grant-read';
    const BCE_ACL_GRANT_FULL_CONTROL = 'x-bce-grant-full-control';

    const BCE_SERVER_SIDE_ENCRYPTION = 'x-bce-server-side-encryption';
    const BCE_KEEP_TIME = 'x-bce-keep-last-modified';

    const MAX_PARTS_COUNT = 'maxPartsCount';
    const PART_NUMBER_MARKER = 'partNumberMarker';

    const MAX_KEYS = 'maxKeys';
    const PREFIX = 'prefix';
    const MARKER = 'marker';
    const DELIMITER = 'delimiter';
    const LIMIT = 'limit';
    const STORAGE_CLASS = 'storageClass';
    const NEXT_APPEND_OFFSET = 'nextAppendOffset';
    const BCE_OBJECT_TYPE = 'objectType';
    const COPY_SOURCE_BUCKET = 'copySourceBucket';
    const COPY_SOURCE_OBJECT = 'copySourceObject';
    const CONTENT_CRC32 = 'crc32';

    const BCE_FETCH_MODE = 'x-bce-fetch-mode';
    const BCE_FETCH_SOURCE = 'x-bce-fetch-source';
    const FETCH = 'fetch';

    const LIFECYCLE = 'lifecycle';
    const LOGGING = 'logging';
    const TRASH = 'trash';
    const WEBSITE = 'website';
    const ENCRYPTION = 'encryption';
    const CORS = 'cors';
    const COPYRIGHTPROTECTION = 'copyrightProtection';

    const PART_SIZE = "partSize";
    const BCE_PROCESS = "x-bce-process";

    const SYMLINK = "symlink";
    const BCE_SYMLINK_TARGET = "x-bce-symlink-target";
    const BCE_FORBID_OVERWRITE = "x-bce-forbid-overwrite";

    const USER_QUOTA = 'userQuota';

    const NOTIFICATION = 'notification';

    const EVENT = 'event';
    const RESULT = 'result';

    const OBJECT_LOCK = 'objectlock';
    const EXTEND_OBJECT_LOCK = 'extendobjectlock';
    const COMPLETE_OBJECT_LOCK = 'completeobjectlock';
    const DELETE = 'delete';
    const RESTORE = 'restore';
} 
<?php
/**
 * Created by IntelliJ IDEA.
 * User: zhangjing60
 * Date: 17/8/14
 * Time: 下午4:16
 */

namespace BaiduBce\Services\Vpc;
use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
//include '/Users/zhangjing60/baidu/bce-sdk-bcc-branch/php/src/BaiduBce/BceBaseClient.php';
//include '/Users/zhangjing60/baidu/bce-sdk-bcc-branch/php/src/BaiduBce/Auth/BceV1Signer.php';



class VpcClient extends BceBaseClient {

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * VpcClient constructor.
     * @param array $config
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'vpc');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * @param string $name
     *        The name of vpc to be created.
     * @param string $cidr
     *        The CIDR of the vpc.
     * @param string $description
     *        The description of the vpc.
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function createVpc($name, $cidr,
                                 $description = null, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if(empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }
        if(empty($name)) {
            throw new \InvalidArgumentException(
                'request $name  should not be empty .'
            );
        }
        if(empty($cidr)) {
            throw new \InvalidArgumentException(
                'request $cidr  should not be empty .'
            );
        }
        $body['name'] = $name;
        $body['cidr'] = $cidr;
        if(!empty($description)) {
            $body['description'] = $description;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/vpc'
        );
    }

    /**
     * Return a list of vpcs owned by the authenticated user.
     * @param string $marker
     *        The optional parameter marker specified in the original request to specify
     *        where in the results to begin listing.
     *        Together with the marker, specifies the list result which listing should begin.
     *        If the marker is not specified, the list result will listing from the first one.
     * @param int $maxkeys
     *        The optional parameter to specifies the max number of list result to return.
     *        The default value is 1000.
     * @param boolean $isDefault
     *        The option param demotes whether the vpc is default vpc.
     * @param array $options
     * @return mixed
     */
    public function listVpcs($marker = null, $maxkeys = null, $isDefault = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(!empty($marker)) {
            $params['marker'] = $marker;
        }
        if(!empty($maxkeys)) {
            $params['maxKeys'] = $maxkeys;
        }
        if(is_bool($isDefault)) {
            $params['isDefault'] = $isDefault;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpc'
        );
        
    }

    /**
     * Get the detail information of specified vpc.
     * @param string $vpcId
     *        The id of the vpc
     * @param array $options
     * @return \stdClass
     */
    public function getVpc($vpcId, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        if(empty($vpcId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/vpc/' . $vpcId
        );
    }

    /**
     * Delete the specified vpc owned by the user.All resource in the vpc must be deleted before the vpc itself
     * can be deleted.
     * @param string $vpcId
     *        The id of the specified vpc
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function deleteVpc( $vpcId, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($vpcId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        }
        if(empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpc/' . $vpcId
        );
    }

    /**
     * Modify the special attribute to new value of the vpc owned by the user.
     * @param string $vpcId
     *        The id of the specified vpc
     * @param string $name
     *        The name of the specified vpc
     * @param string $description
     *        The option param to describe the vpc
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function updateVpc($vpcId,$name, $description = null, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if(empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }
        if(empty($vpcId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        }
        if(empty($name)) {
            throw new \InvalidArgumentException(
                'request $name  should not be empty .'
            );
        }
        if(!empty($description)) {
            $body['description'] = $description;
        }
        $params['modifyAttribute'] = null;
        $body['name'] = $name;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body'=>json_encode($body),
                'params' => $params,
            ),
            '/vpc/' .$vpcId
        );
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return string
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }

    /**
     * Get the detailed information of private ip in one specified vpc.
     *
     * @param $vpcId
     *        The id of the specified vpc
     *
     * @param array $privateIpAddresses
     *        The list of private ip addresses to be queried. The optional parameter
     *
     * @param string $privateIpRange
     *        The range of private ip addresses to be queried. The optional parameter which priority is higher than param $privateIpAddresses
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating VpcClient instance.
     *
     * @return mixed
     */
    public function getVpcPrivateIpAddressInfo($vpcId, $privateIpAddresses = null, $privateIpRange = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if(empty($vpcId)) {
            throw new \InvalidArgumentException(
                'The request $vpcId should not be empty.'
            );
        }
        if(!empty($privateIpRange)) {
            $params['privateIpRange'] = $privateIpRange;
        }
        if(!empty($privateIpAddresses)) {
            $params['privateIpAddresses'] = implode(",", $this->objectToArray($privateIpAddresses));
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/vpc/' . $vpcId . '/privateIpAddressInfo'
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }
}<?php
/**
 * Created by IntelliJ IDEA.
 * User: zhangjing60
 * Date: 17/8/14
 * Time: 下午4:15
 */
namespace BaiduBce\Services\Subnet;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;

class SubnetClient extends BceBaseClient {
    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * SubnetClient constructor.
     * @param array $config
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'subnet');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create a subnet with the specified options.
     * 
     * @param string $name
     *        The name of subnet that will be created.
     * @param string $zoneName
     *        the name of available zone which the subnet belong
     *        through listZones, we can get all available zone info at current region
     *        ee.g. "cn-gz-a"  "cn-gz-b"
     * @param string $cidr
     *        The CIDR of this subnet.
     * @param string $vpcId
     *        The id of vpc which this subnet belongs.
     * @param string $subnetType
     *        The option param to describe the type of subnet create
     * @param string $description
     *        The option param to describe the subnet
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function createSubnet($name, $zoneName, $cidr, $vpcId, $subnetType = null,
                                 $description = null, $clientToken = null,  $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($name)) {
            throw new \InvalidArgumentException(
                'request $name  should not be empty .'
            );
        }
        if (empty($zoneName)) {
            throw new \InvalidArgumentException(
                'request $zoneName  should not be empty .'
            );
        }
        if (empty($cidr)) {
            throw new \InvalidArgumentException(
                'request $cidr  should not be empty .'
            );
        }
        if (empty($vpcId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        }
        $body['name'] = $name;
        $body['zoneName'] = $zoneName;
        $body['cidr'] = $cidr;
        $body['vpcId'] = $vpcId;
        if(!empty($subnetType)) {
            $body['subnetType'] = $subnetType;
        }
        if(!empty($description)) {
            $body['description'] = $description;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/subnet'
        );
    }

    /**
     * Return a list of subnets owned by the authenticated user.
     * 
     * @param string $marker
     *        The optional parameter marker specified in the original request to specify
     *        where in the results to begin listing.
     *        Together with the marker, specifies the list result which listing should begin.
     *        If the marker is not specified, the list result will listing from the first one.
     * @param int $maxKeys
     *        The optional parameter to specifies the max number of list result to return.
     *        The default value is 1000.
     * @param string $vpcId
     *        The id of the vpc
     * @param string $zoneName
     *        the name of available zone which the subnet belong
     *        through listZones, we can get all available zone info at current region
     *        ee.g. "cn-gz-a"  "cn-gz-b"
     * @param string $subnetType
     *        he option param to describe the type of subnet to be created
     * @param array $options
     * @return mixed
     */
    public function listSubnets($marker = null, $maxKeys = null, $vpcId = null, $zoneName = null, 
                                $subnetType = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }
        if (!empty($maxKeys)) {
            $params['maxKeys'] = $maxKeys;
        }
        if (!empty($vpcId)) {
            $params['vpcId'] = $vpcId;
        }
        if (!empty($zoneName)) {
            $params['zoneName'] = $zoneName;
        }
        if (!empty($subnetType)) {
            $params['subnetType'] = $subnetType;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/subnet'
        );
    }

    /**
     * Get the detail information of a specified subnet.
     * 
     * @param string $subnetId
     *        the id of the subnet
     * @param array $options
     * @return mixed
     */
    public function getSubnet($subnetId, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($subnetId)) {
            throw new \InvalidArgumentException(
                'request $subnetId  should not be empty .'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,

            ),
            '/subnet/' . $subnetId
        );
    }

    /**
     * Delete the specified subnet owned by the user.
     * 
     * @param string $subnetId
     *        the id of the subnet to be deleted
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function deleteSubnet($subnetId, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($subnetId)) {
            throw new \InvalidArgumentException(
                'request $subnetId  should not be empty .'
            );
        }
        if (empty($clientToken)) {
            $params['clientToken'] = $this -> generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/subnet/' . $subnetId
        );

    }

    /**
     * Modify the special attribute to new value of the subnet owned by the user.
     * 
     * @param string $subnetId
     *        The id of the specific subnet to be updated
     * @param string $name
     *        The name of the subnet
     * @param string $description
     *        The option param to describe the subnet
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function updateSubnet($subnetId, $name, $description = null, $clientToken = null, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this -> generateClientToken();
        }
        else {
            $params['clientToken'] = $clientToken;
        }

        if (empty($subnetId)) {
            throw new \InvalidArgumentException(
                'request $subnetId  should not be empty .'
            );
        }

        if (empty($name)) {
            throw new \InvalidArgumentException(
                'request $name  should not be empty .'
            );
        }
        $body['name'] = $name;
        if (!empty($description)) {
            $body['description'] = $description;
        }
        $params['modifyAttribute'] = null;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/subnet/' . $subnetId
        );
    }
    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }


}<?php
/*
* Copyright 2015 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Lss;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\DateUtils;

class LssClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v5';

    /**
     * The LssClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'LssClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create a session.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          description: string, session description
     *          preset: string, session preset name
     *          region: string, session region, valid values: bj/gz
     *          pullUrl: string, pulling session's live source url
     *          notification: string, session notification name
     *          securityPolicy: string, session security policy name
     *          imageWatermarks: array, image watermark list
     *          timestampWatermarks: array, timestamp watermark list
     *          thumbnail: string, session thumbnail name
     *      }
     * @return mixed created session detail
     */
    public function createSession($options = array())
    {
        list($config, $description, $preset, $presets, $recording, $region, $pullUrl, $notification,
            $securityPolicy, $imageWatermarks, $timestampWatermarks, $thumbnail) = $this->parseOptions(
            $options,
            'config',
            'description',
            'preset',
            'presets',
            'recording',
            'region',
            'pullUrl',
            'notification',
            'securityPolicy',
            'imageWatermarks',
            'timestampWatermarks',
            'thumbnail'
        );

        $body = array();

        if ($description !== null) {
            $body['description'] = $description;
        } else {
            $body['description'] = '';
        }
        if ($preset !== null) {
            $body['preset'] = $preset;
        }
        if ($presets !== null) {
            $presetMap = array();
            for ($i = 0; $i < count($presets); $i++) {
                $presetMap['L'.$i] = $presets[$i];
            }
            $body['presets'] = $presetMap;
        }
        if ($recording !== null) {
            $body['recording'] = $recording;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }
        if ($securityPolicy !== null) {
            $body['securityPolicy'] = $securityPolicy;
        }
        if ($thumbnail !== null) {
            $body['thumbnail'] = $thumbnail;
        }

        $publish = array();
        if ($region !== null) {
            $publish['region'] = $region;
        }
        if ($pullUrl !== null) {
            $publish['pullUrl'] = $pullUrl;
        }
        if (count($publish) > 0) {
            $body['publish'] = $publish;
        }

        $watermarks = array();
        if ($imageWatermarks !== null) {
            $watermarks['image'] = $imageWatermarks;
        }
        if ($timestampWatermarks !== null) {
            $watermarks['timestamp'] = $timestampWatermarks;
        }
        if (count($watermarks) > 0) {
            $body['watermarks'] = $watermarks;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/session'
        );
    }

    /**
     * Update pull url of session.
     *
     * @param $sessionId string, session id
     * @param $pullUrl string, pullUrl
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session detail
     * @throws BceClientException
     */
    public function updatePullUrl($sessionId, $pullUrl, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array();

        if ($pullUrl !== null) {
            $params['pullUrl'] = $pullUrl;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Get a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session detail
     * @throws BceClientException
     */
    public function getSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Get a session with token in push/play url.
     *
     * More specifically, if the security policy used by this session enables push/play auth,
     * its push/play url need be updated with a token parameter computed from the session id,
     * the session stream, etc., and the security policy auth key. This function returns the
     * detailed session info with push/play url updated, if necessary.
     *
     * @param $sessionId string, session id
     * @param int $expireInMinute number, the push/play url expire time in minute
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getSessionWithToken($sessionId, $expireInMinute = 120, $options = array())
    {
        $session = $this->getSession($sessionId, $options);
        $securityPolicy = $this->getSecurityPolicy($session->securityPolicy);
        $currentTime = new \DateTime();
        $expireTime = $currentTime->add(new \DateInterval("PT{$expireInMinute}M"));
        $expireTime->setTimezone(DateUtils::$UTC_TIMEZONE);
        $expireString = DateUtils::formatAlternateIso8601Date($expireTime);
        if ($securityPolicy->auth->play) {
            if (isset($session->play->hlsUrl)) {
                $hlsUrl = $session->play->hlsUrl;
                $hlsTokenPlain = '/' . $sessionId . '/live.m3u8;' . $expireString;
                $hlsToken = hash_hmac('sha256', $hlsTokenPlain, $securityPolicy->auth->key);
                $session->play->hlsUrl = $hlsUrl . '?token=' . $hlsToken . '&expire=' . $expireString;
            } elseif (isset($session->play->hlsUrls)) {
                $hlsUrls = array();
                foreach ($session->play->hlsUrls as $line => $hlsUrl) {
                    if (isset($hlsUrl)) {
                        $hlsToken = '';
                        if ($line == 'L0') {
                            $hlsTokenPlain = '/' . $sessionId . '/live.m3u8;' . $expireString;
                            $hlsToken = hash_hmac('sha256', $hlsTokenPlain, $securityPolicy->auth->key);
                        } else {
                            $hlsTokenPlain = '/' . $sessionId . '-' . $line . '/live.m3u8;' . $expireString;
                            $hlsToken = hash_hmac('sha256', $hlsTokenPlain, $securityPolicy->auth->key);
                        }
                        $hlsUrls[$line] = $hlsUrl . '?token=' . $hlsToken . '&expire=' . $expireString;
                    }
                }
                $session->play->hlsUrls = $hlsUrls;
            }

            if (isset($session->play->rtmpUrl)) {
                $rtmpUrls = array();
                $rtmpUrl = $session->play->rtmpUrl;
                $rtmpTokenPlain = $sessionId . ';' . $expireString;
                $rtmpToken = hash_hmac('sha256', $rtmpTokenPlain, $securityPolicy->auth->key);
                $session->play->rtmpUrl = $rtmpUrl . '?token=' . $rtmpToken . '&expire=' . $expireString;
            } elseif (isset($session->play->rtmpUrls)) {
                foreach ($session->play->rtmpUrls as $line => $rtmpUrl) {
                    if (isset($rtmpUrl)) {
                        $rtmpTokenPlain = $sessionId . ';' . $expireString;
                        $rtmpToken = hash_hmac('sha256', $rtmpTokenPlain, $securityPolicy->auth->key);
                        $rtmpUrls[$line] = $rtmpUrl . '?token=' . $rtmpToken . '&expire=' . $expireString;
                    }
                }
                $session->play->rtmpUrls = $rtmpUrls;
            }

            if (isset($session->play->flvUrl)) {
                $flvUrl = $session->play->flvUrl;
                $flvTokenPlain = $sessionId . ';' . $expireString;
                $flvToken = hash_hmac('sha256', $flvTokenPlain, $securityPolicy->auth->key);
                $session->play->flvUrl = $flvUrl . '?token=' . $flvToken . '&expire=' . $expireString;
            } elseif (isset($session->play->flvUrls)) {
                $flvUrls = array();
                foreach ($session->play->flvUrls as $line => $flvUrl) {
                    if (isset($flvUrl)) {
                        $flvTokenPlain = $sessionId . ';' . $expireString;
                        $flvToken = hash_hmac('sha256', $flvTokenPlain, $securityPolicy->auth->key);
                        $flvUrls[$line] = $flvUrl . '?token=' . $flvToken . '&expire=' . $expireString;
                    }
                }
                $session->play->flvUrls = $flvUrls;
            }
        }

        if ($securityPolicy->auth->push) {
            if (isset($session->publish->pushUrl)) {
                $pushUrl = $session->publish->pushUrl;
                $pushTokenPlain = $session->publish->pushStream . ';' . $expireString;
                $pushToken = hash_hmac('sha256', $pushTokenPlain, $securityPolicy->auth->key);
                $session->publish->pushUrl = $pushUrl . '?token=' . $pushToken . '&expire=' . $expireString;
            }
        }

        return $session;
    }

    /**
     * List sessions.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          status: session status, READY / ONGOING / PAUSED
     *          marker: query marker.
     *          maxSize: max number of listed sessions.
     *      }
     * @return mixed session list
     */
    public function listSessions($options = array())
    {
        list($config, $status, $marker, $maxSize) = $this->parseOptions($options, 'config', 'status', 'marker', 'maxSize');

        $params = array();

        if ($status !== null) {
            $params['status'] = $status;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxSize !== null) {
            $params['maxSize'] = $maxSize;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/session'
        );
    }

    /**
     * List sessions with a status filter.
     *
     * @param $status string, session status as a filter,
     *                 valid values: READY / ONGOING / PAUSED
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session list
     * @throws BceClientException
     */
    public function listSessionsByStatus($status, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($status)) {
            throw new BceClientException("The parameter status "
                . "should NOT be null or empty string");
        }

        $params = array(
            'status' => $status,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/session'
        );
    }

    /**
     * Begin a pulling session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function pullSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'pull' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }


    /**
     * Pause a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function pauseSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'pause' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Resume a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function resumeSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'resume' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Refresh a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed refreshed session detail
     * @throws BceClientException
     */
    public function refreshSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'refresh' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Delete a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deleteSession($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Set cuepoint to session.
     *
     * @param $sessionId string, session id
     * @param $callback string, callback method name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          arguments: array, callback arguments
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function setCuepoint($sessionId, $callback, $options = array())
    {
        list($config, $arguments) = $this->parseOptions(
            $options,
            'config',
            'arguments'
        );

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }
        if (empty($callback)) {
            throw new BceClientException("The parameter callback "
                . "should NOT be null or empty string");
        }

        $body = array();

        $body['callback'] = $callback;

        if ($arguments !== null) {
            $body['arguments'] = $arguments;
        }

        $params = array(
            'cuepoint' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body, JSON_FORCE_OBJECT),
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Start recording a session.
     *
     * @param $sessionId string, session id
     * @param $recording string, recording name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function startRecording($sessionId, $recording, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        if (empty($recording)) {
            throw new BceClientException("The parameter recording "
                . "should NOT be null or empty string");
        }

        $params = array(
            'recording' => $recording,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Stop recording a session.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function stopRecording($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'recording' => '',
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Get session real-time source info.
     *
     * @param $sessionId string, session id
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getSessionSourceInfo($sessionId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($sessionId)) {
            throw new BceClientException("The parameter sessionId "
                . "should NOT be null or empty string");
        }

        $params = array(
            'sourceInfo' => null,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/session/$sessionId"
        );
    }

    /**
     * Create a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          description: string, preset description
     *          forwardOnly: boolean, whether the preset is forward-only.
     *                      when forwardOnly = true, should not set audio/video.
     *          audio: { audio output settings
     *              bitRateInBps: number, output audio bit rate
     *              sampleRateInHz: number, output audio sample rate
     *              channels: number, output audio
     *          },
     *          video: { video output settings
     *              codec: string, output video codec, valid values: h264
     *              codecOptions: {
     *                  profile: string, valid values: baseline/main/high
     *              }
     *              bitRateInBps: number, output video bit rate
     *              maxFrameRate: number, output video max frame rate
     *              maxWidthInPixel: number, output video max width
     *              maxHeightInPixel: number, output video max height
     *              sizingPolicy: string, output video sizing policy,
     *                            valid values: keep/stretch/shrinkToFit
     *          },
     *          hls: { hls output settings
     *              segmentTimeInSecond: number, each hls segment time length
     *              segmentListSize: number, length of segment list in the output m3u8
     *              adaptive: boolean, whether adaptive hls is enabled
     *          },
     *          rmtp: { rmtp output settings
     *              gopCache: boolean, whether or not cache 1 gop
     *          }
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createPreset($name, $options = array())
    {
        list($config, $description, $forwardOnly, $audio, $video, $hls, $rtmp) = $this->parseOptions(
            $options,
            'config',
            'description',
            'forwardOnly',
            'audio',
            'video',
            'hls',
            'rtmp'
        );

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
        );

        if ($description !== null) {
            $body['description'] = $description;
        }
        if ($forwardOnly !== null) {
            $body['forwardOnly'] = $forwardOnly;
        }
        if ($audio !== null) {
            $body['audio'] = $audio;
        }
        if ($video !== null) {
            $body['video'] = $video;
        }
        if ($hls !== null) {
            $body['hls'] = $hls;
        }
        if ($rtmp !== null) {
            $body['rtmp'] = $rtmp;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/preset'
        );
    }

    /**
     * Get a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed preset detail
     * @throws BceClientException
     */
    public function getPreset($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/preset/$name"
        );
    }

    /**
     * List presets.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @param array $options
     * @return mixed
     */
    public function listPresets($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/preset'
        );
    }

    /**
     * Delete a preset.
     *
     * @param $name string, preset name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deletePreset($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/preset/$name"
        );
    }

    /**
     * Creates a notification.
     *
     * @param $name string, notification name
     * @param $endpoint string, notification endpoint
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createNotification($name, $endpoint, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }
        if (empty($endpoint)) {
            throw new BceClientException("The parameter endpoint "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
            'endpoint' => $endpoint,
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/notification'
        );
    }

    /**
     * Gets a notification.
     *
     * @param $name string, notification name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed notification detail
     * @throws BceClientException
     */
    public function getNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }

    /**
     * List notifications.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed notification list
     */
    public function listNotifications($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/notification'
        );
    }

    /**
     * Delete a notification.
     *
     * @param $name string notification name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deleteNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }

    /**
     * Get a security policy.
     *
     * @param $name string, security policy name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed security policy detail
     * @throws BceClientException
     */
    public function getSecurityPolicy($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/securitypolicy/$name"
        );
    }

    /**
     * List security policies.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed security policy list
     */
    public function listSecurityPolicies($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/securitypolicy'
        );
    }

    /**
     * Get a recording.
     *
     * @param $name string, recording name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed security policy detail
     * @throws BceClientException
     */
    public function getRecording($name, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/recording/$name"
        );
    }

    /**
     * List recordings.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed recording list
     */
    public function listRecordings($options = array()) {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/recording'
        );
    }

    /**
     * Create a image watermark.
     *
     * @param $name string, image watermark name
     * @param $content string, watermark image base64 encode
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          maxWidthInPixel: number, watermark maximum width in pixel
     *          maxHeightInPixel: number, watermark maximum Height in pixel
     *          sizingPolicy: string, watermark size retractable policy
     *          verticalAlignment: string, vertically aligned manner
     *          horizontalAlignment: string, horizontal aligned manner
     *          verticalOffsetInPixel: number, vertical offset in pixel
     *          horizontalOffsetInPixel: number, horizontal offset in pixel
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createImageWatermark($name, $content, $options = array())
    {
        list($config, $maxWidthInPixel, $maxHeightInPixel,
            $sizingPolicy, $verticalAlignment, $horizontalAlignment,
            $verticalOffsetInPixel, $horizontalOffsetInPixel) = $this->parseOptions(
            $options,
            'config',
            'maxWidthInPixel',
            'maxHeightInPixel',
            'sizingPolicy',
            'verticalAlignment',
            'horizontalAlignment',
            'verticalOffsetInPixel',
            'horizontalOffsetInPixel'
        );

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }
        if (empty($content)) {
            throw new BceClientException("The parameter content "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
            'content' => $content,
        );

        $size = array();
        if ($maxWidthInPixel !== null) {
            $size['maxWidthInPixel'] = $maxWidthInPixel;
        }
        if ($maxHeightInPixel !== null) {
            $size['maxHeightInPixel'] = $maxHeightInPixel;
        }
        if ($sizingPolicy !== null) {
            $size['sizingPolicy'] = $sizingPolicy;
        }
        if (count($size) > 0) {
            $body['size'] = $size;
        }

        $position = array();
        if ($verticalAlignment !== null) {
            $position['verticalAlignment'] = $verticalAlignment;
        }
        if ($horizontalAlignment !== null) {
            $position['horizontalAlignment'] = $horizontalAlignment;
        }
        if ($verticalOffsetInPixel !== null) {
            $position['verticalOffsetInPixel'] = $verticalOffsetInPixel;
        }
        if ($horizontalOffsetInPixel !== null) {
            $position['horizontalOffsetInPixel'] = $horizontalOffsetInPixel;
        }
        if (count($position) > 0) {
            $body['position'] = $position;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body, JSON_FORCE_OBJECT),
            ),
            "/watermark/image"
        );
    }

    /**
     * Get a image watermark.
     *
     * @param $name string, image watermark name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed image watermark detail
     * @throws BceClientException
     */
    public function getImageWatermark($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/watermark/image/$name"
        );
    }

    /**
     * List image watermarks.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed image watermark list
     */
    public function listImageWatermarks($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/watermark/image'
        );
    }

    /**
     * Delete a image watermark.
     *
     * @param $name string, image watermark name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deleteImageWatermark($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/watermark/image/$name"
        );
    }

    /**
     * Create a timestamp watermark.
     *
     * @param $name string, image watermark name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          timezone: string, timestamp time zone
     *          alpha: number, timestamp watermark transparency
     *          fontFamily: string, timestamp watermark fonts
     *          fontSizeInPoint: number, font size in point
     *          fontColor: string, timestamp watermark font color
     *          backgroundColor: string, background color
     *          verticalAlignment: string, vertically aligned manner
     *          horizontalAlignment: string, horizontal aligned manner
     *          verticalOffsetInPixel: number, vertical offset in pixel
     *          horizontalOffsetInPixel: number, horizontal offset in pixel
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createTimestampWatermark($name, $options = array())
    {
        list($config, $timezone, $alpha, $fontFamily, $fontSizeInPoint,
            $fontColor, $backgroundColor, $verticalAlignment, $horizontalAlignment,
            $verticalOffsetInPixel, $horizontalOffsetInPixel) = $this->parseOptions(
            $options,
            'config',
            'timezone',
            'alpha',
            'fontFamily',
            'fontSizeInPoint',
            'fontColor',
            'backgroundColor',
            'verticalAlignment',
            'horizontalAlignment',
            'verticalOffsetInPixel',
            'horizontalOffsetInPixel'
        );

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
        );

        if ($timezone !== null) {
            $body['timezone'] = $timezone;
        }
        if ($alpha !== null) {
            $body['alpha'] = $alpha;
        }

        $font = array();
        if ($fontFamily !== null) {
            $font['family'] = $fontFamily;
        }
        if ($fontSizeInPoint !== null) {
            $font['sizeInPoint'] = $fontSizeInPoint;
        }
        if ($fontColor !== null) {
            $font['color'] = $fontColor;
        }
        if (count($font) > 0) {
            $body['font'] = $font;
        }

        $background = array();
        if ($backgroundColor !== null) {
            $background['color'] = $backgroundColor;
            $body['background'] = $background;
        }

        $position = array();
        if ($verticalAlignment !== null) {
            $position['verticalAlignment'] = $verticalAlignment;
        }
        if ($horizontalAlignment !== null) {
            $position['horizontalAlignment'] = $horizontalAlignment;
        }
        if ($verticalOffsetInPixel !== null) {
            $position['verticalOffsetInPixel'] = $verticalOffsetInPixel;
        }
        if ($horizontalOffsetInPixel !== null) {
            $position['horizontalOffsetInPixel'] = $horizontalOffsetInPixel;
        }
        if (count($position) > 0) {
            $body['position'] = $position;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body, JSON_FORCE_OBJECT),
            ),
            "/watermark/timestamp"
        );
    }

    /**
     * Get a timestamp watermark.
     *
     * @param $name string, timestamp watermark name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed timestamp watermark detail
     * @throws BceClientException
     */
    public function getTimestampWatermark($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/watermark/timestamp/$name"
        );
    }

    /**
     * List timestamp watermarks.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed timestamp watermark list
     */
    public function listTimestampWatermarks($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/watermark/timestamp'
        );
    }

    /**
     * Delete a timestamp watermark.
     *
     * @param $name string, timestamp watermark name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deleteTimestampWatermark($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/watermark/timestamp/$name"
        );
    }

    /**
     * API for Lss 3.0.
     * Support push and play stream by customized domain.
     */

    /**
     * Get a stream info.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session detail
     * @throws BceClientException
     */
    public function getStream($domain, $app, $stream, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * Create a stream.
     *
     * @param $domain string, name of play domain
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session detail
     * @throws BceClientException
     */
    public function createStream($domain, $options = array())
    {
        list($config,
            $app,
            $publish,
            $scene,
            $recording,
            $notification,
            $thumbnail,
            $thumbnails,
            $watermarks,
            $destinationPushUrl
        ) = $this->parseOptions(
            $options,
            'config',
            'app',
            'publish',
            'scene',
            'recording',
            'notification',
            'thumbnail',
            'thumbnails',
            'watermarks',
            'destinationPushUrl');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }

        $body = array();

        if ($app !== null) {
            $body['app'] = $app;
        }
        if ($publish !== null) {
            $body['publish'] = $publish;
        }
        if ($scene !== null) {
            $body['scene'] = $scene;
        }
        if ($recording !== null) {
            $body['recording'] = $recording;
        }
        if ($notification !== null) {
            $body['notification'] = $notification;
        }
        if ($thumbnail !== null) {
            $body['thumbnail'] = $thumbnail;
        }
        if ($thumbnails !== null) {
            $body['thumbnails'] = $thumbnails;
        }
        if ($watermarks !== null) {
            $body['watermarks'] = $watermarks;
        }
        if ($destinationPushUrl !== null) {
            $body['destinationPushUrl'] = $destinationPushUrl;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/domain/$domain/stream"
        );
    }

    /**
     * Delete a stream.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed session detail
     * @throws BceClientException
     */
    public function deleteStream($domain, $app, $stream, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * List streams.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          status: stream status, READY / ONGOING / PAUSED
     *          marker: query marker.
     *          maxSize: max number of listed sessions.
     *      }
     * @return mixed stream list
     */
    public function listStreams($domain, $options = array())
    {
        list($config, $status, $marker, $maxSize) = $this->parseOptions($options, 'config', 'status', 'marker', 'maxSize');

        $params = array();

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if ($status !== null) {
            $params['status'] = $status;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxSize !== null) {
            $params['maxSize'] = $maxSize;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/domain/$domain/stream"
        );
    }

    /**
     * Pause a stream.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function pauseStream($domain, $app, $stream, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        $params = array(
            'pause' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * Resume a stream.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function resumeStream($domain, $app, $stream, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        $params = array(
            'resume' => null,
        );

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * Get domain static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainStatistics($domain, $options = array())
    {
        list($config, $startDate, $endDate, $aggregate) = $this->parseOptions(
            $options,
            'config',
            'startDate',
            'endDate',
            'aggregate'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($startDate)) {
            throw new BceClientException("The query parameter startDate "
                . "should NOT be null or empty string");
        }
        if (empty($endDate)) {
            throw new BceClientException("The query parameter endDate "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startDate' => $startDate,
            'endDate' => $endDate,
            'aggregate' => $aggregate,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain"
        );
    }

    /**
     * Get domain summary static info.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainSummaryStatistics($options = array())
    {
        list($config, $startTime, $endTime) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/summary"
        );
    }

    /**
     * List domain static info.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function listDomainStatistics($options = array())
    {
        list($config, $startTime, $endTime, $keywordType, $keyword, $orderBy) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'keywordType',
            'keyword',
            'orderBy'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'keywordType' => $keywordType,
            'keyword' => $keyword,
            'orderBy' => $orderBy,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/list"
        );
    }

    /**
     * Get stream static info.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getStreamStatistics($domain, $app, $stream, $options = array())
    {
        list($config, $startDate, $endDate, $aggregate) = $this->parseOptions(
            $options,
            'config',
            'startDate',
            'endDate',
            'aggregate'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }
        if (empty($startDate)) {
            throw new BceClientException("The query parameter startDate "
                . "should NOT be null or empty string");
        }
        if (empty($endDate)) {
            throw new BceClientException("The query parameter endDate "
                . "should NOT be null or empty string");
        }


        $params = array(
            'startDate' => $startDate,
            'endDate' => $endDate,
            'aggregate' => $aggregate,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * List stream static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function listStreamStatistics($domain, $options = array())
    {
        list($config, $app, $startTime, $endTime, $pageNo, $pageSize,
            $keywordType, $keyword, $orderBy) = $this->parseOptions(
            $options,
            'config',
            'app',
            'startTime',
            'endTime',
            'pageNo',
            'pageSize',
            'keywordType',
            'keyword',
            'orderBy'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }

        $params = array(
            'app' => $app,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'pageNo' => $pageNo,
            'pageSize' => $pageSize,
            'keywordType' => $keywordType,
            'keyword' => $keyword,
            'orderBy' => $orderBy,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain/stream"
        );
    }

    /**
     * Get all domain traffic static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getAllDomainTrafficStatistics($options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/traffic"
        );
    }

    /**
     * Get a specific domain traffic static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainTrafficStatistics($domain, $options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain/traffic"
        );
    }

    /**
     * Get all domain bandwidth static info.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getAllDomainBandwidthStatistics($options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/bandwidth"
        );
    }

    /**
     * Get a specific domain bandwidth static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainBandwidthStatistics($domain, $options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain/bandwidth"
        );
    }

    /**
     * Get all domain play count static info.
     *
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getAllDomainPlayCountStatistics($options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/playcount"
        );
    }

    /**
     * Get a specific domain play count static info.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getDomainPlayCountStatistics($domain, $options = array())
    {
        list($config, $startTime, $endTime, $timeInterval) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime',
            'timeInterval'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }
        if (empty($timeInterval)) {
            throw new BceClientException(
                "The query parameter timeInterval should be set in [SHORT_TERM|MID_TERM|LONG_TERM] "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
            'timeInterval' => $timeInterval,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/$domain/playcount"
        );
    }

    /**
     * Update watermark of the stream.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function updateWatermarksOfStream($domain, $app, $stream, $options = array())
    {
        list($config, $watermarks) = $this->parseOptions($options, 'config', 'watermarks');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        $body = array();

        if (count($watermarks) > 0) {
            $body['watermarks'] = $watermarks;
        }

        $params = array(
            'watermark' => null,
        );

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * List realtime stream static info.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function listRealtimeStreamStatistics($domain, $app, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The query parameter app "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/statistics/realtime/domain/$domain/app/$app"
        );
    }

    /**
     * Get realtime live source info of the stream.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getRealtimeStreamSourceInfo($domain, $app, $stream, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }

        $params = array(
            'sourceInfo' => null,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * Get a security policy of LSS 3.0.
     *
     * @param $name string, security policy name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed security policy detail
     * @throws BceClientException
     */
    public function querySecurityPolicy($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                . "should NOT be null or empty string");
        }
        $this->prefix = '/v6';

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/securitypolicy/$name"
        );
    }

    /**
     * Add metadata into living stream for LSS 3.0.
     *
     * @param $domain string, name of play domain
     * @param $app string, name of app
     * @param $stream string, name of stream
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function AddMetadataIntoStream($domain, $app, $stream, $options = array())
    {
        list($config, $metadata) = $this->parseOptions($options, 'config', 'metadata');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }
        if (empty($metadata)) {
            throw new BceClientException("The parameter metadata "
                . "should NOT be null or empty string");
        }

        $params = array(
            'addMetadata' => null,
        );

        $body = array(
            'metadata' => $metadata
        );
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            "/domain/$domain/app/$app/stream/$stream"
        );
    }

    /**
     * Get realtime live source info list of a domain.
     *
     * @param $domain string, name of play domain
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getSourceInfoByDomain($domain, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/domain/$domain/sourceInfo"
        );
    }

    /**
     * clip recording video.
     *
     * @param $name string, recording name
     * @param array $options Supported options:
     *      {
     *          config: the optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed security policy detail
     * @throws BceClientException
     */
    public function clipRecordingVideo($domain, $app, $stream, $options = array()) {
        list($config, $filename, $startTime, $endTime, $format, $pipeline,
            $preset, $sourceFile, $clipId) = $this->parseOptions(
            $options,
            'config',
            'filename',
            'startTime',
            'endTime',
            'format',
            'pipeline',
            'preset',
            'sourceFile',
            'clipId'
        );

        if (empty($domain)) {
            throw new BceClientException("The parameter domain "
                . "should NOT be null or empty string");
        }
        if (empty($app)) {
            throw new BceClientException("The parameter app "
                . "should NOT be null or empty string");
        }
        if (empty($stream)) {
            throw new BceClientException("The parameter stream "
                . "should NOT be null or empty string");
        }
        $body = array(
            'playDomain' => $domain,
            'app' => $app,
            'stream' => $stream,
        );

        if ($filename !== null) {
            $body['filename'] = $filename;
        }
        if ($startTime !== null) {
            $body['startTime'] = $filename;
        }
        if ($endTime !== null) {
            $body['endTime'] = $filename;
        }
        if ($format !== null) {
            $body['format'] = $filename;
        }
        if ($pipeline !== null) {
            $body['pipeline'] = $filename;
        }
        if ($preset !== null) {
            $body['preset'] = $filename;
        }
        if ($sourceFile !== null) {
            $body['sourceFile'] = $filename;
        }
        if ($clipId !== null) {
            $body['clipId'] = $filename;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/recording/clip'
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }
}
<?php

namespace BaiduBce\Services\Acl;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;

class AclClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * AclClient constructor.
     * @param array $config
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'acl');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }


    /**
     * Get the acl information.
     * @param string $vpcId
     *        The id of the vpc
     * @param array $options
     * @return Acl information
     */
    public function getAcl($vpcId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($vpcId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        } else {
            $params['vpcId'] = $vpcId;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/acl'
        );
    }


    /**
     * @param array $aclRules
     *        The list of AclRule to be created.
     * @return mixed
     */
    public function createAclRule($aclRules, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($aclRules)) {
            throw new \InvalidArgumentException(
                'request $aclRules should not be empty .'
            );
        }
        $body['aclRules'] = $this->objectToArray($aclRules);
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/acl/rule'
        );
    }

    /**
     * Return a list of acl rules which belong to the subnet.
     * @param string $marker
     *        The optional parameter marker specified in the original request to specify
     *        where in the results to begin listing.
     *        Together with the marker, specifies the list result which listing should begin.
     *        If the marker is not specified, the list result will listing from the first one.
     * @param int $maxkeys
     *        The optional parameter to specifies the max number of list result to return.
     *        The default value is 1000.
     * @param string $subnetId
     *        The subnet id which you want to list aclRules .
     * @param array $options
     * @return The list of acl rule which belong to the $subnetId  subnet.
     */
    public function listAclRules($subnetId, $marker = null, $maxkeys = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (!empty($marker)) {
            $params['marker'] = $marker;
        }
        if (!empty($maxkeys)) {
            $params['maxKeys'] = $maxkeys;
        }
        if (empty($subnetId)) {
            throw new \InvalidArgumentException(
                'request $subnetId should not be empty .'
            );
        } else {
            $params['subnetId'] = $subnetId;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/acl/rule'
        );

    }

    /**
     * Delete the specified aclRule owned by the user.
     * @param string $aclRuleId
     *        The id of the specified acl rule.
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function deleteAclRule($aclRuleId, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($aclRuleId)) {
            throw new \InvalidArgumentException(
                'request $vpcId  should not be empty .'
            );
        }
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/acl/rule/' . $aclRuleId
        );
    }

    /**
     * update the rule attribute of the vpc owned by the user.
     * @param string $aclRuleId
     *        The id of the specified acl rule.
     * @param string $description
     *        The description of the specified acl rule.
     * @param string $protocol
     *        The protocol of the specified acl rule.include 'all' 'tcp' 'udp' and 'icmp'
     * @param string $sourceIpAddress
     *        The sourceIpAddress of the specified acl rule.
     * @param string $destinationIpAddress
     *        The destinationIpAddress of the specified acl rule.
     * @param string $sourcePort
     *        The sourcePort of the specified acl rule.
     * @param string $destinationPort
     *        TThe destinationPort of the specified acl rule.
     * @param string $position
     *        The position of the specified acl rule.the range of position is[1,5000]
     * @param string $action
     *        The action of the specified acl rule.include 'allow' and 'deny'.
     * @param string $clientToken
     *        An ASCII string whose length is less than 64.
     *        The request will be idempotent if clientToken is provided.
     *        If the clientToken is not specified by the user, a random String generated by default algorithm will be used.
     * @param array $options
     * @return mixed
     */
    public function updateAclRule($aclRuleId, $description = null, $protocol = null, $sourceIpAddress = null, $destinationIpAddress = null, $sourcePort = null, $destinationPort = null, $position = null, $action = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($aclRuleId)) {
            throw new \InvalidArgumentException(
                'request $aclRuleId  should not be empty .'
            );
        }
        $body['description'] = $description;
        $body['protocol'] = $protocol;
        $body['sourceIpAddress'] = $sourceIpAddress;
        $body['destinationIpAddress'] = $destinationIpAddress;
        $body['sourcePort'] = $sourcePort;
        $body['destinationPort'] = $destinationPort;
        $body['position'] = $position;
        $body['action'] = $action;
        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/acl/rule/' . $aclRuleId
        );
    }


    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }


    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return string
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php

namespace BaiduBce\Services\Acl\model;

class AclRule
{
    var $subnetId;
    var $description;
    var $protocol;
    var $sourceIpAddress;
    var $destinationIpAddress;
    var $sourcePort;
    var $destinationPort;
    var $position;
    var $direction;
    var $action;

    /**
     * AclRule information.
     *
     * @param string $subnetId
     *          The acl rule's subnetId .
     *
     * @param string $description
     *          The acl rule's description .The optional parameter.
     *
     * @param string $protocol
     *          The acl rule's protocol .
     *
     * @param string $sourceIpAddress
     *          The acl rule's sourceIpAddress .
     *
     * @param string $destinationIpAddress
     *          The acl rule's destinationIpAddress .
     *
     * @param string $sourcePort
     *          The acl rule's sourcePort .
     *
     * @param string $destinationPort
     *          The acl rule's destinationPort .
     *
     * @param string $position
     *          The acl rule's position .
     *
     * @param string $direction
     *          The acl rule's direction .
     *
     * @param string $action
     *           The acl rule's action .
     */
    function __construct($subnetId, $protocol, $sourceIpAddress, $destinationIpAddress, $sourcePort, $destinationPort, $position, $direction, $action, $description = null)
    {
        $this->subnetId = $subnetId;
        $this->protocol = $protocol;
        $this->sourceIpAddress = $sourceIpAddress;
        $this->destinationIpAddress = $destinationIpAddress;
        $this->sourcePort = $sourcePort;
        $this->destinationPort = $destinationPort;
        $this->position = $position;
        $this->direction = $direction;
        $this->action = $action;
        $this->description = $description;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Eip;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\Eip\model\Billing;

/**
 * This module provides a client class for EIP.
 */
class EipClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The BccClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'eip');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an eip with the specified options.
     *
     * @param int $bandwidthInMbps
     *          specify the bandwidth in Mbps
     *
     * @param string $name
     *          name of eip. The optional parameter
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function createEip($bandwidthInMbps, $name=null, $billing=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['name'] = $name;
        $body['bandwidthInMbps'] = $bandwidthInMbps;
        if (empty($billing)) {
            $billing = $this->generateDefaultBilling();
        }
        $body['billing'] = $this->objectToArray($billing);
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eip'
        );
    }

    /**
     * Resizing eip
     *
     * @param string $eip
     *          eip address to be resized
     *
     * @param int $newBandwidthInMbps
     *          specify new bandwidth in Mbps for eip
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function resizeEip($eip, $newBandwidthInMbps, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['newBandwidthInMbps'] = $newBandwidthInMbps;
        $params = array();
        $params['resize'] = null;
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eip/' . $eip
        );
    }

    /**
     * PurchaseReserved eip with fixed duration,only Prepaid eip can do this
     *
     * @param string $eip
     *          eip address to be renewed
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default reservationLength is 1
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedEip($eip, $billing=null, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($billing)) {
            $reservation = array();
            $reservation['reservationTimeUnit'] = 'Month';
            $reservation['reservationLength'] = 1;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        } else {
            $reservation = array();
            $reservation['reservationTimeUnit'] = $billing->reservation->reservationTimeUnit;
            $reservation['reservationLength'] = $billing->reservation->reservationLength;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        }
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['purchaseReserved'] = null;
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eip/' . $eip
        );
    }

    /**
     * bind the eip to a specified instanceId and instanceType
     *
     * @param string $eip
     *          eip address to be bound
     *
     * @param string $instanceType
     *          type of instance to be bound(BCC BLB et.)
     *
     * @param string $instanceId
     *          id of instance to be bound
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function bindEip($eip, $instanceType, $instanceId, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $body['instanceType'] = $instanceType;
        $body['instanceId'] = $instanceId;
        $params = array();
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['bind'] = '';
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eip/' . $eip
        );
    }

    /**
     * unbind the eip from a specified instance
     *
     * @param string $eip
     *          eip address to be unbound
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function unbindEip($eip, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['unbind'] = '';
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eip/' . $eip
        );
    }

    /**
     * release the eip(delete operation)
     * Only the Postpaid instance or Prepaid which is expired can be released.
     * if the eip has been bound, must unbind before releasing.
     *
     * @param string $eip
     *          eip address to be released
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function releaseEip($eip, $clientToken=null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params = array();
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eip/' . $eip
        );
    }

    /**
     * get a list of eip owned by the authenticated user and specified conditions.
     * we can Also get a single eip function  through this interface by eip condition
     *
     * @param string $eip
     *          eip address condition
     *
     * @param string $instanceType
     *          bound instance type condition
     *
     * @param string $instanceId
     *          bound instance id condition
     *          if query by the instanceId or instanceType condition,
     *          must provides both of them at the same time
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipClient instance.
     *
     * @return mixed
     */
    public function listEips($eip=null, $instanceType=null, $instanceId=null, $marker=null, $maxKeys=1000,
                                $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($eip !== null) {
            $params['eip'] = $eip;
        }
        if ($instanceType !== null) {
            $params['instanceType'] = $instanceType;
        }
        if ($instanceId !== null) {
            $params['instanceId'] = $instanceId;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eip'
        );
    }

    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The method to generate a default Billing which is Postpaid.
     *
     * @return Billing object with Postpaid PaymentTiming.
     */
    private function generateDefaultBilling() {
        return new Billing('Postpaid', 'ByBandwidth');
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Eip\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct($reservationLength, $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Eip\model;

class Billing
{
    var $paymentTiming;
    var $billingMethod;
    var $reservation;

    /**
     * Billing information.
     *
     * @param string $paymentTiming
     *          The pay time of the payment, default value 'Postpaid'
     *
     * @param string $billingMethod
     *          The way of eip charging, default value 'ByBandwidth'
     *
     * @param int $reservationLength
     *          purchase length
     *
     * @param string $reservationTimeUnit
     *          time unit of purchasing,default 'Month'
     */
    function __construct($paymentTiming='Postpaid', $billingMethod='ByBandwidth', $reservationLength=null, $reservationTimeUnit='Month')
    {
        if ($paymentTiming !== null) {
            $this->paymentTiming = $paymentTiming;
        }
        $this->billingMethod = $billingMethod;
        $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
    }
}<?php
/*
* Copyright 2018 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/


namespace BaiduBce\Services\EipGroup;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Services\EipGroup\model\Billing;

/**
 * This module provides a client class for EipGroupClient.
 */
class EipGroupClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The EipGroupClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'eipgroup');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an EipGroup with the specified options.
     *
     * @param int $bandwidthInMbps
     *          specify the bandwidth in Mbps
     *
     * @param int eipCount
     *          specify the eip count in EipGroup
     *
     * @param string $name
     *          name of EipGroup. The optional parameter
     *
     * @param Billing $billing
     *          billing information. The optional parameter, default paymentTiming is Postpaid
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function createEipGroup($bandwidthInMbps, $eipCount, $billing, $name = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($bandwidthInMbps)) {
            throw new \InvalidArgumentException(
                'request $bandwidthInMbps  should not be empty .'
            );
        }
        if (empty($eipCount)) {
            throw new \InvalidArgumentException(
                'request $eipCount  should not be empty .'
            );
        }
        if (empty($billing)) {
            throw new \InvalidArgumentException(
                'request $billing  should not be empty .'
            );
        }
        $body['name'] = $name;
        $body['eipCount'] = $eipCount;
        $body['bandwidthInMbps'] = $bandwidthInMbps;
        $body['billing'] = $this->objectToArray($billing);
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/eipgroup'
        );
    }

    /**
     * Resizing EipGroup
     *
     * @param string id
     *          EipGroup's id to be resized
     *
     * @param int bandwidthInMbps
     *          specify new bandwidth in Mbps for EipGroup
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function resizeEipGroupForBandWidth($id, $bandwidthInMbps, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($id)) {
            throw new \InvalidArgumentException(
                'request $id  should not be empty .'
            );
        }
        if (empty($bandwidthInMbps)) {
            throw new \InvalidArgumentException(
                'request $bandwidthInMbps  should not be empty .'
            );
        }
        $body['bandwidthInMbps'] = $bandwidthInMbps;

        $params['resize'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipgroup/' . $id
        );
    }

    /**
     * Resizing EipGroup
     *
     * @param string id
     *          EipGroup's id to be resized
     *
     * @param int eipAddCount
     *          specify the added counts for EipGroup.The eipAddCount must greater than 0.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function resizeEipGroupForEipCount($id, $eipAddCount, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if (empty($id)) {
            throw new \InvalidArgumentException(
                'request $id  should not be empty .'
            );
        }
        if (empty($eipAddCount)) {
            throw new \InvalidArgumentException(
                'request $eipAddCount  should not be empty .'
            );
        }
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        $body['eipAddCount'] = $eipAddCount;
        $params['resize'] = null;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipgroup/' . $id
        );
    }


    /**
     * update EipGroup
     *
     * @param string $id
     *          EipGroup's id to be updated
     *
     * @param string $name
     *          specify the new name EipGroup.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function updateEipGroup($id, $name, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        $body = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        if (empty($id)) {
            throw new \InvalidArgumentException(
                'request $id  should not be empty .'
            );
        }
        if (empty($name)) {
            throw new \InvalidArgumentException(
                'request $name  should not be empty .'
            );
        }
        $params['update'] = null;
        $body['name'] = $name;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
                'params' => $params,
            ),
            '/eipgroup/' . $id
        );
    }

    /**
     * PurchaseReserved EipGroup with fixed duration
     *
     * @param string $id
     *          EipGroup's id to be renewed
     *
     * @param Billing $billing
     *          billing information.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function purchaseReservedEipGroup($id, $billing, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        $params = array();
        if (empty($id)) {
            throw new \InvalidArgumentException(
                'request $id  should not be empty .'
            );
        }
        if (empty($billing)) {
            throw new \InvalidArgumentException(
                'request $billing  should not be empty .'
            );
        } else {
            $reservation = array();
            $reservation['reservationTimeUnit'] = $billing->reservation->reservationTimeUnit;
            $reservation['reservationLength'] = $billing->reservation->reservationLength;
            $billingBody = array();
            $billingBody['reservation'] = $reservation;
            $body['billing'] = $billingBody;
        }
        if (empty($clientToken)) {
            $clientToken = $this->generateClientToken();
        }
        $params['purchaseReserved'] = null;
        $params['clientToken'] = $clientToken;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eipgroup/' . $id
        );
    }


    /**
     * get a list of EipGroup owned by the authenticated user and specified conditions.
     * we can Also get a single EipGroup function  through this interface by EipGroup condition
     *
     * @param string $id
     *          EipGroup's id condition
     *
     * @param string $name
     *          EipGroup name condition
     *
     * @param string $status
     *          EipGroup instance status condition
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function listEipGroups($id = null, $name = null, $status = null, $marker = null, $maxKeys = 1000,
                                  $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($id !== null) {
            $params['id'] = $id;
        }
        if ($name !== null) {
            $params['name'] = $name;
        }
        if ($status !== null) {
            $params['status'] = $status;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eipgroup'
        );
    }

    /**
     * get a detail of the EipGroup which you specified  .
     *
     * @param string $id
     *          EipGroup's id condition
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipGroupClient instance.
     *
     * @return mixed
     */
    public function getEipGroup($id, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if (empty($id)) {
            throw new \InvalidArgumentException(
                'request $id  should not be empty .'
            );
        }
        $params['id'] = $id;
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eipgroup'
        );
    }


    /**
     * convert object to array
     *
     * @param object $obj
     *
     * @return array
     */
    function objectToArray($obj)
    {
        if (is_array($obj)) {
            return $obj;
        }
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        $arr = array();
        foreach ($_arr as $key => $value) {
            $value = (is_array($value)) || is_object($value) ? $this->objectToArray($value) : $value;
            $arr[$key] = $value;
        }
        return $arr;
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */

    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The method to generate a default Billing which is Postpaid.
     *
     * @return Billing object with Postpaid PaymentTiming.
     */
    private function generateDefaultBilling()
    {
        return new Billing('Postpaid', 'ByBandwidth');
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}<?php
/*
* Copyright 2018 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\EipGroup\model;

class Reservation
{
    var $reservationLength;
    var $reservationTimeUnit;

    /**
     * Reservation constructor.
     *
     * @param int $reservationLength
     * @param string $reservationTimeUnit
     */
    function __construct($reservationLength, $reservationTimeUnit)
    {
        $this->reservationLength = $reservationLength;
        $this->reservationTimeUnit = $reservationTimeUnit;
    }
}<?php
/*
* Copyright 2017 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\EipGroup\model;

class Billing
{
    var $paymentTiming;
    var $reservation;

    /**
     * Billing information.
     *
     * @param string $paymentTiming
     *          The pay time of the payment
     *
     *
     * @param int $reservationLength
     *          purchase length
     *
     * @param string $reservationTimeUnit
     *          time unit of purchasing,default 'Month'
     */
    function __construct($paymentTiming = null, $reservationLength = null, $reservationTimeUnit = 'Month')
    {
        if ($paymentTiming !== null) {
            $this->paymentTiming = $paymentTiming;
        }
        $this->reservation = new Reservation($reservationLength, $reservationTimeUnit);
    }
}<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Sts;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Util\HttpUtils;

class StsClient extends BceBaseClient
{
    const STS_URL_PREFIX = "/";
    const GET_SESSION_TOKEN_VERSION = "v1";
    const GET_SESSION_TOKEN_PATH = "sessionToken";
	
    /**
     * @var \BaiduBce\Auth\SignerInterface
     */
    private $signer;
    private $httpClient;
    private $stsEndpoint;

    /**
     * The StsClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'sts');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
        $this->stsEndpoint = $config['stsEndpoint'];
    }
	
    /**
     * Get STS session token
     * @param mixed $options The optional bce configuration, which will overwrite the
     *   default configuration that was passed while creating StsClient instance.
     * @return object the server response.
     */
    public function getSessionToken($options = array())
    {
        list($config, $acl, $durationSeconds) =
            $this->parseOptions(
                $options,
                'config',
                'acl',
                'durationSeconds'
            );
		
        $params = array();
        if ($durationSeconds !== null) {
            $params['durationSeconds'] = $durationSeconds;
        }
        $headers = array();
        if ($acl !== null) {
            $headers[HttpHeaders::CONTENT_LENGTH] = strlen($acl);
        } else {
            $headers[HttpHeaders::CONTENT_LENGTH] = 0;
        }
        $headers[HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        // prevent low version curl add a default pragma:no-cache
        $headers[HttpHeaders::PRAGMA] = '';
        $config['endpoint'] = $this->stsEndpoint;
        $config = array_merge(
            $this->config,
            $config
        );
        $path = HttpUtils::appendUri(StsClient::STS_URL_PREFIX, StsClient::GET_SESSION_TOKEN_VERSION, StsClient::GET_SESSION_TOKEN_PATH);

        $response = $this->httpClient->sendRequest(
            $config,
            HttpMethod::POST,
            $path,
            $acl,
            $headers,
            $params,
            $this->signer
        );
		
        return $this->parseJsonResult($response['body']);
    }
}
<?php
/*
* Copyright 2014 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\Media;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Exception\BceClientException;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpContentTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;

class MediaClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v3';

    /**
     * The MediaClient constructor
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'MediaClient');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Get the specific pipeline information
     *
     * @param string $pipelineName The pipeline name
     * @param string $jobStatus The jobStatus of the job, not filter if null
     * @param string $begin The createTime should be later than or equals with begin, not check if null
     * @param string $end The createTime should be earlier than or equals with end, not check if null
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function listJobs($pipelineName, $jobStatus = null, $begin = null, $end = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();

        if (!empty($pipelineName)) {
            $params['pipelineName'] = $pipelineName;
        } else {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }
        if (!empty($jobStatus)) {
            $params['jobStatus'] = $jobStatus;
        }
        if (!empty($begin)) {
            $params['begin'] = $begin;
        }
        if (!empty($end)) {
            $params['end'] = $end;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/job'
        );
    }

    /**
     * Create a job, a simpler api
     * @param string $pipelineName The pipeline name
     * @param string $sourceKey The source media object's key
     * @param string $targetKey The target media object's key
     *        which will be generated
     * @param string $presetName The preset name this job use
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createSimpleJob(
        $pipelineName,
        $sourceKey,
        $targetKey,
        $presetName,
        $options = array()
    ) {

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        if (empty($sourceKey)) {
            throw new BceClientException("The parameter sourceKey " 
                ."should NOT be null or empty string");
        }

        if (empty($targetKey)) {
            throw new BceClientException("The parameter targetKey " 
                ."should NOT be null or empty string");
        }

        if (empty($presetName)) {
            throw new BceClientException("The parameter presetName " 
                ."should NOT be null or empty string");
        }

        return $this->createJob(
            $pipelineName,
            array(
                'sourceKey' => $sourceKey,
            ),
            array(
                'targetKey' => $targetKey,
                'presetName' => $presetName,
            ),
            $options
        );
    }

    /**
     * Create a job
     * @param string $pipelineName The pipeline name
     * @param array $source
     *      {
     *          sourceKey: The source media object's key
     *      }
     * @param array $target
     *      {
     *          targetKey: The target media object's key
     *          presetName: Name of the preset used in the job
     *      }
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createJob(
        $pipelineName,
        array $source,
        array $target,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        if (empty($source)) {
            throw new BceClientException("The parameter source " 
                ."should NOT be null or empty string");
        }

        if (empty($target)) {
            throw new BceClientException("The parameter target " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode(array(
                    'pipelineName' => $pipelineName,
                    'source' => $source,
                    'target' => $target,
                )),
            ),
            '/job'
        );
    }

    /**
     * Get the specific job information
     *
     * @param string $jobId The job's id
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getJob($jobId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($jobId)) {
            throw new BceClientException("The parameter jobId " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/job/$jobId"
        );
    }

    /**
     * Get the information of a media object in BOS
     *
     * @param string $bucket The bucket's name in BOS
     * @param string $key The object's key in bucket
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      } 
     * @return mixed
     * @throws BceClientException
     */
    public function getMediaInfoOfFile($bucket, $key, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($bucket)) {
            throw new BceClientException("The parameter bucket " 
                ."should NOT be null or empty string");
        }

        if (empty($key)) {
            throw new BceClientException("The parameter key " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => array(
                    'bucket' => $bucket,
                    'key' => rawurlencode($key),
                ),
            ),
            '/mediainfo'
        );
    }

    /**
     * List all pipelines' information
     *
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     */
    public function listPipelines($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/pipeline'
        );
    }

    /**
     * Create a pipeline
     *
     * @param string $pipelineName The pipeline name
     * @param string $sourceBucket The input source bucket's name in BOS
     * @param string $targetBucket The output target bucket's name in BOS
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          pipelineConfig: {
     *              capacity: The capacity of pipeline
     *          }
     *          description: The description of pipeline
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createPipeline(
        $pipelineName,
        $sourceBucket,
        $targetBucket,
        $options = array()
    ) {
        list($config, $description, $pipelineConfig) = $this->parseOptions(
            $options,
            'config',
            'description',
            'pipelineConfig'
        );

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        if (empty($sourceBucket)) {
            throw new BceClientException("The parameter sourceBucket " 
                ."should NOT be null or empty string");
        }

        if (empty($targetBucket)) {
            throw new BceClientException("The parameter targetBucket " 
                ."should NOT be null or empty string");
        }

        $body = array(
            'pipelineName' => $pipelineName,
            'sourceBucket' => $sourceBucket,
            'targetBucket' => $targetBucket,
        );
        if ($description !== null) {
            $body['description'] = $description;
        } else {
            $body['description'] = '';
        }
        if ($pipelineConfig !== null) {
            $body['config'] = $pipelineConfig;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/pipeline'
        );
    }

    /**
     * update a pipeline
     *
     * @param string $pipelineName The pipeline's name
     * @param array $options Supported options:
     *      {
     *          clientConfig: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          all pipeline parameters for updating
     *      }
     * @return mixed
     * @throws BceClientException
     */

    public function updatePipeline($pipelineName, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra(
            $options,
            'clientConfig'
        );

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName "
                ."should NOT be null or empty string");
        }

        if (!empty($config)) {
            unset($options['clientConfig']);
        }

        $body = $options;
        if (array_key_exists('pipelineConfig', $body)) {
            $body['config'] = $body['pipelineConfig'];
        }

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/pipeline/$pipelineName"
        );
    }

    /**
     * Get the specific pipeline information
     *
     * @param string $pipelineName The pipeline name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getPipeline($pipelineName, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/pipeline/$pipelineName"
        );
    }

    /**
     * Delete the specific pipeline
     *
     * @param string $pipelineName The pipeline name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deletePipeline($pipelineName, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/pipeline/$pipelineName"
        );
    }

    /**
     * Create a preset
     *
     * @param string $presetName The preset's name
     * @param string $container enum(MP4, FLV, HLS, MP3, M4A)
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          description: The preset's description
     *          transmux(boolean): whether only preceed format transformation
     *          clip: {   cut the video or audio
     *              startTimeInSecond: The start time from video
     *              durationInSecond: The duration time from video in seconds
     *          }
     *          audio: {  audio preceeding set, default to be video preceeding only
     *              bitRateInBps: The target audio bit rate
     *              sampleRateInHz:
     *              channels: The number of audio's channels
     *          }
     *          video: {  video proceeding set, default to be audio preceeding only
     *              codec: H.264
     *              codecOptions: {
     *                  profile: enum(baseline, main, high)
     *              }
     *              bitRateInBps: The target video bit rate
     *              maxFrameRate: The max frame rate, enum(10,15, 23.97, 24, 25, 29.97, 30, 50, 60)
     *              maxWidthInPixel: The target video's max width in pixel, range(128, 4096)
     *              maxHeightInPixel: The target video's max height in pixel, range(96, 3072)
     *              sizingPolicy: enum(Keep, ShrinkToFit, Stretch)
     *          }
     *          encryption: {
     *              strategy: enum(Fixed)
     *              aesKey: The aes 128-bit secret key
     *          }
     *          watermarkId: watermarkId
     *      }    
     * @return mixed
     * @throws BceClientException
     */

    public function createPreset($presetName, $container, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra(
            $options,
            'config'
        );

        if (empty($presetName)) {
            throw new BceClientException("The parameter presetName " 
                ."should NOT be null or empty string");
        }

        if (empty($container)) {
            throw new BceClientException("The parameter container " 
                ."should NOT be null or empty string");
        }

        if (!empty($config)) {
            unset($options['config']);
        }
        $body = $options;
        $body['presetName'] = $presetName;
        $body['container'] = $container;

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/preset'
        );
    }

    /**
     * update a preset
     *
     * @param string $presetName The preset's name
     * @param array $options the preset for updating
     * @return mixed
     * @throws BceClientException
     */

    public function updatePreset($presetName, $options = array())
    {
        list($config) = $this->parseOptionsIgnoreExtra(
            $options,
            'config'
        );

        if (empty($presetName)) {
            throw new BceClientException("The parameter presetName "
                ."should NOT be null or empty string");
        }

        if (!empty($config)) {
            unset($options['config']);
        }
        $body = $options;

        return $this->sendRequest(
            HttpMethod::PUT,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            "/preset/$presetName"
        );
    }

    /**
     * Get the specific preset information
     *
     * @param string $presetName The preset's name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getPreset($presetName, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($presetName)) {
            throw new BceClientException("The parameter presetName " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/preset/$presetName"
        );
    }

    /**
     * List information of all presets
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     */
    public function listPresets($options = array())
    {

        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/preset'
        );
    }

    /**
     * Delete the specific preset
     *
     * @param string $presetName The preset's name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */

    public function deletePreset($presetName, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($presetName)) {
            throw new BceClientException("The parameter presetName "
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/preset/$presetName"
        );
    }

    /**
     * Create a job of generating thumbnail
     * 
     * @param string $pipelineName the pipeline name
     * @param array $source
     *      {
     *          key: The source media object's key
     *      }
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          target: { The target thumbnail info set
     *              keyPrefix: Prefix of the target thumbnail
     *              format: Target thumbnail file format, enum(jpg, png), only jpg is supported now
     *              sizingPolicy: enum(keep, shrinkToFit, stretch)
     *              widthInPixel: The target thumbnail width in pixel
     *              heightInPixel: The target thumbnail height in pixel
     *          }
     *          capture: { The rules to generate the thumbnail
     *              mode: enum(auto, manual)
     *              startTimeInSecond: The start time
     *              endTimeInSecond: The end time
     *              intervalInSecond: The time interval
     *          }
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createThumbnailJob($pipelineName, array $source, $options = array()) {
        list($config, $target, $capture) = $this->parseOptions(
            $options,
            'config',
            'target',
            'capture'
        );

        if (empty($pipelineName)) {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }

        if (empty($source)) {
            throw new BceClientException("The parameter source " 
                ."should NOT be null or empty string");
        }
        
        $body = array(
            'pipelineName' => $pipelineName,
            'source' => $source,
        );

        if ($target !== null) {
            $body['target'] = $target;
        }
        if ($capture !== null) {
            $body['capture'] = $capture;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/job/thumbnail'
        );
    }


    /**
     * Get a thumbnail
     * 
     * @param string $jobId The thumbnail job id
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getThumbnailJob($jobId, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($jobId)) {
            throw new BceClientException("The parameter jobId " 
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/job/thumbnail/$jobId"
        );
    }

    /**
     * Get thumbnail jobs
     * 
     * @param string $pipelineName The pipeline name
     * @param string $jobStatus The jobStatus of the thumbnail job, not filter if null
     * @param string $begin The createTime should be later than or equals with begin, not check if null
     * @param string $end The createTime should be earlier than or equals with end, not check if null
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function listThumbnailJobsByPipelineName(
        $pipelineName,
        $jobStatus = null,
        $begin = null,
        $end = null,
        $options = array()
    ) {
        list($config) = $this->parseOptions($options, 'config');

        $params = array();
        if (!empty($pipelineName)) {
            $params['pipelineName'] = $pipelineName;
        } else {
            throw new BceClientException("The parameter pipelineName " 
                ."should NOT be null or empty string");
        }
        if (!empty($jobStatus)) {
            $params['jobStatus'] = $jobStatus;
        }
        if (!empty($begin)) {
            $params['begin'] = $begin;
        }
        if (!empty($end)) {
            $params['end'] = $end;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/job/thumbnail"
        );
    }

    /**
     * Create a watermark
     *
     * @param string $bucket The source media BOS bucket
     * @param string $key the source media object key
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *          verticalAlignment: watermark vertical alignment, enum(top, center, bottom)
     *          horizontalAlignment: watermark vertical alignment, enum(left, center, right)
     *          verticalOffsetInPixel: numeric vertical offset, 0~3072
     *          horizontalOffsetInPixel: numeric vertical offset, 0~4096
     *      }
     * @return mixed
     * @throws BceClientException
     * @since 0.8.4
     */
    public function createWatermark(
        $bucket, 
        $key,
        $options = array()
    ) {
        list(
            $config,
            $verticalAlignment,
            $horizontalAlignment,
            $verticalOffsetInPixel,
            $horizontalOffsetInPixel
        ) = $this->parseOptions(
            $options,
            'config',
            'verticalAlignment',
            'horizontalAlignment',
            'verticalOffsetInPixel',
            'horizontalOffsetInPixel'
        );

        if (empty($bucket)) {
            throw new BceClientException("The parameter bucket "
                ."should NOT be null or empty string");
        }

        if (empty($key)) {
            throw new BceClientException("The parameter key "
                ."should NOT be null or empty string");
        }

        $body = array(
            'bucket' => $bucket,
            'key' => $key,
        );
        if ($verticalAlignment !== null) {
            $body['verticalAlignment'] = $verticalAlignment;
        }
        if ($horizontalAlignment !== null) {
            $body['horizontalAlignment'] = $horizontalAlignment;
        }
        if ($verticalOffsetInPixel !== null) {
            $body['verticalOffsetInPixel'] = $verticalOffsetInPixel;
        }
        if ($horizontalOffsetInPixel !== null) {
            $body['horizontalOffsetInPixel'] = $horizontalOffsetInPixel;
        }

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/watermark'
        );
    }

    /**
     * Get a watermark
     * 
     * @param string $watermarkId The watermark id
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getWatermark($watermarkId, $options = array()) {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($watermarkId)) {
            throw new BceClientException("The parameter watermarkId "
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/watermark/$watermarkId"
        );
    }

    /**
     * Get watermarks
     *
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     */
    public function listWatermarks($options = array()) {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/watermark"
        );
    }


    /**
     * Delete the specific watermark
     *
     * @param string $watermarkId The watermark Id
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */

    public function deleteWatermark($watermarkId, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($watermarkId)) {
            throw new BceClientException("The parameter watermarkId "
                ."should NOT be null or empty string");
        }
        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/watermark/$watermarkId"
        );
    }

    /**
     * Create HttpClient and send request
     * @param string $httpMethod The Http request method
     * @param array $varArgs The extra arguments
     * @param string $requestPath The Http request uri
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);
        $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
        return $result;
    }

    /**
     * List all notifications' information
     *
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     */
    public function listNotifications($options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            '/notification'
        );
    }

    /**
     * Create a notification
     *
     * @param string $name The notification name
     * @param string $endpoint The notification endpoint
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function createNotification(
        $name,
        $endpoint,
        $options = array()
    ) {
        list($config) = $this->parseOptions(
            $options,
            'config'
        );

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                ."should NOT be null or empty string");
        }

        if (empty($endpoint)) {
            throw new BceClientException("The parameter endpoint "
                ."should NOT be null or empty string");
        }

        $body = array(
            'name' => $name,
            'endpoint' => $endpoint,
        );
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'body' => json_encode($body),
            ),
            '/notification'
        );
    }

    /**
     * Get the specific notification information
     *
     * @param string $name The notification name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function getNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }

    /**
     * Delete the specific notification
     *
     * @param string $name The notification name
     * @param array $options Supported options:
     *      {
     *          config: The optional bce configuration, which will overwrite the
     *                  default client configuration that was passed in constructor.
     *      }
     * @return mixed
     * @throws BceClientException
     */
    public function deleteNotification($name, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');

        if (empty($name)) {
            throw new BceClientException("The parameter name "
                ."should NOT be null or empty string");
        }

        return $this->sendRequest(
            HttpMethod::DELETE,
            array(
                'config' => $config,
            ),
            "/notification/$name"
        );
    }
}
(���Q�]
��T���CՊ��GBMB